blob: 5bcbaf4275df312b9d439573e173972deb794700 [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 Kastenb28686f2012-01-06 08:39:38 -08001130 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001131 mDevice(device),
1132 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133{
1134}
1135
1136AudioFlinger::ThreadBase::~ThreadBase()
1137{
1138 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001139 // do not lock the mutex in destructor
1140 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001141 if (mPowerManager != 0) {
1142 sp<IBinder> binder = mPowerManager->asBinder();
1143 binder->unlinkToDeath(mDeathRecipient);
1144 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145}
1146
1147void AudioFlinger::ThreadBase::exit()
1148{
Steve Block3856b092011-10-20 11:56:00 +01001149 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001151 // This lock prevents the following race in thread (uniprocessor for illustration):
1152 // if (!exitPending()) {
1153 // // context switch from here to exit()
1154 // // exit() calls requestExit(), what exitPending() observes
1155 // // exit() calls signal(), which is dropped since no waiters
1156 // // context switch back from exit() to here
1157 // mWaitWorkCV.wait(...);
1158 // // now thread is hung
1159 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001160 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 requestExit();
1162 mWaitWorkCV.signal();
1163 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001164 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1165 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 requestExitAndWait();
1167}
1168
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1170{
1171 status_t status;
1172
Steve Block3856b092011-10-20 11:56:00 +01001173 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 Mutex::Autolock _l(mLock);
1175
1176 mNewParameters.add(keyValuePairs);
1177 mWaitWorkCV.signal();
1178 // wait condition with timeout in case the thread loop has exited
1179 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001180 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181 status = mParamStatus;
1182 mWaitWorkCV.signal();
1183 } else {
1184 status = TIMED_OUT;
1185 }
1186 return status;
1187}
1188
1189void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1190{
1191 Mutex::Autolock _l(mLock);
1192 sendConfigEvent_l(event, param);
1193}
1194
1195// sendConfigEvent_l() must be called with ThreadBase::mLock held
1196void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1197{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001198 ConfigEvent configEvent;
1199 configEvent.mEvent = event;
1200 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 mWaitWorkCV.signal();
1204}
1205
1206void AudioFlinger::ThreadBase::processConfigEvents()
1207{
1208 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001209 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001210 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001211 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001212 mConfigEvents.removeAt(0);
1213 // release mLock before locking AudioFlinger mLock: lock order is always
1214 // AudioFlinger then ThreadBase to avoid cross deadlock
1215 mLock.unlock();
1216 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001217 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 mLock.lock();
1220 }
1221 mLock.unlock();
1222}
1223
1224status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1225{
1226 const size_t SIZE = 256;
1227 char buffer[SIZE];
1228 String8 result;
1229
1230 bool locked = tryLock(mLock);
1231 if (!locked) {
1232 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1233 write(fd, buffer, strlen(buffer));
1234 }
1235
Eric Laurent612bbb52012-03-14 15:03:26 -07001236 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1237 result.append(buffer);
1238 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1239 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1241 result.append(buffer);
1242 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1243 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001244 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1245 result.append(buffer);
1246 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 result.append(buffer);
1248 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1249 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001250 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1251 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1253 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001254 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 result.append(buffer);
1256
1257 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1258 result.append(buffer);
1259 result.append(" Index Command");
1260 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1261 snprintf(buffer, SIZE, "\n %02d ", i);
1262 result.append(buffer);
1263 result.append(mNewParameters[i]);
1264 }
1265
1266 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1267 result.append(buffer);
1268 snprintf(buffer, SIZE, " Index event param\n");
1269 result.append(buffer);
1270 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001271 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 result.append(buffer);
1273 }
1274 result.append("\n");
1275
1276 write(fd, result.string(), result.size());
1277
1278 if (locked) {
1279 mLock.unlock();
1280 }
1281 return NO_ERROR;
1282}
1283
Eric Laurent1d2bff02011-07-24 17:49:51 -07001284status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1285{
1286 const size_t SIZE = 256;
1287 char buffer[SIZE];
1288 String8 result;
1289
1290 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1291 write(fd, buffer, strlen(buffer));
1292
1293 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1294 sp<EffectChain> chain = mEffectChains[i];
1295 if (chain != 0) {
1296 chain->dump(fd, args);
1297 }
1298 }
1299 return NO_ERROR;
1300}
1301
Eric Laurentfeb0db62011-07-22 09:04:31 -07001302void AudioFlinger::ThreadBase::acquireWakeLock()
1303{
1304 Mutex::Autolock _l(mLock);
1305 acquireWakeLock_l();
1306}
1307
1308void AudioFlinger::ThreadBase::acquireWakeLock_l()
1309{
1310 if (mPowerManager == 0) {
1311 // use checkService() to avoid blocking if power service is not up yet
1312 sp<IBinder> binder =
1313 defaultServiceManager()->checkService(String16("power"));
1314 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001315 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001316 } else {
1317 mPowerManager = interface_cast<IPowerManager>(binder);
1318 binder->linkToDeath(mDeathRecipient);
1319 }
1320 }
1321 if (mPowerManager != 0) {
1322 sp<IBinder> binder = new BBinder();
1323 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1324 binder,
1325 String16(mName));
1326 if (status == NO_ERROR) {
1327 mWakeLockToken = binder;
1328 }
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001330 }
1331}
1332
1333void AudioFlinger::ThreadBase::releaseWakeLock()
1334{
1335 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001336 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001337}
1338
1339void AudioFlinger::ThreadBase::releaseWakeLock_l()
1340{
1341 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001342 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001343 if (mPowerManager != 0) {
1344 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1345 }
1346 mWakeLockToken.clear();
1347 }
1348}
1349
1350void AudioFlinger::ThreadBase::clearPowerManager()
1351{
1352 Mutex::Autolock _l(mLock);
1353 releaseWakeLock_l();
1354 mPowerManager.clear();
1355}
1356
1357void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1358{
1359 sp<ThreadBase> thread = mThread.promote();
1360 if (thread != 0) {
1361 thread->clearPowerManager();
1362 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001363 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001364}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001365
Eric Laurent59255e42011-07-27 19:49:51 -07001366void AudioFlinger::ThreadBase::setEffectSuspended(
1367 const effect_uuid_t *type, bool suspend, int sessionId)
1368{
1369 Mutex::Autolock _l(mLock);
1370 setEffectSuspended_l(type, suspend, sessionId);
1371}
1372
1373void AudioFlinger::ThreadBase::setEffectSuspended_l(
1374 const effect_uuid_t *type, bool suspend, int sessionId)
1375{
Glenn Kasten090f0192012-01-30 13:00:02 -08001376 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001377 if (chain != 0) {
1378 if (type != NULL) {
1379 chain->setEffectSuspended_l(type, suspend);
1380 } else {
1381 chain->setEffectSuspendedAll_l(suspend);
1382 }
1383 }
1384
1385 updateSuspendedSessions_l(type, suspend, sessionId);
1386}
1387
1388void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1389{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001390 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001391 if (index < 0) {
1392 return;
1393 }
1394
1395 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1396 mSuspendedSessions.editValueAt(index);
1397
1398 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001399 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001400 for (int j = 0; j < desc->mRefCount; j++) {
1401 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1402 chain->setEffectSuspendedAll_l(true);
1403 } else {
Steve Block3856b092011-10-20 11:56:00 +01001404 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001405 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001406 chain->setEffectSuspended_l(&desc->mType, true);
1407 }
1408 }
1409 }
1410}
1411
Eric Laurent59255e42011-07-27 19:49:51 -07001412void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1413 bool suspend,
1414 int sessionId)
1415{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001416 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001417
1418 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1419
1420 if (suspend) {
1421 if (index >= 0) {
1422 sessionEffects = mSuspendedSessions.editValueAt(index);
1423 } else {
1424 mSuspendedSessions.add(sessionId, sessionEffects);
1425 }
1426 } else {
1427 if (index < 0) {
1428 return;
1429 }
1430 sessionEffects = mSuspendedSessions.editValueAt(index);
1431 }
1432
1433
1434 int key = EffectChain::kKeyForSuspendAll;
1435 if (type != NULL) {
1436 key = type->timeLow;
1437 }
1438 index = sessionEffects.indexOfKey(key);
1439
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001440 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001441 if (suspend) {
1442 if (index >= 0) {
1443 desc = sessionEffects.valueAt(index);
1444 } else {
1445 desc = new SuspendedSessionDesc();
1446 if (type != NULL) {
1447 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1448 }
1449 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001450 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001451 }
1452 desc->mRefCount++;
1453 } else {
1454 if (index < 0) {
1455 return;
1456 }
1457 desc = sessionEffects.valueAt(index);
1458 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001459 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001460 sessionEffects.removeItemsAt(index);
1461 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001463 sessionId);
1464 mSuspendedSessions.removeItem(sessionId);
1465 }
1466 }
1467 }
1468 if (!sessionEffects.isEmpty()) {
1469 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1470 }
1471}
1472
1473void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1474 bool enabled,
1475 int sessionId)
1476{
1477 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001478 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1479}
Eric Laurent59255e42011-07-27 19:49:51 -07001480
Eric Laurenta85a74a2011-10-19 11:44:54 -07001481void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1482 bool enabled,
1483 int sessionId)
1484{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001485 if (mType != RECORD) {
1486 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1487 // another session. This gives the priority to well behaved effect control panels
1488 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001489 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1490 // global effects
1491 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001492 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1493 }
1494 }
Eric Laurent59255e42011-07-27 19:49:51 -07001495
1496 sp<EffectChain> chain = getEffectChain_l(sessionId);
1497 if (chain != 0) {
1498 chain->checkSuspendOnEffectEnabled(effect, enabled);
1499 }
1500}
1501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502// ----------------------------------------------------------------------------
1503
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001504AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1505 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001506 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001507 uint32_t device,
1508 type_t type)
1509 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001510 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1511 // Assumes constructor is called by AudioFlinger with it's mLock held,
1512 // but it would be safer to explicitly pass initial masterMute as parameter
1513 mMasterMute(audioFlinger->masterMute_l()),
1514 // mStreamTypes[] initialized in constructor body
1515 mOutput(output),
1516 // Assumes constructor is called by AudioFlinger with it's mLock held,
1517 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001518 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001519 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001520 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001521 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001522 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001523 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001524 // index 0 is reserved for normal mixer's submix
1525 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526{
Glenn Kasten480b4682012-02-28 12:30:08 -08001527 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001528
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 readOutputParameters();
1530
Glenn Kasten263709e2012-01-06 08:40:01 -08001531 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001532 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1533 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1534 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001535 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1536 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001538 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1539 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540}
1541
1542AudioFlinger::PlaybackThread::~PlaybackThread()
1543{
1544 delete [] mMixBuffer;
1545}
1546
1547status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1548{
1549 dumpInternals(fd, args);
1550 dumpTracks(fd, args);
1551 dumpEffectChains(fd, args);
1552 return NO_ERROR;
1553}
1554
1555status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1556{
1557 const size_t SIZE = 256;
1558 char buffer[SIZE];
1559 String8 result;
1560
Glenn Kasten58912562012-04-03 10:45:00 -07001561 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1562 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1563 const stream_type_t *st = &mStreamTypes[i];
1564 if (i > 0) {
1565 result.appendFormat(", ");
1566 }
1567 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1568 if (st->mute) {
1569 result.append("M");
1570 }
1571 }
1572 result.append("\n");
1573 write(fd, result.string(), result.length());
1574 result.clear();
1575
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1577 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001578 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 for (size_t i = 0; i < mTracks.size(); ++i) {
1580 sp<Track> track = mTracks[i];
1581 if (track != 0) {
1582 track->dump(buffer, SIZE);
1583 result.append(buffer);
1584 }
1585 }
1586
1587 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1588 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001589 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001591 sp<Track> track = mActiveTracks[i].promote();
1592 if (track != 0) {
1593 track->dump(buffer, SIZE);
1594 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 }
1596 }
1597 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001598
1599 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1600 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1601 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1602 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1603
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 return NO_ERROR;
1605}
1606
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1608{
1609 const size_t SIZE = 256;
1610 char buffer[SIZE];
1611 String8 result;
1612
1613 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1614 result.append(buffer);
1615 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1616 result.append(buffer);
1617 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1618 result.append(buffer);
1619 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1620 result.append(buffer);
1621 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1622 result.append(buffer);
1623 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1624 result.append(buffer);
1625 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1626 result.append(buffer);
1627 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001628 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629
1630 dumpBase(fd, args);
1631
1632 return NO_ERROR;
1633}
1634
1635// Thread virtuals
1636status_t AudioFlinger::PlaybackThread::readyToRun()
1637{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001638 status_t status = initCheck();
1639 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001640 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001641 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001642 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001644 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645}
1646
1647void AudioFlinger::PlaybackThread::onFirstRef()
1648{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001649 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650}
1651
1652// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001653sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001655 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001657 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001658 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 int frameCount,
1660 const sp<IMemory>& sharedBuffer,
1661 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001662 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001663 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 status_t *status)
1665{
1666 sp<Track> track;
1667 status_t lStatus;
1668
Glenn Kasten73d22752012-03-19 13:38:30 -07001669 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1670
1671 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001672 if (flags & IAudioFlinger::TRACK_FAST) {
1673 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001674 // not timed
1675 (!isTimed) &&
1676 // either of these use cases:
1677 (
1678 // use case 1: shared buffer with any frame count
1679 (
1680 (sharedBuffer != 0)
1681 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001683 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001684 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001685 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001686 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001687 )
1688 ) &&
1689 // PCM data
1690 audio_is_linear_pcm(format) &&
1691 // mono or stereo
1692 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1693 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001694#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001695 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001696 (sampleRate == mSampleRate) &&
1697#endif
1698 // normal mixer has an associated fast mixer
1699 hasFastMixer() &&
1700 // there are sufficient fast track slots available
1701 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001702 // FIXME test that MixerThread for this fast track has a capable output HAL
1703 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001705 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1706 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001707 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001708 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001709 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001710 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001711 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001712 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001713 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1714 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1715 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1716 audio_is_linear_pcm(format),
1717 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001718 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001719 // For compatibility with AudioTrack calculation, buffer depth is forced
1720 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1721 // This is probably too conservative, but legacy application code may depend on it.
1722 // If you change this calculation, also review the start threshold which is related.
1723 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1724 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1725 if (minBufCount < 2) {
1726 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001727 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001728 int minFrameCount = mNormalFrameCount * minBufCount;
1729 if (frameCount < minFrameCount) {
1730 frameCount = minFrameCount;
1731 }
1732 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001733 }
1734
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001736 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1737 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001738 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001739 "for output %p with format %d",
1740 sampleRate, format, channelMask, mOutput, mFormat);
1741 lStatus = BAD_VALUE;
1742 goto Exit;
1743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 }
1745 } else {
1746 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1747 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001748 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 lStatus = BAD_VALUE;
1750 goto Exit;
1751 }
1752 }
1753
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001754 lStatus = initCheck();
1755 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001756 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 goto Exit;
1758 }
1759
1760 { // scope for mLock
1761 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001762
1763 // all tracks in same audio session must share the same routing strategy otherwise
1764 // conflicts will happen when tracks are moved from one output to another by audio policy
1765 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001766 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001767 for (size_t i = 0; i < mTracks.size(); ++i) {
1768 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001769 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001770 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001771 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001772 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001773 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001774 lStatus = BAD_VALUE;
1775 goto Exit;
1776 }
1777 }
1778 }
1779
John Grossman4ff14ba2012-02-08 16:37:41 -08001780 if (!isTimed) {
1781 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001782 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001783 } else {
1784 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1785 channelMask, frameCount, sharedBuffer, sessionId);
1786 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001787 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 lStatus = NO_MEMORY;
1789 goto Exit;
1790 }
1791 mTracks.add(track);
1792
1793 sp<EffectChain> chain = getEffectChain_l(sessionId);
1794 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001795 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001797 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001798 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 }
1800 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001801
Glenn Kasten3acbd052012-02-28 10:39:56 -08001802 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1803 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1804 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1805 // so ask activity manager to do this on our behalf
1806 int err = requestPriority(callingPid, tid, 1);
1807 if (err != 0) {
1808 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1809 1, callingPid, tid, err);
1810 }
1811 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001812
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 lStatus = NO_ERROR;
1814
1815Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001816 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 *status = lStatus;
1818 }
1819 return track;
1820}
1821
Eric Laurente737cda2012-05-22 18:55:44 -07001822uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1823{
1824 if (mFastMixer != NULL) {
1825 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1826 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1827 }
1828 return latency;
1829}
1830
1831uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1832{
1833 return latency;
1834}
1835
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836uint32_t AudioFlinger::PlaybackThread::latency() const
1837{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001838 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001839 return latency_l();
1840}
1841uint32_t AudioFlinger::PlaybackThread::latency_l() const
1842{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001843 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001844 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001845 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 return 0;
1847 }
1848}
1849
Glenn Kasten6637baa2012-01-09 09:40:36 -08001850void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001852 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854}
1855
Glenn Kasten6637baa2012-01-09 09:40:36 -08001856void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001858 Mutex::Autolock _l(mLock);
1859 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860}
1861
Glenn Kasten6637baa2012-01-09 09:40:36 -08001862void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001864 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866}
1867
Glenn Kasten6637baa2012-01-09 09:40:36 -08001868void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001870 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872}
1873
Glenn Kastenfff6d712012-01-12 16:38:12 -08001874float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001876 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 return mStreamTypes[stream].volume;
1878}
1879
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880// addTrack_l() must be called with ThreadBase::mLock held
1881status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1882{
1883 status_t status = ALREADY_EXISTS;
1884
1885 // set retry count for buffer fill
1886 track->mRetryCount = kMaxTrackStartupRetries;
1887 if (mActiveTracks.indexOf(track) < 0) {
1888 // the track is newly added, make sure it fills up all its
1889 // buffers before playing. This is to ensure the client will
1890 // effectively get the latency it requested.
1891 track->mFillingUpStatus = Track::FS_FILLING;
1892 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001893 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 mActiveTracks.add(track);
1895 if (track->mainBuffer() != mMixBuffer) {
1896 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1897 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001898 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001899 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 }
1901 }
1902
1903 status = NO_ERROR;
1904 }
1905
Steve Block3856b092011-10-20 11:56:00 +01001906 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 mWaitWorkCV.broadcast();
1908
1909 return status;
1910}
1911
1912// destroyTrack_l() must be called with ThreadBase::mLock held
1913void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1914{
1915 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001916 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001918 removeTrack_l(track);
1919 }
1920}
1921
1922void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1923{
Eric Laurent29864602012-05-08 18:57:51 -07001924 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001925 mTracks.remove(track);
1926 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001927 // redundant as track is about to be destroyed, for dumpsys only
1928 track->mName = -1;
1929 if (track->isFastTrack()) {
1930 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001931 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001932 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1933 mFastTrackAvailMask |= 1 << index;
1934 // redundant as track is about to be destroyed, for dumpsys only
1935 track->mFastIndex = -1;
1936 }
Eric Laurentb469b942011-05-09 12:09:06 -07001937 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1938 if (chain != 0) {
1939 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 }
1941}
1942
1943String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1944{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001945 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001946 char *s;
1947
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001948 Mutex::Autolock _l(mLock);
1949 if (initCheck() != NO_ERROR) {
1950 return out_s8;
1951 }
1952
Dima Zavin799a70e2011-04-18 16:57:27 -07001953 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001954 out_s8 = String8(s);
1955 free(s);
1956 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957}
1958
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001959// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1961 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001962 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963
Steve Block3856b092011-10-20 11:56:00 +01001964 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965
1966 switch (event) {
1967 case AudioSystem::OUTPUT_OPENED:
1968 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001969 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 desc.samplingRate = mSampleRate;
1971 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001972 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 desc.latency = latency();
1974 param2 = &desc;
1975 break;
1976
1977 case AudioSystem::STREAM_CONFIG_CHANGED:
1978 param2 = &param;
1979 case AudioSystem::OUTPUT_CLOSED:
1980 default:
1981 break;
1982 }
1983 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1984}
1985
1986void AudioFlinger::PlaybackThread::readOutputParameters()
1987{
Dima Zavin799a70e2011-04-18 16:57:27 -07001988 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001989 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1990 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001991 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001992 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001993 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001994 if (mFrameCount & 15) {
1995 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1996 mFrameCount);
1997 }
1998
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001999 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002000 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002001 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002002 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002003 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2004 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2005 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2006 maxNormalFrameCount = maxNormalFrameCount & ~15;
2007 if (maxNormalFrameCount < minNormalFrameCount) {
2008 maxNormalFrameCount = minNormalFrameCount;
2009 }
2010 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2011 if (multiplier <= 1.0) {
2012 multiplier = 1.0;
2013 } else if (multiplier <= 2.0) {
2014 if (2 * mFrameCount <= maxNormalFrameCount) {
2015 multiplier = 2.0;
2016 } else {
2017 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2018 }
2019 } else {
2020 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2021 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2022 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2023 // FIXME this rounding up should not be done if no HAL SRC
2024 uint32_t truncMult = (uint32_t) multiplier;
2025 if ((truncMult & 1)) {
2026 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2027 ++truncMult;
2028 }
2029 }
2030 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002031 }
Glenn Kasten58912562012-04-03 10:45:00 -07002032 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002033 mNormalFrameCount = multiplier * mFrameCount;
2034 // round up to nearest 16 frames to satisfy AudioMixer
2035 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002036 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037
Glenn Kastene9dd0172012-01-27 18:08:45 -08002038 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002039 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2040 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041
Eric Laurentde070132010-07-13 04:45:46 -07002042 // force reconfiguration of effect chains and engines to take new buffer size and audio
2043 // parameters into account
2044 // Note that mLock is not held when readOutputParameters() is called from the constructor
2045 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2046 // matter.
2047 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2048 Vector< sp<EffectChain> > effectChains = mEffectChains;
2049 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002050 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002051 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052}
2053
Eric Laurente737cda2012-05-22 18:55:44 -07002054
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2056{
Glenn Kastena0d68332012-01-27 16:47:15 -08002057 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 return BAD_VALUE;
2059 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002060 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002061 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 return INVALID_OPERATION;
2063 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002064 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065
Dima Zavin799a70e2011-04-18 16:57:27 -07002066 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067}
2068
Eric Laurent39e94f82010-07-28 01:32:47 -07002069uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070{
2071 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002072 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002074 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 }
2076
2077 for (size_t i = 0; i < mTracks.size(); ++i) {
2078 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002079 if (sessionId == track->sessionId() &&
2080 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002081 result |= TRACK_SESSION;
2082 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 }
2084 }
2085
Eric Laurent39e94f82010-07-28 01:32:47 -07002086 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087}
2088
Eric Laurentde070132010-07-13 04:45:46 -07002089uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2090{
Dima Zavinfce7a472011-04-19 22:30:36 -07002091 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002092 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002093 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2094 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002095 }
2096 for (size_t i = 0; i < mTracks.size(); i++) {
2097 sp<Track> track = mTracks[i];
2098 if (sessionId == track->sessionId() &&
2099 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002100 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002101 }
2102 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002103 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002104}
2105
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106
Glenn Kastenaed850d2012-01-26 09:46:34 -08002107AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002108{
2109 Mutex::Autolock _l(mLock);
2110 return mOutput;
2111}
2112
2113AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2114{
2115 Mutex::Autolock _l(mLock);
2116 AudioStreamOut *output = mOutput;
2117 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002118 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2119 // must push a NULL and wait for ack
2120 mOutputSink.clear();
2121 mPipeSink.clear();
2122 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002123 return output;
2124}
2125
2126// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002127audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002128{
2129 if (mOutput == NULL) {
2130 return NULL;
2131 }
2132 return &mOutput->stream->common;
2133}
2134
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002135uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002136{
Eric Laurentab9071b2012-06-04 13:45:29 -07002137 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002138}
2139
Eric Laurenta011e352012-03-29 15:51:43 -07002140status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2141{
2142 if (!isValidSyncEvent(event)) {
2143 return BAD_VALUE;
2144 }
2145
2146 Mutex::Autolock _l(mLock);
2147
2148 for (size_t i = 0; i < mTracks.size(); ++i) {
2149 sp<Track> track = mTracks[i];
2150 if (event->triggerSession() == track->sessionId()) {
2151 track->setSyncEvent(event);
2152 return NO_ERROR;
2153 }
2154 }
2155
2156 return NAME_NOT_FOUND;
2157}
2158
2159bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2160{
2161 switch (event->type()) {
2162 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2163 return true;
2164 default:
2165 break;
2166 }
2167 return false;
2168}
2169
Eric Laurent44a957f2012-05-15 15:26:05 -07002170void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2171{
2172 size_t count = tracksToRemove.size();
2173 if (CC_UNLIKELY(count)) {
2174 for (size_t i = 0 ; i < count ; i++) {
2175 const sp<Track>& track = tracksToRemove.itemAt(i);
2176 if ((track->sharedBuffer() != 0) &&
2177 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2178 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2179 }
2180 }
2181 }
2182
2183}
2184
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185// ----------------------------------------------------------------------------
2186
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002187AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002188 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002189 : PlaybackThread(audioFlinger, output, id, device, type),
2190 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002191 // mFastMixer below
2192 mFastMixerFutex(0)
2193 // mOutputSink below
2194 // mPipeSink below
2195 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196{
Glenn Kasten58912562012-04-03 10:45:00 -07002197 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2198 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2199 "mFrameCount=%d, mNormalFrameCount=%d",
2200 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2201 mNormalFrameCount);
2202 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2203
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 // FIXME - Current mixer implementation only supports stereo output
2205 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002206 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 }
Glenn Kasten58912562012-04-03 10:45:00 -07002208
2209 // create an NBAIO sink for the HAL output stream, and negotiate
2210 mOutputSink = new AudioStreamOutSink(output->stream);
2211 size_t numCounterOffers = 0;
2212 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2213 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2214 ALOG_ASSERT(index == 0);
2215
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002216 // initialize fast mixer depending on configuration
2217 bool initFastMixer;
2218 switch (kUseFastMixer) {
2219 case FastMixer_Never:
2220 initFastMixer = false;
2221 break;
2222 case FastMixer_Always:
2223 initFastMixer = true;
2224 break;
2225 case FastMixer_Static:
2226 case FastMixer_Dynamic:
2227 initFastMixer = mFrameCount < mNormalFrameCount;
2228 break;
2229 }
2230 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002231
2232 // create a MonoPipe to connect our submix to FastMixer
2233 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002234 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2235 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2236 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2237 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002238 const NBAIO_Format offers[1] = {format};
2239 size_t numCounterOffers = 0;
2240 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2241 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002242 monoPipe->setAvgFrames((mScreenState & 1) ?
2243 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002244 mPipeSink = monoPipe;
2245
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002246#ifdef TEE_SINK_FRAMES
2247 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2248 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2249 numCounterOffers = 0;
2250 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2251 ALOG_ASSERT(index == 0);
2252 mTeeSink = teeSink;
2253 PipeReader *teeSource = new PipeReader(*teeSink);
2254 numCounterOffers = 0;
2255 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2256 ALOG_ASSERT(index == 0);
2257 mTeeSource = teeSource;
2258#endif
2259
Glenn Kasten58912562012-04-03 10:45:00 -07002260 // create fast mixer and configure it initially with just one fast track for our submix
2261 mFastMixer = new FastMixer();
2262 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002263#ifdef STATE_QUEUE_DUMP
2264 sq->setObserverDump(&mStateQueueObserverDump);
2265 sq->setMutatorDump(&mStateQueueMutatorDump);
2266#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002267 FastMixerState *state = sq->begin();
2268 FastTrack *fastTrack = &state->mFastTracks[0];
2269 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2270 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2271 fastTrack->mVolumeProvider = NULL;
2272 fastTrack->mGeneration++;
2273 state->mFastTracksGen++;
2274 state->mTrackMask = 1;
2275 // fast mixer will use the HAL output sink
2276 state->mOutputSink = mOutputSink.get();
2277 state->mOutputSinkGen++;
2278 state->mFrameCount = mFrameCount;
2279 state->mCommand = FastMixerState::COLD_IDLE;
2280 // already done in constructor initialization list
2281 //mFastMixerFutex = 0;
2282 state->mColdFutexAddr = &mFastMixerFutex;
2283 state->mColdGen++;
2284 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002285 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002286 sq->end();
2287 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2288
2289 // start the fast mixer
2290 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002291 pid_t tid = mFastMixer->getTid();
2292 int err = requestPriority(getpid_cached, tid, 2);
2293 if (err != 0) {
2294 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2295 2, getpid_cached, tid, err);
2296 }
Glenn Kasten58912562012-04-03 10:45:00 -07002297
Glenn Kastenc15d6652012-05-30 14:52:57 -07002298#ifdef AUDIO_WATCHDOG
2299 // create and start the watchdog
2300 mAudioWatchdog = new AudioWatchdog();
2301 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2302 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2303 tid = mAudioWatchdog->getTid();
2304 err = requestPriority(getpid_cached, tid, 1);
2305 if (err != 0) {
2306 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2307 1, getpid_cached, tid, err);
2308 }
2309#endif
2310
Glenn Kasten58912562012-04-03 10:45:00 -07002311 } else {
2312 mFastMixer = NULL;
2313 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002314
2315 switch (kUseFastMixer) {
2316 case FastMixer_Never:
2317 case FastMixer_Dynamic:
2318 mNormalSink = mOutputSink;
2319 break;
2320 case FastMixer_Always:
2321 mNormalSink = mPipeSink;
2322 break;
2323 case FastMixer_Static:
2324 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2325 break;
2326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327}
2328
2329AudioFlinger::MixerThread::~MixerThread()
2330{
Glenn Kasten58912562012-04-03 10:45:00 -07002331 if (mFastMixer != NULL) {
2332 FastMixerStateQueue *sq = mFastMixer->sq();
2333 FastMixerState *state = sq->begin();
2334 if (state->mCommand == FastMixerState::COLD_IDLE) {
2335 int32_t old = android_atomic_inc(&mFastMixerFutex);
2336 if (old == -1) {
2337 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2338 }
2339 }
2340 state->mCommand = FastMixerState::EXIT;
2341 sq->end();
2342 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2343 mFastMixer->join();
2344 // Though the fast mixer thread has exited, it's state queue is still valid.
2345 // We'll use that extract the final state which contains one remaining fast track
2346 // corresponding to our sub-mix.
2347 state = sq->begin();
2348 ALOG_ASSERT(state->mTrackMask == 1);
2349 FastTrack *fastTrack = &state->mFastTracks[0];
2350 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2351 delete fastTrack->mBufferProvider;
2352 sq->end(false /*didModify*/);
2353 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002354 if (mAudioWatchdog != 0) {
2355 mAudioWatchdog->requestExit();
2356 mAudioWatchdog->requestExitAndWait();
2357 mAudioWatchdog.clear();
2358 }
Glenn Kasten58912562012-04-03 10:45:00 -07002359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 delete mAudioMixer;
2361}
2362
Glenn Kasten83efdd02012-02-24 07:21:32 -08002363class CpuStats {
2364public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002365 CpuStats();
2366 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002367#ifdef DEBUG_CPU_USAGE
2368private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002369 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2370 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2371
2372 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2373
2374 int mCpuNum; // thread's current CPU number
2375 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002376#endif
2377};
2378
Glenn Kasten190a46f2012-03-06 11:27:10 -08002379CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002380#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002381 : mCpuNum(-1), mCpukHz(-1)
2382#endif
2383{
2384}
2385
2386void CpuStats::sample(const String8 &title) {
2387#ifdef DEBUG_CPU_USAGE
2388 // get current thread's delta CPU time in wall clock ns
2389 double wcNs;
2390 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2391
2392 // record sample for wall clock statistics
2393 if (valid) {
2394 mWcStats.sample(wcNs);
2395 }
2396
2397 // get the current CPU number
2398 int cpuNum = sched_getcpu();
2399
2400 // get the current CPU frequency in kHz
2401 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2402
2403 // check if either CPU number or frequency changed
2404 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2405 mCpuNum = cpuNum;
2406 mCpukHz = cpukHz;
2407 // ignore sample for purposes of cycles
2408 valid = false;
2409 }
2410
2411 // if no change in CPU number or frequency, then record sample for cycle statistics
2412 if (valid && mCpukHz > 0) {
2413 double cycles = wcNs * cpukHz * 0.000001;
2414 mHzStats.sample(cycles);
2415 }
2416
2417 unsigned n = mWcStats.n();
2418 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002419 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002420 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002421 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2422 double perLoop = elapsed / (double) n;
2423 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002424 double perLoop1k = perLoop * 0.001;
2425 double mean = mWcStats.mean();
2426 double stddev = mWcStats.stddev();
2427 double minimum = mWcStats.minimum();
2428 double maximum = mWcStats.maximum();
2429 double meanCycles = mHzStats.mean();
2430 double stddevCycles = mHzStats.stddev();
2431 double minCycles = mHzStats.minimum();
2432 double maxCycles = mHzStats.maximum();
2433 mCpuUsage.resetElapsed();
2434 mWcStats.reset();
2435 mHzStats.reset();
2436 ALOGD("CPU usage for %s over past %.1f secs\n"
2437 " (%u mixer loops at %.1f mean ms per loop):\n"
2438 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2439 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2440 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2441 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002442 elapsed * .000000001, n, perLoop * .000001,
2443 mean * .001,
2444 stddev * .001,
2445 minimum * .001,
2446 maximum * .001,
2447 mean / perLoop100,
2448 stddev / perLoop100,
2449 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002450 maximum / perLoop100,
2451 meanCycles / perLoop1k,
2452 stddevCycles / perLoop1k,
2453 minCycles / perLoop1k,
2454 maxCycles / perLoop1k);
2455
Glenn Kasten83efdd02012-02-24 07:21:32 -08002456 }
2457 }
2458#endif
2459};
2460
Glenn Kasten37d825e2012-02-24 07:21:48 -08002461void AudioFlinger::PlaybackThread::checkSilentMode_l()
2462{
2463 if (!mMasterMute) {
2464 char value[PROPERTY_VALUE_MAX];
2465 if (property_get("ro.audio.silent", value, "0") > 0) {
2466 char *endptr;
2467 unsigned long ul = strtoul(value, &endptr, 0);
2468 if (*endptr == '\0' && ul != 0) {
2469 ALOGD("Silence is golden");
2470 // The setprop command will not allow a property to be changed after
2471 // the first time it is set, so we don't have to worry about un-muting.
2472 setMasterMute_l(true);
2473 }
2474 }
2475 }
2476}
2477
Glenn Kasten000f0e32012-03-01 17:10:56 -08002478bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479{
2480 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002481
Glenn Kasten000f0e32012-03-01 17:10:56 -08002482 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002483
2484 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002486
Glenn Kasten000f0e32012-03-01 17:10:56 -08002487 // DUPLICATING
2488 // FIXME could this be made local to while loop?
2489 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002490
Glenn Kasten66fcab92012-02-24 14:59:21 -08002491 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002492 sleepTime = idleSleepTime;
2493
2494if (mType == MIXER) {
2495 sleepTimeShift = 0;
2496}
2497
Glenn Kasten83efdd02012-02-24 07:21:32 -08002498 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002499 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500
Eric Laurentfeb0db62011-07-22 09:04:31 -07002501 acquireWakeLock();
2502
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 while (!exitPending())
2504 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002505 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002506
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002507 Vector< sp<EffectChain> > effectChains;
2508
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 processConfigEvents();
2510
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 { // scope for mLock
2512
2513 Mutex::Autolock _l(mLock);
2514
2515 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002516 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 }
2518
Glenn Kastenfa26a852012-03-06 11:28:04 -08002519 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002522 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002523 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525
2526 threadLoop_standby();
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 mStandby = true;
2529 mBytesWritten = 0;
2530 }
2531
Glenn Kasten3e074702012-02-28 18:40:35 -08002532 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 // we're about to wait, flush the binder command buffer
2534 IPCThreadState::self()->flushCommands();
2535
Glenn Kastenfa26a852012-03-06 11:28:04 -08002536 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002537
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 if (exitPending()) break;
2539
Eric Laurentfeb0db62011-07-22 09:04:31 -07002540 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002542 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002544 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002545 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546
Eric Laurentda747442012-04-25 18:53:13 -07002547 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002548 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002549
Glenn Kasten37d825e2012-02-24 07:21:48 -08002550 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551
Glenn Kasten000f0e32012-03-01 17:10:56 -08002552 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002554 if (mType == MIXER) {
2555 sleepTimeShift = 0;
2556 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002557
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 continue;
2559 }
2560 }
2561
Glenn Kasten81028042012-04-30 18:15:12 -07002562 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002563 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564
2565 // prevent any changes in effect chain list and in each effect chain
2566 // during mixing and effect process as the audio buffers could be deleted
2567 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002568 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570
Glenn Kastenfec279f2012-03-08 07:47:15 -08002571 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002572 threadLoop_mix();
2573 } else {
2574 threadLoop_sleepTime();
2575 }
2576
2577 if (mSuspended > 0) {
2578 sleepTime = suspendSleepTimeUs();
2579 }
2580
2581 // only process effects if we're going to write
2582 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002583 for (size_t i = 0; i < effectChains.size(); i ++) {
2584 effectChains[i]->process_l();
2585 }
2586 }
2587
2588 // enable changes in effect chain
2589 unlockEffectChains(effectChains);
2590
2591 // sleepTime == 0 means we must write to audio hardware
2592 if (sleepTime == 0) {
2593
2594 threadLoop_write();
2595
2596if (mType == MIXER) {
2597 // write blocked detection
2598 nsecs_t now = systemTime();
2599 nsecs_t delta = now - mLastWriteTime;
2600 if (!mStandby && delta > maxPeriod) {
2601 mNumDelayedWrites++;
2602 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002603#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002604 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002605#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002606 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2607 ns2ms(delta), mNumDelayedWrites, this);
2608 lastWarning = now;
2609 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002610 }
2611}
2612
2613 mStandby = false;
2614 } else {
2615 usleep(sleepTime);
2616 }
2617
Glenn Kasten58912562012-04-03 10:45:00 -07002618 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002619 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002620 // same lock. This will also mutate and push a new fast mixer state.
2621 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002622 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002623
Glenn Kastenfa26a852012-03-06 11:28:04 -08002624 // FIXME I don't understand the need for this here;
2625 // it was in the original code but maybe the
2626 // assignment in saveOutputTracks() makes this unnecessary?
2627 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002628
2629 // Effect chains will be actually deleted here if they were removed from
2630 // mEffectChains list during mixing or effects processing
2631 effectChains.clear();
2632
2633 // FIXME Note that the above .clear() is no longer necessary since effectChains
2634 // is now local to this block, but will keep it for now (at least until merge done).
2635 }
2636
2637if (mType == MIXER || mType == DIRECT) {
2638 // put output stream into standby mode
2639 if (!mStandby) {
2640 mOutput->stream->common.standby(&mOutput->stream->common);
2641 }
2642}
2643if (mType == DUPLICATING) {
2644 // for DuplicatingThread, standby mode is handled by the outputTracks
2645}
2646
2647 releaseWakeLock();
2648
2649 ALOGV("Thread %p type %d exiting", this, mType);
2650 return false;
2651}
2652
Glenn Kasten58912562012-04-03 10:45:00 -07002653void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2654{
Glenn Kasten58912562012-04-03 10:45:00 -07002655 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2656}
2657
2658void AudioFlinger::MixerThread::threadLoop_write()
2659{
2660 // FIXME we should only do one push per cycle; confirm this is true
2661 // Start the fast mixer if it's not already running
2662 if (mFastMixer != NULL) {
2663 FastMixerStateQueue *sq = mFastMixer->sq();
2664 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002665 if (state->mCommand != FastMixerState::MIX_WRITE &&
2666 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002667 if (state->mCommand == FastMixerState::COLD_IDLE) {
2668 int32_t old = android_atomic_inc(&mFastMixerFutex);
2669 if (old == -1) {
2670 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2671 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002672 if (mAudioWatchdog != 0) {
2673 mAudioWatchdog->resume();
2674 }
Glenn Kasten58912562012-04-03 10:45:00 -07002675 }
2676 state->mCommand = FastMixerState::MIX_WRITE;
2677 sq->end();
2678 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002679 if (kUseFastMixer == FastMixer_Dynamic) {
2680 mNormalSink = mPipeSink;
2681 }
Glenn Kasten58912562012-04-03 10:45:00 -07002682 } else {
2683 sq->end(false /*didModify*/);
2684 }
2685 }
2686 PlaybackThread::threadLoop_write();
2687}
2688
Glenn Kasten000f0e32012-03-01 17:10:56 -08002689// shared by MIXER and DIRECT, overridden by DUPLICATING
2690void AudioFlinger::PlaybackThread::threadLoop_write()
2691{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002692 // FIXME rewrite to reduce number of system calls
2693 mLastWriteTime = systemTime();
2694 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002695 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002696
Eric Laurent67c0a582012-05-01 19:31:12 -07002697 // If an NBAIO sink is present, use it to write the normal mixer's submix
2698 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002699#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002700 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002701#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002702 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002703#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002704 // update the setpoint when gScreenState changes
2705 uint32_t screenState = gScreenState;
2706 if (screenState != mScreenState) {
2707 mScreenState = screenState;
2708 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2709 if (pipe != NULL) {
2710 pipe->setAvgFrames((mScreenState & 1) ?
2711 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2712 }
2713 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002714 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002715#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002716 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002717#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002718 if (framesWritten > 0) {
2719 bytesWritten = framesWritten << mBitShift;
2720 } else {
2721 bytesWritten = framesWritten;
2722 }
2723 // otherwise use the HAL / AudioStreamOut directly
2724 } else {
2725 // Direct output thread.
2726 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002727 }
2728
Eric Laurent67c0a582012-05-01 19:31:12 -07002729 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002730 mNumWrites++;
2731 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002732}
2733
Glenn Kasten58912562012-04-03 10:45:00 -07002734void AudioFlinger::MixerThread::threadLoop_standby()
2735{
2736 // Idle the fast mixer if it's currently running
2737 if (mFastMixer != NULL) {
2738 FastMixerStateQueue *sq = mFastMixer->sq();
2739 FastMixerState *state = sq->begin();
2740 if (!(state->mCommand & FastMixerState::IDLE)) {
2741 state->mCommand = FastMixerState::COLD_IDLE;
2742 state->mColdFutexAddr = &mFastMixerFutex;
2743 state->mColdGen++;
2744 mFastMixerFutex = 0;
2745 sq->end();
2746 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2747 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002748 if (kUseFastMixer == FastMixer_Dynamic) {
2749 mNormalSink = mOutputSink;
2750 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002751 if (mAudioWatchdog != 0) {
2752 mAudioWatchdog->pause();
2753 }
Glenn Kasten58912562012-04-03 10:45:00 -07002754 } else {
2755 sq->end(false /*didModify*/);
2756 }
2757 }
2758 PlaybackThread::threadLoop_standby();
2759}
2760
Glenn Kasten000f0e32012-03-01 17:10:56 -08002761// shared by MIXER and DIRECT, overridden by DUPLICATING
2762void AudioFlinger::PlaybackThread::threadLoop_standby()
2763{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002764 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2765 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002766}
2767
2768void AudioFlinger::MixerThread::threadLoop_mix()
2769{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002770 // obtain the presentation timestamp of the next output buffer
2771 int64_t pts;
2772 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002773
Glenn Kasten952eeb22012-03-06 11:30:57 -08002774 if (NULL != mOutput->stream->get_next_write_timestamp) {
2775 status = mOutput->stream->get_next_write_timestamp(
2776 mOutput->stream, &pts);
2777 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002778
Glenn Kasten952eeb22012-03-06 11:30:57 -08002779 if (status != NO_ERROR) {
2780 pts = AudioBufferProvider::kInvalidPTS;
2781 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002782
Glenn Kasten952eeb22012-03-06 11:30:57 -08002783 // mix buffers...
2784 mAudioMixer->process(pts);
2785 // increase sleep time progressively when application underrun condition clears.
2786 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2787 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2788 // such that we would underrun the audio HAL.
2789 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2790 sleepTimeShift--;
2791 }
2792 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002793 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002795}
2796
2797void AudioFlinger::MixerThread::threadLoop_sleepTime()
2798{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002799 // If no tracks are ready, sleep once for the duration of an output
2800 // buffer size, then write 0s to the output
2801 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002802 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002803 sleepTime = activeSleepTime >> sleepTimeShift;
2804 if (sleepTime < kMinThreadSleepTimeUs) {
2805 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002807 // reduce sleep time in case of consecutive application underruns to avoid
2808 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2809 // duration we would end up writing less data than needed by the audio HAL if
2810 // the condition persists.
2811 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2812 sleepTimeShift++;
2813 }
2814 } else {
2815 sleepTime = idleSleepTime;
2816 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002817 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 memset (mMixBuffer, 0, mixBufferSize);
2819 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002820 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002821 }
2822 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823}
2824
2825// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002826AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002827 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828{
2829
Glenn Kasten29c23c32012-01-26 13:37:52 -08002830 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002832 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 size_t mixedTracks = 0;
2834 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002835 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002836 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002837 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838
2839 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002840 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841
Eric Laurent571d49c2010-08-11 05:20:11 -07002842 if (masterMute) {
2843 masterVolume = 0;
2844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002846 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002848 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002849 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 masterVolume = (float)((v + (1 << 23)) >> 24);
2851 chain.clear();
2852 }
2853
Glenn Kasten288ed212012-04-25 17:52:27 -07002854 // prepare a new state to push
2855 FastMixerStateQueue *sq = NULL;
2856 FastMixerState *state = NULL;
2857 bool didModify = false;
2858 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2859 if (mFastMixer != NULL) {
2860 sq = mFastMixer->sq();
2861 state = sq->begin();
2862 }
2863
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002865 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 if (t == 0) continue;
2867
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002868 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002870
Glenn Kasten288ed212012-04-25 17:52:27 -07002871 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002872 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002873
2874 // It's theoretically possible (though unlikely) for a fast track to be created
2875 // and then removed within the same normal mix cycle. This is not a problem, as
2876 // the track never becomes active so it's fast mixer slot is never touched.
2877 // The converse, of removing an (active) track and then creating a new track
2878 // at the identical fast mixer slot within the same normal mix cycle,
2879 // is impossible because the slot isn't marked available until the end of each cycle.
2880 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002881 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2882 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002883 FastTrack *fastTrack = &state->mFastTracks[j];
2884
2885 // Determine whether the track is currently in underrun condition,
2886 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002887 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2888 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002889 uint32_t recentFull = (underruns.mBitFields.mFull -
2890 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2891 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2892 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2893 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2894 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2895 uint32_t recentUnderruns = recentPartial + recentEmpty;
2896 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002897 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002898 // or stopped which can occur when flush() is called while active
2899 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002900 track->mUnderrunCount += recentUnderruns;
2901 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002902
Glenn Kastend08f48c2012-05-01 18:14:02 -07002903 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002904 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002905 bool isActive = true;
2906 switch (track->mState) {
2907 case TrackBase::STOPPING_1:
2908 // track stays active in STOPPING_1 state until first underrun
2909 if (recentUnderruns > 0) {
2910 track->mState = TrackBase::STOPPING_2;
2911 }
2912 break;
2913 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002914 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002915 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002916 break;
2917 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002918 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002919 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002920 break;
2921 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002922 if (recentFull > 0 || recentPartial > 0) {
2923 // track has provided at least some frames recently: reset retry count
2924 track->mRetryCount = kMaxTrackRetries;
2925 }
2926 if (recentUnderruns == 0) {
2927 // no recent underruns: stay active
2928 break;
2929 }
2930 // there has recently been an underrun of some kind
2931 if (track->sharedBuffer() == 0) {
2932 // were any of the recent underruns "empty" (no frames available)?
2933 if (recentEmpty == 0) {
2934 // no, then ignore the partial underruns as they are allowed indefinitely
2935 break;
2936 }
2937 // there has recently been an "empty" underrun: decrement the retry counter
2938 if (--(track->mRetryCount) > 0) {
2939 break;
2940 }
2941 // indicate to client process that the track was disabled because of underrun;
2942 // it will then automatically call start() when data is available
2943 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2944 // remove from active list, but state remains ACTIVE [confusing but true]
2945 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002946 break;
2947 }
2948 // fall through
2949 case TrackBase::STOPPING_2:
2950 case TrackBase::PAUSED:
2951 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002952 case TrackBase::STOPPED:
2953 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002954 // Check for presentation complete if track is inactive
2955 // We have consumed all the buffers of this track.
2956 // This would be incomplete if we auto-paused on underrun
2957 {
2958 size_t audioHALFrames =
2959 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2960 size_t framesWritten =
2961 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2962 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2963 // track stays in active list until presentation is complete
2964 break;
2965 }
2966 }
2967 if (track->isStopping_2()) {
2968 track->mState = TrackBase::STOPPED;
2969 }
2970 if (track->isStopped()) {
2971 // Can't reset directly, as fast mixer is still polling this track
2972 // track->reset();
2973 // So instead mark this track as needing to be reset after push with ack
2974 resetMask |= 1 << i;
2975 }
2976 isActive = false;
2977 break;
2978 case TrackBase::IDLE:
2979 default:
2980 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002981 }
2982
2983 if (isActive) {
2984 // was it previously inactive?
2985 if (!(state->mTrackMask & (1 << j))) {
2986 ExtendedAudioBufferProvider *eabp = track;
2987 VolumeProvider *vp = track;
2988 fastTrack->mBufferProvider = eabp;
2989 fastTrack->mVolumeProvider = vp;
2990 fastTrack->mSampleRate = track->mSampleRate;
2991 fastTrack->mChannelMask = track->mChannelMask;
2992 fastTrack->mGeneration++;
2993 state->mTrackMask |= 1 << j;
2994 didModify = true;
2995 // no acknowledgement required for newly active tracks
2996 }
2997 // cache the combined master volume and stream type volume for fast mixer; this
2998 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2999 track->mCachedVolume = track->isMuted() ?
3000 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3001 ++fastTracks;
3002 } else {
3003 // was it previously active?
3004 if (state->mTrackMask & (1 << j)) {
3005 fastTrack->mBufferProvider = NULL;
3006 fastTrack->mGeneration++;
3007 state->mTrackMask &= ~(1 << j);
3008 didModify = true;
3009 // If any fast tracks were removed, we must wait for acknowledgement
3010 // because we're about to decrement the last sp<> on those tracks.
3011 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003012 } else {
3013 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003014 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003015 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003016 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003017 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003018 }
3019 continue;
3020 }
3021
3022 { // local variable scope to avoid goto warning
3023
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 audio_track_cblk_t* cblk = track->cblk();
3025
3026 // The first time a track is added we wait
3027 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003028 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003029 // make sure that we have enough frames to mix one full buffer.
3030 // enforce this condition only once to enable draining the buffer in case the client
3031 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003032 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003033 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003034 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003035 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003036 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003037 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003038 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003039 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003040 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003041 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003042 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003043 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003044 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3045 // the minimum track buffer size is normally twice the number of frames necessary
3046 // to fill one buffer and the resampler should not leave more than one buffer worth
3047 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003048 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003049 }
3050 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003051 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 !track->isPaused() && !track->isTerminated())
3053 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003054 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055
3056 mixedTracks++;
3057
3058 // track->mainBuffer() != mMixBuffer means there is an effect chain
3059 // connected to the track
3060 chain.clear();
3061 if (track->mainBuffer() != mMixBuffer) {
3062 chain = getEffectChain_l(track->sessionId());
3063 // Delegate volume control to effect in track effect chain if needed
3064 if (chain != 0) {
3065 tracksWithEffect++;
3066 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003067 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003068 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 }
3070 }
3071
3072
3073 int param = AudioMixer::VOLUME;
3074 if (track->mFillingUpStatus == Track::FS_FILLED) {
3075 // no ramp for the first volume setting
3076 track->mFillingUpStatus = Track::FS_ACTIVE;
3077 if (track->mState == TrackBase::RESUMING) {
3078 track->mState = TrackBase::ACTIVE;
3079 param = AudioMixer::RAMP_VOLUME;
3080 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003081 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 } else if (cblk->server != 0) {
3083 // If the track is stopped before the first frame was mixed,
3084 // do not apply ramp
3085 param = AudioMixer::RAMP_VOLUME;
3086 }
3087
3088 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003089 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003090 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003091 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003092 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 if (track->isPausing()) {
3094 track->setPaused();
3095 }
3096 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003097
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003099 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003101 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003102 vl = vlr & 0xFFFF;
3103 vr = vlr >> 16;
3104 // track volumes come from shared memory, so can't be trusted and must be clamped
3105 if (vl > MAX_GAIN_INT) {
3106 ALOGV("Track left volume out of range: %04X", vl);
3107 vl = MAX_GAIN_INT;
3108 }
3109 if (vr > MAX_GAIN_INT) {
3110 ALOGV("Track right volume out of range: %04X", vr);
3111 vr = MAX_GAIN_INT;
3112 }
3113 // now apply the master volume and stream type volume
3114 vl = (uint32_t)(v * vl) << 12;
3115 vr = (uint32_t)(v * vr) << 12;
3116 // assuming master volume and stream type volume each go up to 1.0,
3117 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118
Glenn Kasten05632a52012-01-03 14:22:33 -08003119 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3120 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003121 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003122 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003123 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003124 }
3125 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003127 // Delegate volume control to effect in track effect chain if needed
3128 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3129 // Do not ramp volume if volume is controlled by effect
3130 param = AudioMixer::VOLUME;
3131 track->mHasVolumeController = true;
3132 } else {
3133 // force no volume ramp when volume controller was just disabled or removed
3134 // from effect chain to avoid volume spike
3135 if (track->mHasVolumeController) {
3136 param = AudioMixer::VOLUME;
3137 }
3138 track->mHasVolumeController = false;
3139 }
3140
3141 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003142 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003143 vl = (vl + (1 << 11)) >> 12;
3144 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3145 vr = (vr + (1 << 11)) >> 12;
3146 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003147
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003148 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 -07003149
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003151 mAudioMixer->setBufferProvider(name, track);
3152 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003154 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3155 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3156 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003158 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 AudioMixer::TRACK,
3160 AudioMixer::FORMAT, (void *)track->format());
3161 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003162 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003164 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003166 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 AudioMixer::RESAMPLE,
3168 AudioMixer::SAMPLE_RATE,
3169 (void *)(cblk->sampleRate));
3170 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003171 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 AudioMixer::TRACK,
3173 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3174 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003175 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 AudioMixer::TRACK,
3177 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3178
3179 // reset retry count
3180 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003181
Eric Laurent27741442012-01-17 19:20:12 -08003182 // If one track is ready, set the mixer ready if:
3183 // - the mixer was not ready during previous round OR
3184 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003185 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003186 mixerStatus != MIXER_TRACKS_ENABLED) {
3187 mixerStatus = MIXER_TRACKS_READY;
3188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003190 // clear effect chain input buffer if an active track underruns to avoid sending
3191 // previous audio buffer again to effects
3192 chain = getEffectChain_l(track->sessionId());
3193 if (chain != 0) {
3194 chain->clearInputBuffer();
3195 }
3196
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003197 //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 -07003198 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3199 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 // We have consumed all the buffers of this track.
3201 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003202 // TODO: use actual buffer filling status instead of latency when available from
3203 // audio HAL
3204 size_t audioHALFrames =
3205 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3206 size_t framesWritten =
3207 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3208 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003209 if (track->isStopped()) {
3210 track->reset();
3211 }
Eric Laurenta011e352012-03-29 15:51:43 -07003212 tracksToRemove->add(track);
3213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003215 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 // No buffers for this track. Give it a few chances to
3217 // fill a buffer, then remove it from active list.
3218 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003219 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003221 // indicate to client process that the track was disabled because of underrun;
3222 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003223 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003224 // If one track is not ready, mark the mixer also not ready if:
3225 // - the mixer was ready during previous round OR
3226 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003227 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003228 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 mixerStatus = MIXER_TRACKS_ENABLED;
3230 }
3231 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003232 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 }
Glenn Kasten58912562012-04-03 10:45:00 -07003234
3235 } // local variable scope to avoid goto warning
3236track_is_ready: ;
3237
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 }
3239
Glenn Kasten288ed212012-04-25 17:52:27 -07003240 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003241 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003242 if (didModify) {
3243 state->mFastTracksGen++;
3244 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3245 if (kUseFastMixer == FastMixer_Dynamic &&
3246 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3247 state->mCommand = FastMixerState::COLD_IDLE;
3248 state->mColdFutexAddr = &mFastMixerFutex;
3249 state->mColdGen++;
3250 mFastMixerFutex = 0;
3251 if (kUseFastMixer == FastMixer_Dynamic) {
3252 mNormalSink = mOutputSink;
3253 }
3254 // If we go into cold idle, need to wait for acknowledgement
3255 // so that fast mixer stops doing I/O.
3256 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003257 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003258 }
3259 sq->end();
3260 }
3261 if (sq != NULL) {
3262 sq->end(didModify);
3263 sq->push(block);
3264 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003265 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3266 mAudioWatchdog->pause();
3267 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003268
3269 // Now perform the deferred reset on fast tracks that have stopped
3270 while (resetMask != 0) {
3271 size_t i = __builtin_ctz(resetMask);
3272 ALOG_ASSERT(i < count);
3273 resetMask &= ~(1 << i);
3274 sp<Track> t = mActiveTracks[i].promote();
3275 if (t == 0) continue;
3276 Track* track = t.get();
3277 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3278 track->reset();
3279 }
Glenn Kasten58912562012-04-03 10:45:00 -07003280
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 // remove all the tracks that need to be...
3282 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003283 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 for (size_t i=0 ; i<count ; i++) {
3285 const sp<Track>& track = tracksToRemove->itemAt(i);
3286 mActiveTracks.remove(track);
3287 if (track->mainBuffer() != mMixBuffer) {
3288 chain = getEffectChain_l(track->sessionId());
3289 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003290 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003291 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 }
3293 }
3294 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003295 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 }
3297 }
3298 }
3299
3300 // mix buffer must be cleared if all tracks are connected to an
3301 // effect chain as in this case the mixer will not write to
3302 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003303 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3304 // FIXME as a performance optimization, should remember previous zero status
3305 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 }
3307
Glenn Kasten58912562012-04-03 10:45:00 -07003308 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003309 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003310 if (fastTracks > 0) {
3311 mixerStatus = MIXER_TRACKS_READY;
3312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 return mixerStatus;
3314}
3315
Glenn Kasten66fcab92012-02-24 14:59:21 -08003316/*
3317The derived values that are cached:
3318 - mixBufferSize from frame count * frame size
3319 - activeSleepTime from activeSleepTimeUs()
3320 - idleSleepTime from idleSleepTimeUs()
3321 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3322 - maxPeriod from frame count and sample rate (MIXER only)
3323
3324The parameters that affect these derived values are:
3325 - frame count
3326 - frame size
3327 - sample rate
3328 - device type: A2DP or not
3329 - device latency
3330 - format: PCM or not
3331 - active sleep time
3332 - idle sleep time
3333*/
3334
3335void AudioFlinger::PlaybackThread::cacheParameters_l()
3336{
Glenn Kasten58912562012-04-03 10:45:00 -07003337 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003338 activeSleepTime = activeSleepTimeUs();
3339 idleSleepTime = idleSleepTimeUs();
3340}
3341
Eric Laurent22167852012-06-20 12:26:32 -07003342void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343{
Steve Block3856b092011-10-20 11:56:00 +01003344 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003345 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003347
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 size_t size = mTracks.size();
3349 for (size_t i = 0; i < size; i++) {
3350 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003351 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003352 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 }
3355 }
3356}
3357
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003359int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003361 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362}
3363
3364// deleteTrackName_l() must be called with ThreadBase::mLock held
3365void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3366{
Steve Block3856b092011-10-20 11:56:00 +01003367 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 mAudioMixer->deleteTrackName(name);
3369}
3370
3371// checkForNewParameters_l() must be called with ThreadBase::mLock held
3372bool AudioFlinger::MixerThread::checkForNewParameters_l()
3373{
Glenn Kasten58912562012-04-03 10:45:00 -07003374 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3375 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 bool reconfig = false;
3377
3378 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003379
3380 if (mFastMixer != NULL) {
3381 FastMixerStateQueue *sq = mFastMixer->sq();
3382 FastMixerState *state = sq->begin();
3383 if (!(state->mCommand & FastMixerState::IDLE)) {
3384 previousCommand = state->mCommand;
3385 state->mCommand = FastMixerState::HOT_IDLE;
3386 sq->end();
3387 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3388 } else {
3389 sq->end(false /*didModify*/);
3390 }
3391 }
3392
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 status_t status = NO_ERROR;
3394 String8 keyValuePair = mNewParameters[0];
3395 AudioParameter param = AudioParameter(keyValuePair);
3396 int value;
3397
3398 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3399 reconfig = true;
3400 }
3401 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003402 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 status = BAD_VALUE;
3404 } else {
3405 reconfig = true;
3406 }
3407 }
3408 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003409 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 status = BAD_VALUE;
3411 } else {
3412 reconfig = true;
3413 }
3414 }
3415 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3416 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003417 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 // if frame count is changed after track creation
3419 if (!mTracks.isEmpty()) {
3420 status = INVALID_OPERATION;
3421 } else {
3422 reconfig = true;
3423 }
3424 }
3425 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003426#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003427 // when changing the audio output device, call addBatteryData to notify
3428 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003429 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003430 uint32_t params = 0;
3431 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003432 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003433 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3434 }
3435
3436 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003437 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003438 // check if any other device (except speaker) is on
3439 if (value & deviceWithoutSpeaker ) {
3440 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3441 }
3442
3443 if (params != 0) {
3444 addBatteryData(params);
3445 }
3446 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003447#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003448
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 // forward device change to effects that have requested to be
3450 // aware of attached audio device.
3451 mDevice = (uint32_t)value;
3452 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003453 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454 }
3455 }
3456
3457 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003458 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003459 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003461 mOutput->stream->common.standby(&mOutput->stream->common);
3462 mStandby = true;
3463 mBytesWritten = 0;
3464 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003465 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 }
3467 if (status == NO_ERROR && reconfig) {
3468 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003469 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3470 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003472 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003474 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 if (name < 0) break;
3476 mTracks[i]->mName = name;
3477 // limit track sample rate to 2 x new output sample rate
3478 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3479 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3480 }
3481 }
3482 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3483 }
3484 }
3485
3486 mNewParameters.removeAt(0);
3487
3488 mParamStatus = status;
3489 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003490 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3491 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003492 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 }
Glenn Kasten58912562012-04-03 10:45:00 -07003494
3495 if (!(previousCommand & FastMixerState::IDLE)) {
3496 ALOG_ASSERT(mFastMixer != NULL);
3497 FastMixerStateQueue *sq = mFastMixer->sq();
3498 FastMixerState *state = sq->begin();
3499 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3500 state->mCommand = previousCommand;
3501 sq->end();
3502 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3503 }
3504
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 return reconfig;
3506}
3507
3508status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3509{
3510 const size_t SIZE = 256;
3511 char buffer[SIZE];
3512 String8 result;
3513
3514 PlaybackThread::dumpInternals(fd, args);
3515
3516 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3517 result.append(buffer);
3518 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003519
3520 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3521 FastMixerDumpState copy = mFastMixerDumpState;
3522 copy.dump(fd);
3523
Glenn Kasten39993082012-05-31 13:40:27 -07003524#ifdef STATE_QUEUE_DUMP
3525 // Similar for state queue
3526 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3527 observerCopy.dump(fd);
3528 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3529 mutatorCopy.dump(fd);
3530#endif
3531
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003532 // Write the tee output to a .wav file
3533 NBAIO_Source *teeSource = mTeeSource.get();
3534 if (teeSource != NULL) {
3535 char teePath[64];
3536 struct timeval tv;
3537 gettimeofday(&tv, NULL);
3538 struct tm tm;
3539 localtime_r(&tv.tv_sec, &tm);
3540 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3541 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3542 if (teeFd >= 0) {
3543 char wavHeader[44];
3544 memcpy(wavHeader,
3545 "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",
3546 sizeof(wavHeader));
3547 NBAIO_Format format = teeSource->format();
3548 unsigned channelCount = Format_channelCount(format);
3549 ALOG_ASSERT(channelCount <= FCC_2);
3550 unsigned sampleRate = Format_sampleRate(format);
3551 wavHeader[22] = channelCount; // number of channels
3552 wavHeader[24] = sampleRate; // sample rate
3553 wavHeader[25] = sampleRate >> 8;
3554 wavHeader[32] = channelCount * 2; // block alignment
3555 write(teeFd, wavHeader, sizeof(wavHeader));
3556 size_t total = 0;
3557 bool firstRead = true;
3558 for (;;) {
3559#define TEE_SINK_READ 1024
3560 short buffer[TEE_SINK_READ * FCC_2];
3561 size_t count = TEE_SINK_READ;
3562 ssize_t actual = teeSource->read(buffer, count);
3563 bool wasFirstRead = firstRead;
3564 firstRead = false;
3565 if (actual <= 0) {
3566 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3567 continue;
3568 }
3569 break;
3570 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003571 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003572 write(teeFd, buffer, actual * channelCount * sizeof(short));
3573 total += actual;
3574 }
3575 lseek(teeFd, (off_t) 4, SEEK_SET);
3576 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3577 write(teeFd, &temp, sizeof(temp));
3578 lseek(teeFd, (off_t) 40, SEEK_SET);
3579 temp = total * channelCount * sizeof(short);
3580 write(teeFd, &temp, sizeof(temp));
3581 close(teeFd);
3582 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3583 } else {
3584 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3585 }
3586 }
3587
Glenn Kastenc15d6652012-05-30 14:52:57 -07003588 if (mAudioWatchdog != 0) {
3589 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3590 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3591 wdCopy.dump(fd);
3592 }
3593
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 return NO_ERROR;
3595}
3596
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003597uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598{
Glenn Kasten58912562012-04-03 10:45:00 -07003599 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600}
3601
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003602uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003603{
Glenn Kasten58912562012-04-03 10:45:00 -07003604 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003605}
3606
Glenn Kasten66fcab92012-02-24 14:59:21 -08003607void AudioFlinger::MixerThread::cacheParameters_l()
3608{
3609 PlaybackThread::cacheParameters_l();
3610
3611 // FIXME: Relaxed timing because of a certain device that can't meet latency
3612 // Should be reduced to 2x after the vendor fixes the driver issue
3613 // increase threshold again due to low power audio mode. The way this warning
3614 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003615 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003616}
3617
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003619AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3620 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003621 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003622 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624}
3625
3626AudioFlinger::DirectOutputThread::~DirectOutputThread()
3627{
3628}
3629
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003630AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3631 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003632)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003634 sp<Track> trackToRemove;
3635
Glenn Kastenfec279f2012-03-08 07:47:15 -08003636 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637
Glenn Kasten952eeb22012-03-06 11:30:57 -08003638 // find out which tracks need to be processed
3639 if (mActiveTracks.size() != 0) {
3640 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003641 // The track died recently
3642 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643
Glenn Kasten952eeb22012-03-06 11:30:57 -08003644 Track* const track = t.get();
3645 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646
Glenn Kasten952eeb22012-03-06 11:30:57 -08003647 // The first time a track is added we wait
3648 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003649 uint32_t minFrames;
3650 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3651 minFrames = mNormalFrameCount;
3652 } else {
3653 minFrames = 1;
3654 }
3655 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 !track->isPaused() && !track->isTerminated())
3657 {
3658 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659
Glenn Kasten952eeb22012-03-06 11:30:57 -08003660 if (track->mFillingUpStatus == Track::FS_FILLED) {
3661 track->mFillingUpStatus = Track::FS_ACTIVE;
3662 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003663 if (track->mState == TrackBase::RESUMING) {
3664 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003665 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003666 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003667
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 // compute volume for this track
3669 float left, right;
3670 if (track->isMuted() || mMasterMute || track->isPausing() ||
3671 mStreamTypes[track->streamType()].mute) {
3672 left = right = 0;
3673 if (track->isPausing()) {
3674 track->setPaused();
3675 }
3676 } else {
3677 float typeVolume = mStreamTypes[track->streamType()].volume;
3678 float v = mMasterVolume * typeVolume;
3679 uint32_t vlr = cblk->getVolumeLR();
3680 float v_clamped = v * (vlr & 0xFFFF);
3681 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3682 left = v_clamped/MAX_GAIN;
3683 v_clamped = v * (vlr >> 16);
3684 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3685 right = v_clamped/MAX_GAIN;
3686 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687
Glenn Kasten952eeb22012-03-06 11:30:57 -08003688 if (left != mLeftVolFloat || right != mRightVolFloat) {
3689 mLeftVolFloat = left;
3690 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 // Convert volumes from float to 8.24
3693 uint32_t vl = (uint32_t)(left * (1 << 24));
3694 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003695
Glenn Kasten952eeb22012-03-06 11:30:57 -08003696 // Delegate volume control to effect in track effect chain if needed
3697 // only one effect chain can be present on DirectOutputThread, so if
3698 // there is one, the track is connected to it
3699 if (!mEffectChains.isEmpty()) {
3700 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003701 mEffectChains[0]->setVolume_l(&vl, &vr);
3702 left = (float)vl / (1 << 24);
3703 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003704 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003705 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003706 }
3707
3708 // reset retry count
3709 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003710 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003711 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003713 // clear effect chain input buffer if an active track underruns to avoid sending
3714 // previous audio buffer again to effects
3715 if (!mEffectChains.isEmpty()) {
3716 mEffectChains[0]->clearInputBuffer();
3717 }
3718
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003720 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3721 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 // We have consumed all the buffers of this track.
3723 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003724 // TODO: implement behavior for compressed audio
3725 size_t audioHALFrames =
3726 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3727 size_t framesWritten =
3728 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3729 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003730 if (track->isStopped()) {
3731 track->reset();
3732 }
Eric Laurenta011e352012-03-29 15:51:43 -07003733 trackToRemove = track;
3734 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003735 } else {
3736 // No buffers for this track. Give it a few chances to
3737 // fill a buffer, then remove it from active list.
3738 if (--(track->mRetryCount) <= 0) {
3739 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3740 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003742 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743 }
3744 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 }
3746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003748 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 // remove all the tracks that need to be...
3750 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003751 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003752 mActiveTracks.remove(trackToRemove);
3753 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003754 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003755 trackToRemove->sessionId());
3756 mEffectChains[0]->decActiveTrackCnt();
3757 }
3758 if (trackToRemove->isTerminated()) {
3759 removeTrack_l(trackToRemove);
3760 }
3761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762
Glenn Kastenfec279f2012-03-08 07:47:15 -08003763 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003764}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765
Glenn Kasten000f0e32012-03-01 17:10:56 -08003766void AudioFlinger::DirectOutputThread::threadLoop_mix()
3767{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003768 AudioBufferProvider::Buffer buffer;
3769 size_t frameCount = mFrameCount;
3770 int8_t *curBuf = (int8_t *)mMixBuffer;
3771 // output audio to hardware
3772 while (frameCount) {
3773 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003774 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 if (CC_UNLIKELY(buffer.raw == NULL)) {
3776 memset(curBuf, 0, frameCount * mFrameSize);
3777 break;
3778 }
3779 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3780 frameCount -= buffer.frameCount;
3781 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003782 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003783 }
3784 sleepTime = 0;
3785 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003786 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003787
Glenn Kasten000f0e32012-03-01 17:10:56 -08003788}
3789
3790void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3791{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003792 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003793 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 sleepTime = activeSleepTime;
3795 } else {
3796 sleepTime = idleSleepTime;
3797 }
3798 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003799 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003800 sleepTime = 0;
3801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802}
3803
3804// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003805int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003806{
3807 return 0;
3808}
3809
3810// deleteTrackName_l() must be called with ThreadBase::mLock held
3811void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3812{
3813}
3814
3815// checkForNewParameters_l() must be called with ThreadBase::mLock held
3816bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3817{
3818 bool reconfig = false;
3819
3820 while (!mNewParameters.isEmpty()) {
3821 status_t status = NO_ERROR;
3822 String8 keyValuePair = mNewParameters[0];
3823 AudioParameter param = AudioParameter(keyValuePair);
3824 int value;
3825
3826 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3827 // do not accept frame count changes if tracks are open as the track buffer
3828 // size depends on frame count and correct behavior would not be garantied
3829 // if frame count is changed after track creation
3830 if (!mTracks.isEmpty()) {
3831 status = INVALID_OPERATION;
3832 } else {
3833 reconfig = true;
3834 }
3835 }
3836 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003837 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003838 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003840 mOutput->stream->common.standby(&mOutput->stream->common);
3841 mStandby = true;
3842 mBytesWritten = 0;
3843 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003844 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003845 }
3846 if (status == NO_ERROR && reconfig) {
3847 readOutputParameters();
3848 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3849 }
3850 }
3851
3852 mNewParameters.removeAt(0);
3853
3854 mParamStatus = status;
3855 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003856 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3857 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003858 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 }
3860 return reconfig;
3861}
3862
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003863uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864{
3865 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003866 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003867 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003868 } else {
3869 time = 10000;
3870 }
3871 return time;
3872}
3873
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003874uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875{
3876 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003877 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003878 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 } else {
3880 time = 10000;
3881 }
3882 return time;
3883}
3884
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003885uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003886{
3887 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003888 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003889 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3890 } else {
3891 time = 10000;
3892 }
3893 return time;
3894}
3895
Glenn Kasten66fcab92012-02-24 14:59:21 -08003896void AudioFlinger::DirectOutputThread::cacheParameters_l()
3897{
3898 PlaybackThread::cacheParameters_l();
3899
3900 // use shorter standby delay as on normal output to release
3901 // hardware resources as soon as possible
3902 standbyDelay = microseconds(activeSleepTime*2);
3903}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003904
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905// ----------------------------------------------------------------------------
3906
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003907AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003908 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003909 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3910 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912 addOutputTrack(mainThread);
3913}
3914
3915AudioFlinger::DuplicatingThread::~DuplicatingThread()
3916{
3917 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3918 mOutputTracks[i]->destroy();
3919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920}
3921
Glenn Kasten000f0e32012-03-01 17:10:56 -08003922void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003923{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003924 // mix buffers...
3925 if (outputsReady(outputTracks)) {
3926 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3927 } else {
3928 memset(mMixBuffer, 0, mixBufferSize);
3929 }
3930 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003931 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003932 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003933}
3934
3935void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3936{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003937 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003938 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003939 sleepTime = activeSleepTime;
3940 } else {
3941 sleepTime = idleSleepTime;
3942 }
3943 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003944 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3945 writeFrames = mNormalFrameCount;
3946 memset(mMixBuffer, 0, mixBufferSize);
3947 } else {
3948 // flush remaining overflow buffers in output tracks
3949 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003950 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003951 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003952 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003953}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954
Glenn Kasten000f0e32012-03-01 17:10:56 -08003955void AudioFlinger::DuplicatingThread::threadLoop_write()
3956{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003957 for (size_t i = 0; i < outputTracks.size(); i++) {
3958 outputTracks[i]->write(mMixBuffer, writeFrames);
3959 }
3960 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003961}
Glenn Kasten688a6402012-02-29 07:57:06 -08003962
Glenn Kasten000f0e32012-03-01 17:10:56 -08003963void AudioFlinger::DuplicatingThread::threadLoop_standby()
3964{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003965 // DuplicatingThread implements standby by stopping all tracks
3966 for (size_t i = 0; i < outputTracks.size(); i++) {
3967 outputTracks[i]->stop();
3968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969}
3970
Glenn Kastenfa26a852012-03-06 11:28:04 -08003971void AudioFlinger::DuplicatingThread::saveOutputTracks()
3972{
3973 outputTracks = mOutputTracks;
3974}
3975
3976void AudioFlinger::DuplicatingThread::clearOutputTracks()
3977{
3978 outputTracks.clear();
3979}
3980
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3982{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003983 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003984 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003985 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003986 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 this,
3988 mSampleRate,
3989 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003990 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 frameCount);
3992 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003993 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003995 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003996 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 }
3998}
3999
4000void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4001{
4002 Mutex::Autolock _l(mLock);
4003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004004 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 mOutputTracks[i]->destroy();
4006 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004007 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 return;
4009 }
4010 }
Steve Block3856b092011-10-20 11:56:00 +01004011 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012}
4013
Glenn Kasten438b0362012-03-06 11:24:48 -08004014// caller must hold mLock
4015void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016{
4017 mWaitTimeMs = UINT_MAX;
4018 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4019 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004020 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4022 if (waitTimeMs < mWaitTimeMs) {
4023 mWaitTimeMs = waitTimeMs;
4024 }
4025 }
4026 }
4027}
4028
4029
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004030bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031{
4032 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004033 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004035 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 return false;
4037 }
4038 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4039 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);
4465 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004467 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004469 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470
4471getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004472 buffer->raw = NULL;
4473 buffer->frameCount = 0;
4474 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4475 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476}
4477
Glenn Kasten288ed212012-04-25 17:52:27 -07004478// Note that framesReady() takes a mutex on the control block using tryLock().
4479// This could result in priority inversion if framesReady() is called by the normal mixer,
4480// as the normal mixer thread runs at lower
4481// priority than the client's callback thread: there is a short window within framesReady()
4482// during which the normal mixer could be preempted, and the client callback would block.
4483// Another problem can occur if framesReady() is called by the fast mixer:
4484// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4485// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4486size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004487 return mCblk->framesReady();
4488}
4489
Glenn Kasten288ed212012-04-25 17:52:27 -07004490// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004492 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493
John Grossman4ff14ba2012-02-08 16:37:41 -08004494 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4496 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004497 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 return true;
4499 }
4500 return false;
4501}
4502
Glenn Kasten3acbd052012-02-28 10:39:56 -08004503status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004504 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505{
4506 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004507 ALOGV("start(%d), calling pid %d session %d",
4508 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004509
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 sp<ThreadBase> thread = mThread.promote();
4511 if (thread != 0) {
4512 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004513 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 // here the track could be either new, or restarted
4515 // in both cases "unstop" the track
4516 if (mState == PAUSED) {
4517 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004518 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 } else {
4520 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004521 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 }
4523
4524 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4525 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004526 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004528
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004529#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004530 // to track the speaker usage
4531 if (status == NO_ERROR) {
4532 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4533 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004534#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 }
4536 if (status == NO_ERROR) {
4537 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4538 playbackThread->addTrack_l(this);
4539 } else {
4540 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004541 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 }
4543 } else {
4544 status = BAD_VALUE;
4545 }
4546 return status;
4547}
4548
4549void AudioFlinger::PlaybackThread::Track::stop()
4550{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004551 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 sp<ThreadBase> thread = mThread.promote();
4553 if (thread != 0) {
4554 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004555 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004556 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557 // If the track is not active (PAUSED and buffers full), flush buffers
4558 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4559 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4560 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004561 mState = STOPPED;
4562 } else if (!isFastTrack()) {
4563 mState = STOPPED;
4564 } else {
4565 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4566 // and then to STOPPED and reset() when presentation is complete
4567 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004569 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 }
4571 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4572 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004573 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004575
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004576#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004577 // to track the speaker usage
4578 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004579#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
4581 }
4582}
4583
4584void AudioFlinger::PlaybackThread::Track::pause()
4585{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004586 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 sp<ThreadBase> thread = mThread.promote();
4588 if (thread != 0) {
4589 Mutex::Autolock _l(thread->mLock);
4590 if (mState == ACTIVE || mState == RESUMING) {
4591 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004592 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 if (!isOutputTrack()) {
4594 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004595 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004597
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004598#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004599 // to track the speaker usage
4600 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004601#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 }
4603 }
4604 }
4605}
4606
4607void AudioFlinger::PlaybackThread::Track::flush()
4608{
Steve Block3856b092011-10-20 11:56:00 +01004609 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 sp<ThreadBase> thread = mThread.promote();
4611 if (thread != 0) {
4612 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004613 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4614 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 return;
4616 }
4617 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004618 // FLUSHED state
4619 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004620 // do not reset the track if it is still in the process of being stopped or paused.
4621 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004622 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004623 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004624 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4625 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4626 reset();
4627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 }
4629}
4630
4631void AudioFlinger::PlaybackThread::Track::reset()
4632{
4633 // Do not reset twice to avoid discarding data written just after a flush and before
4634 // the audioflinger thread detects the track is stopped.
4635 if (!mResetDone) {
4636 TrackBase::reset();
4637 // Force underrun condition to avoid false underrun callback until first data is
4638 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004639 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4640 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 mFillingUpStatus = FS_FILLING;
4642 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004643 if (mState == FLUSHED) {
4644 mState = IDLE;
4645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 }
4647}
4648
4649void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4650{
4651 mMute = muted;
4652}
4653
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4655{
4656 status_t status = DEAD_OBJECT;
4657 sp<ThreadBase> thread = mThread.promote();
4658 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004659 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004660 sp<AudioFlinger> af = mClient->audioFlinger();
4661
4662 Mutex::Autolock _l(af->mLock);
4663
4664 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004665
Eric Laurent109347d2012-07-02 12:31:03 -07004666 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004667 Mutex::Autolock _dl(playbackThread->mLock);
4668 Mutex::Autolock _sl(srcThread->mLock);
4669 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4670 if (chain == 0) {
4671 return INVALID_OPERATION;
4672 }
4673
4674 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4675 if (effect == 0) {
4676 return INVALID_OPERATION;
4677 }
4678 srcThread->removeEffect_l(effect);
4679 playbackThread->addEffect_l(effect);
4680 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4681 if (effect->state() == EffectModule::ACTIVE ||
4682 effect->state() == EffectModule::STOPPING) {
4683 effect->start();
4684 }
4685
4686 sp<EffectChain> dstChain = effect->chain().promote();
4687 if (dstChain == 0) {
4688 srcThread->addEffect_l(effect);
4689 return INVALID_OPERATION;
4690 }
4691 AudioSystem::unregisterEffect(effect->id());
4692 AudioSystem::registerEffect(&effect->desc(),
4693 srcThread->id(),
4694 dstChain->strategy(),
4695 AUDIO_SESSION_OUTPUT_MIX,
4696 effect->id());
4697 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004698 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699 }
4700 return status;
4701}
4702
4703void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4704{
4705 mAuxEffectId = EffectId;
4706 mAuxBuffer = buffer;
4707}
4708
Eric Laurenta011e352012-03-29 15:51:43 -07004709bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4710 size_t audioHalFrames)
4711{
4712 // a track is considered presented when the total number of frames written to audio HAL
4713 // corresponds to the number of frames written when presentationComplete() is called for the
4714 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4715 if (mPresentationCompleteFrames == 0) {
4716 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4717 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4718 mPresentationCompleteFrames, audioHalFrames);
4719 }
4720 if (framesWritten >= mPresentationCompleteFrames) {
4721 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4722 mSessionId, framesWritten);
4723 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004724 return true;
4725 }
4726 return false;
4727}
4728
4729void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4730{
4731 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4732 if (mSyncEvents[i]->type() == type) {
4733 mSyncEvents[i]->trigger();
4734 mSyncEvents.removeAt(i);
4735 i--;
4736 }
4737 }
4738}
4739
Glenn Kasten58912562012-04-03 10:45:00 -07004740// implement VolumeBufferProvider interface
4741
4742uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4743{
4744 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4745 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4746 uint32_t vlr = mCblk->getVolumeLR();
4747 uint32_t vl = vlr & 0xFFFF;
4748 uint32_t vr = vlr >> 16;
4749 // track volumes come from shared memory, so can't be trusted and must be clamped
4750 if (vl > MAX_GAIN_INT) {
4751 vl = MAX_GAIN_INT;
4752 }
4753 if (vr > MAX_GAIN_INT) {
4754 vr = MAX_GAIN_INT;
4755 }
4756 // now apply the cached master volume and stream type volume;
4757 // this is trusted but lacks any synchronization or barrier so may be stale
4758 float v = mCachedVolume;
4759 vl *= v;
4760 vr *= v;
4761 // re-combine into U4.16
4762 vlr = (vr << 16) | (vl & 0xFFFF);
4763 // FIXME look at mute, pause, and stop flags
4764 return vlr;
4765}
Eric Laurenta011e352012-03-29 15:51:43 -07004766
Eric Laurent29864602012-05-08 18:57:51 -07004767status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4768{
4769 if (mState == TERMINATED || mState == PAUSED ||
4770 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4771 (mState == STOPPED)))) {
4772 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4773 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4774 event->cancel();
4775 return INVALID_OPERATION;
4776 }
4777 TrackBase::setSyncEvent(event);
4778 return NO_ERROR;
4779}
4780
John Grossman4ff14ba2012-02-08 16:37:41 -08004781// timed audio tracks
4782
4783sp<AudioFlinger::PlaybackThread::TimedTrack>
4784AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004785 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004786 const sp<Client>& client,
4787 audio_stream_type_t streamType,
4788 uint32_t sampleRate,
4789 audio_format_t format,
4790 uint32_t channelMask,
4791 int frameCount,
4792 const sp<IMemory>& sharedBuffer,
4793 int sessionId) {
4794 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004795 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004796
Glenn Kastena0356762012-03-19 10:38:51 -07004797 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004798 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4799 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004800}
4801
4802AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004803 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004804 const sp<Client>& client,
4805 audio_stream_type_t streamType,
4806 uint32_t sampleRate,
4807 audio_format_t format,
4808 uint32_t channelMask,
4809 int frameCount,
4810 const sp<IMemory>& sharedBuffer,
4811 int sessionId)
4812 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004813 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004814 mQueueHeadInFlight(false),
4815 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004816 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004817 mTimedSilenceBuffer(NULL),
4818 mTimedSilenceBufferSize(0),
4819 mTimedAudioOutputOnTime(false),
4820 mMediaTimeTransformValid(false)
4821{
4822 LocalClock lc;
4823 mLocalTimeFreq = lc.getLocalFreq();
4824
4825 mLocalTimeToSampleTransform.a_zero = 0;
4826 mLocalTimeToSampleTransform.b_zero = 0;
4827 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4828 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4829 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4830 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004831
4832 mMediaTimeToSampleTransform.a_zero = 0;
4833 mMediaTimeToSampleTransform.b_zero = 0;
4834 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4835 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4836 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4837 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004838}
4839
4840AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4841 mClient->releaseTimedTrack();
4842 delete [] mTimedSilenceBuffer;
4843}
4844
4845status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4846 size_t size, sp<IMemory>* buffer) {
4847
4848 Mutex::Autolock _l(mTimedBufferQueueLock);
4849
4850 trimTimedBufferQueue_l();
4851
4852 // lazily initialize the shared memory heap for timed buffers
4853 if (mTimedMemoryDealer == NULL) {
4854 const int kTimedBufferHeapSize = 512 << 10;
4855
4856 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4857 "AudioFlingerTimed");
4858 if (mTimedMemoryDealer == NULL)
4859 return NO_MEMORY;
4860 }
4861
4862 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4863 if (newBuffer == NULL) {
4864 newBuffer = mTimedMemoryDealer->allocate(size);
4865 if (newBuffer == NULL)
4866 return NO_MEMORY;
4867 }
4868
4869 *buffer = newBuffer;
4870 return NO_ERROR;
4871}
4872
4873// caller must hold mTimedBufferQueueLock
4874void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4875 int64_t mediaTimeNow;
4876 {
4877 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4878 if (!mMediaTimeTransformValid)
4879 return;
4880
4881 int64_t targetTimeNow;
4882 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4883 ? mCCHelper.getCommonTime(&targetTimeNow)
4884 : mCCHelper.getLocalTime(&targetTimeNow);
4885
4886 if (OK != res)
4887 return;
4888
4889 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4890 &mediaTimeNow)) {
4891 return;
4892 }
4893 }
4894
John Grossman1c345192012-03-27 14:00:17 -07004895 size_t trimEnd;
4896 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004897 int64_t bufEnd;
4898
John Grossmanc95cfbb2012-04-12 11:53:11 -07004899 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4900 // We have a next buffer. Just use its PTS as the PTS of the frame
4901 // following the last frame in this buffer. If the stream is sparse
4902 // (ie, there are deliberate gaps left in the stream which should be
4903 // filled with silence by the TimedAudioTrack), then this can result
4904 // in one extra buffer being left un-trimmed when it could have
4905 // been. In general, this is not typical, and we would rather
4906 // optimized away the TS calculation below for the more common case
4907 // where PTSes are contiguous.
4908 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4909 } else {
4910 // We have no next buffer. Compute the PTS of the frame following
4911 // the last frame in this buffer by computing the duration of of
4912 // this frame in media time units and adding it to the PTS of the
4913 // buffer.
4914 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4915 / mCblk->frameSize;
4916
4917 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4918 &bufEnd)) {
4919 ALOGE("Failed to convert frame count of %lld to media time"
4920 " duration" " (scale factor %d/%u) in %s",
4921 frameCount,
4922 mMediaTimeToSampleTransform.a_to_b_numer,
4923 mMediaTimeToSampleTransform.a_to_b_denom,
4924 __PRETTY_FUNCTION__);
4925 break;
4926 }
4927 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004928 }
John Grossman9fbdee12012-03-26 17:51:46 -07004929
4930 if (bufEnd > mediaTimeNow)
4931 break;
4932
4933 // Is the buffer we want to use in the middle of a mix operation right
4934 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4935 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004936 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004937 mTrimQueueHeadOnRelease = true;
4938 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004939 }
4940
John Grossman9fbdee12012-03-26 17:51:46 -07004941 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004942 if (trimStart < trimEnd) {
4943 // Update the bookkeeping for framesReady()
4944 for (size_t i = trimStart; i < trimEnd; ++i) {
4945 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4946 }
4947
4948 // Now actually remove the buffers from the queue.
4949 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004950 }
4951}
4952
John Grossman1c345192012-03-27 14:00:17 -07004953void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4954 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004955 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4956 "%s called (reason \"%s\"), but timed buffer queue has no"
4957 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004958
4959 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4960 mTimedBufferQueue.removeAt(0);
4961}
4962
4963void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4964 const TimedBuffer& buf,
4965 const char* logTag) {
4966 uint32_t bufBytes = buf.buffer()->size();
4967 uint32_t consumedAlready = buf.position();
4968
Eric Laurentb388e532012-04-14 13:32:48 -07004969 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004970 "Bad bookkeeping while updating frames pending. Timed buffer is"
4971 " only %u bytes long, but claims to have consumed %u"
4972 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004973 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004974
4975 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004976 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4977 "Bad bookkeeping while updating frames pending. Should have at"
4978 " least %u queued frames, but we think we have only %u. (update"
4979 " reason: \"%s\")",
4980 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004981
4982 mFramesPendingInQueue -= bufFrames;
4983}
4984
John Grossman4ff14ba2012-02-08 16:37:41 -08004985status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4986 const sp<IMemory>& buffer, int64_t pts) {
4987
4988 {
4989 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4990 if (!mMediaTimeTransformValid)
4991 return INVALID_OPERATION;
4992 }
4993
4994 Mutex::Autolock _l(mTimedBufferQueueLock);
4995
John Grossman1c345192012-03-27 14:00:17 -07004996 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4997 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004998 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4999
5000 return NO_ERROR;
5001}
5002
5003status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5004 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5005
John Grossman1c345192012-03-27 14:00:17 -07005006 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5007 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5008 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005009
5010 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5011 target == TimedAudioTrack::COMMON_TIME)) {
5012 return BAD_VALUE;
5013 }
5014
5015 Mutex::Autolock lock(mMediaTimeTransformLock);
5016 mMediaTimeTransform = xform;
5017 mMediaTimeTransformTarget = target;
5018 mMediaTimeTransformValid = true;
5019
5020 return NO_ERROR;
5021}
5022
5023#define min(a, b) ((a) < (b) ? (a) : (b))
5024
5025// implementation of getNextBuffer for tracks whose buffers have timestamps
5026status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5027 AudioBufferProvider::Buffer* buffer, int64_t pts)
5028{
5029 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005030 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005031 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005032 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005033 return INVALID_OPERATION;
5034 }
5035
John Grossman4ff14ba2012-02-08 16:37:41 -08005036 Mutex::Autolock _l(mTimedBufferQueueLock);
5037
John Grossman9fbdee12012-03-26 17:51:46 -07005038 ALOG_ASSERT(!mQueueHeadInFlight,
5039 "getNextBuffer called without releaseBuffer!");
5040
John Grossman4ff14ba2012-02-08 16:37:41 -08005041 while (true) {
5042
5043 // if we have no timed buffers, then fail
5044 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005045 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005046 buffer->frameCount = 0;
5047 return NOT_ENOUGH_DATA;
5048 }
5049
5050 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5051
5052 // calculate the PTS of the head of the timed buffer queue expressed in
5053 // local time
5054 int64_t headLocalPTS;
5055 {
5056 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5057
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005058 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005059
5060 if (mMediaTimeTransform.a_to_b_denom == 0) {
5061 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005062 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005063 return NO_ERROR;
5064 }
5065
5066 int64_t transformedPTS;
5067 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5068 &transformedPTS)) {
5069 // the transform failed. this shouldn't happen, but if it does
5070 // then just drop this buffer
5071 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005072 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005073 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005074 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005075 return NO_ERROR;
5076 }
5077
5078 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5079 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5080 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005081 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005082 buffer->frameCount = 0;
5083 return INVALID_OPERATION;
5084 }
5085 } else {
5086 headLocalPTS = transformedPTS;
5087 }
5088 }
5089
5090 // adjust the head buffer's PTS to reflect the portion of the head buffer
5091 // that has already been consumed
5092 int64_t effectivePTS = headLocalPTS +
5093 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5094
5095 // Calculate the delta in samples between the head of the input buffer
5096 // queue and the start of the next output buffer that will be written.
5097 // If the transformation fails because of over or underflow, it means
5098 // that the sample's position in the output stream is so far out of
5099 // whack that it should just be dropped.
5100 int64_t sampleDelta;
5101 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5102 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005103 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5104 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005105 continue;
5106 }
5107 if (!mLocalTimeToSampleTransform.doForwardTransform(
5108 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005109 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005110 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005111 continue;
5112 }
5113
John Grossman1c345192012-03-27 14:00:17 -07005114 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5115 " sampleDelta=[%d.%08x]",
5116 head.pts(), head.position(), pts,
5117 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5118 + (sampleDelta >> 32)),
5119 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005120
5121 // if the delta between the ideal placement for the next input sample and
5122 // the current output position is within this threshold, then we will
5123 // concatenate the next input samples to the previous output
5124 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005125 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005126
5127 // if this is the first buffer of audio that we're emitting from this track
5128 // then it should be almost exactly on time.
5129 const int64_t kSampleStartupThreshold = 1LL << 32;
5130
5131 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005132 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 // the next input is close enough to being on time, so concatenate it
5134 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005135 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005136
John Grossman1c345192012-03-27 14:00:17 -07005137 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5138 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005139 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005140 }
5141
5142 // Looks like our output is not on time. Reset our on timed status.
5143 // Next time we mix samples from our input queue, then should be within
5144 // the StartupThreshold.
5145 mTimedAudioOutputOnTime = false;
5146 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005147 // the gap between the current output position and the proper start of
5148 // the next input sample is too big, so fill it with silence
5149 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5150
John Grossman9fbdee12012-03-26 17:51:46 -07005151 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005152 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5153 return NO_ERROR;
5154 } else {
5155 // the next input sample is late
5156 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5157 size_t onTimeSamplePosition =
5158 head.position() + lateFrames * mCblk->frameSize;
5159
5160 if (onTimeSamplePosition > head.buffer()->size()) {
5161 // all the remaining samples in the head are too late, so
5162 // drop it and move on
5163 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005164 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 continue;
5166 } else {
5167 // skip over the late samples
5168 head.setPosition(onTimeSamplePosition);
5169
5170 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005171 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005172
5173 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5174 return NO_ERROR;
5175 }
5176 }
5177 }
5178}
5179
5180// Yield samples from the timed buffer queue head up to the given output
5181// buffer's capacity.
5182//
5183// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005184void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 AudioBufferProvider::Buffer* buffer) {
5186
5187 const TimedBuffer& head = mTimedBufferQueue[0];
5188
5189 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5190 head.position());
5191
5192 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5193 mCblk->frameSize);
5194 size_t framesRequested = buffer->frameCount;
5195 buffer->frameCount = min(framesLeftInHead, framesRequested);
5196
John Grossman9fbdee12012-03-26 17:51:46 -07005197 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005198 mTimedAudioOutputOnTime = true;
5199}
5200
5201// Yield samples of silence up to the given output buffer's capacity
5202//
5203// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005204void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5206
5207 // lazily allocate a buffer filled with silence
5208 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5209 delete [] mTimedSilenceBuffer;
5210 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5211 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5212 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5213 }
5214
5215 buffer->raw = mTimedSilenceBuffer;
5216 size_t framesRequested = buffer->frameCount;
5217 buffer->frameCount = min(numFrames, framesRequested);
5218
5219 mTimedAudioOutputOnTime = false;
5220}
5221
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005222// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005223void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5224 AudioBufferProvider::Buffer* buffer) {
5225
5226 Mutex::Autolock _l(mTimedBufferQueueLock);
5227
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005228 // If the buffer which was just released is part of the buffer at the head
5229 // of the queue, be sure to update the amt of the buffer which has been
5230 // consumed. If the buffer being returned is not part of the head of the
5231 // queue, its either because the buffer is part of the silence buffer, or
5232 // because the head of the timed queue was trimmed after the mixer called
5233 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005234 if (buffer->raw == mTimedSilenceBuffer) {
5235 ALOG_ASSERT(!mQueueHeadInFlight,
5236 "Queue head in flight during release of silence buffer!");
5237 goto done;
5238 }
5239
5240 ALOG_ASSERT(mQueueHeadInFlight,
5241 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5242 " head in flight.");
5243
5244 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005245 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005246
5247 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005248 void* end = reinterpret_cast<void*>(
5249 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5250 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005251
John Grossman9fbdee12012-03-26 17:51:46 -07005252 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5253 "released buffer not within the head of the timed buffer"
5254 " queue; qHead = [%p, %p], released buffer = %p",
5255 start, end, buffer->raw);
5256
5257 head.setPosition(head.position() +
5258 (buffer->frameCount * mCblk->frameSize));
5259 mQueueHeadInFlight = false;
5260
John Grossman1c345192012-03-27 14:00:17 -07005261 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5262 "Bad bookkeeping during releaseBuffer! Should have at"
5263 " least %u queued frames, but we think we have only %u",
5264 buffer->frameCount, mFramesPendingInQueue);
5265
5266 mFramesPendingInQueue -= buffer->frameCount;
5267
John Grossman9fbdee12012-03-26 17:51:46 -07005268 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5269 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005270 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005271 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005272 }
John Grossman9fbdee12012-03-26 17:51:46 -07005273 } else {
5274 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5275 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005276 }
5277
John Grossman9fbdee12012-03-26 17:51:46 -07005278done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005279 buffer->raw = 0;
5280 buffer->frameCount = 0;
5281}
5282
Glenn Kasten288ed212012-04-25 17:52:27 -07005283size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005284 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005285 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005286}
5287
5288AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5289 : mPTS(0), mPosition(0) {}
5290
5291AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5292 const sp<IMemory>& buffer, int64_t pts)
5293 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5294
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295// ----------------------------------------------------------------------------
5296
5297// RecordTrack constructor must be called with AudioFlinger::mLock held
5298AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005299 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005300 const sp<Client>& client,
5301 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005302 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005303 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005305 int sessionId)
5306 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005307 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 mOverflow(false)
5309{
5310 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005311 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5312 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5313 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5314 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5315 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5316 } else {
5317 mCblk->frameSize = sizeof(int8_t);
5318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 }
5320}
5321
5322AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5323{
5324 sp<ThreadBase> thread = mThread.promote();
5325 if (thread != 0) {
5326 AudioSystem::releaseInput(thread->id());
5327 }
5328}
5329
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005330// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005331status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332{
5333 audio_track_cblk_t* cblk = this->cblk();
5334 uint32_t framesAvail;
5335 uint32_t framesReq = buffer->frameCount;
5336
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005337 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005338 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005340 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005341 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 }
5343
5344 framesAvail = cblk->framesAvailable_l();
5345
Glenn Kastenf6b16782011-12-15 09:51:17 -08005346 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 uint32_t s = cblk->server;
5348 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5349
5350 if (framesReq > framesAvail) {
5351 framesReq = framesAvail;
5352 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005353 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 framesReq = bufferEnd - s;
5355 }
5356
5357 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005358 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359
5360 buffer->frameCount = framesReq;
5361 return NO_ERROR;
5362 }
5363
5364getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005365 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366 buffer->frameCount = 0;
5367 return NOT_ENOUGH_DATA;
5368}
5369
Glenn Kasten3acbd052012-02-28 10:39:56 -08005370status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005371 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372{
5373 sp<ThreadBase> thread = mThread.promote();
5374 if (thread != 0) {
5375 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005376 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377 } else {
5378 return BAD_VALUE;
5379 }
5380}
5381
5382void AudioFlinger::RecordThread::RecordTrack::stop()
5383{
5384 sp<ThreadBase> thread = mThread.promote();
5385 if (thread != 0) {
5386 RecordThread *recordThread = (RecordThread *)thread.get();
5387 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005388 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005389 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005390 // read from buffer
5391 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 }
5393}
5394
5395void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5396{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005397 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005398 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005400 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 mSessionId,
5402 mFrameCount,
5403 mState,
5404 mCblk->sampleRate,
5405 mCblk->server,
5406 mCblk->user);
5407}
5408
5409
5410// ----------------------------------------------------------------------------
5411
5412AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005413 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 DuplicatingThread *sourceThread,
5415 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005416 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005417 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005419 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5420 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 mActive(false), mSourceThread(sourceThread)
5422{
5423
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 if (mCblk != NULL) {
5425 mCblk->flags |= CBLK_DIRECTION_OUT;
5426 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 mOutBuffer.frameCount = 0;
5428 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005429 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005430 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5431 mCblk, mBuffer, mCblk->buffers,
5432 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005434 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 }
5436}
5437
5438AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5439{
5440 clearBufferQueue();
5441}
5442
Glenn Kasten3acbd052012-02-28 10:39:56 -08005443status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005444 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005446 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 if (status != NO_ERROR) {
5448 return status;
5449 }
5450
5451 mActive = true;
5452 mRetryCount = 127;
5453 return status;
5454}
5455
5456void AudioFlinger::PlaybackThread::OutputTrack::stop()
5457{
5458 Track::stop();
5459 clearBufferQueue();
5460 mOutBuffer.frameCount = 0;
5461 mActive = false;
5462}
5463
5464bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5465{
5466 Buffer *pInBuffer;
5467 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005468 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 bool outputBufferFull = false;
5470 inBuffer.frameCount = frames;
5471 inBuffer.i16 = data;
5472
5473 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5474
5475 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005476 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 sp<ThreadBase> thread = mThread.promote();
5478 if (thread != 0) {
5479 MixerThread *mixerThread = (MixerThread *)thread.get();
5480 if (mCblk->frameCount > frames){
5481 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5482 uint32_t startFrames = (mCblk->frameCount - frames);
5483 pInBuffer = new Buffer;
5484 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5485 pInBuffer->frameCount = startFrames;
5486 pInBuffer->i16 = pInBuffer->mBuffer;
5487 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5488 mBufferQueue.add(pInBuffer);
5489 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005490 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 }
5492 }
5493 }
5494 }
5495
5496 while (waitTimeLeftMs) {
5497 // First write pending buffers, then new data
5498 if (mBufferQueue.size()) {
5499 pInBuffer = mBufferQueue.itemAt(0);
5500 } else {
5501 pInBuffer = &inBuffer;
5502 }
5503
5504 if (pInBuffer->frameCount == 0) {
5505 break;
5506 }
5507
5508 if (mOutBuffer.frameCount == 0) {
5509 mOutBuffer.frameCount = pInBuffer->frameCount;
5510 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005511 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005512 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513 outputBufferFull = true;
5514 break;
5515 }
5516 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5517 if (waitTimeLeftMs >= waitTimeMs) {
5518 waitTimeLeftMs -= waitTimeMs;
5519 } else {
5520 waitTimeLeftMs = 0;
5521 }
5522 }
5523
5524 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5525 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5526 mCblk->stepUser(outFrames);
5527 pInBuffer->frameCount -= outFrames;
5528 pInBuffer->i16 += outFrames * channelCount;
5529 mOutBuffer.frameCount -= outFrames;
5530 mOutBuffer.i16 += outFrames * channelCount;
5531
5532 if (pInBuffer->frameCount == 0) {
5533 if (mBufferQueue.size()) {
5534 mBufferQueue.removeAt(0);
5535 delete [] pInBuffer->mBuffer;
5536 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005537 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 } else {
5539 break;
5540 }
5541 }
5542 }
5543
5544 // If we could not write all frames, allocate a buffer and queue it for next time.
5545 if (inBuffer.frameCount) {
5546 sp<ThreadBase> thread = mThread.promote();
5547 if (thread != 0 && !thread->standby()) {
5548 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5549 pInBuffer = new Buffer;
5550 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5551 pInBuffer->frameCount = inBuffer.frameCount;
5552 pInBuffer->i16 = pInBuffer->mBuffer;
5553 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5554 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005555 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005557 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 }
5559 }
5560 }
5561
5562 // Calling write() with a 0 length buffer, means that no more data will be written:
5563 // If no more buffers are pending, fill output track buffer to make sure it is started
5564 // by output mixer.
5565 if (frames == 0 && mBufferQueue.size() == 0) {
5566 if (mCblk->user < mCblk->frameCount) {
5567 frames = mCblk->frameCount - mCblk->user;
5568 pInBuffer = new Buffer;
5569 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5570 pInBuffer->frameCount = frames;
5571 pInBuffer->i16 = pInBuffer->mBuffer;
5572 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5573 mBufferQueue.add(pInBuffer);
5574 } else if (mActive) {
5575 stop();
5576 }
5577 }
5578
5579 return outputBufferFull;
5580}
5581
5582status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5583{
5584 int active;
5585 status_t result;
5586 audio_track_cblk_t* cblk = mCblk;
5587 uint32_t framesReq = buffer->frameCount;
5588
Steve Block3856b092011-10-20 11:56:00 +01005589// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 buffer->frameCount = 0;
5591
5592 uint32_t framesAvail = cblk->framesAvailable();
5593
5594
5595 if (framesAvail == 0) {
5596 Mutex::Autolock _l(cblk->lock);
5597 goto start_loop_here;
5598 while (framesAvail == 0) {
5599 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005600 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005601 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005602 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 }
5604 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5605 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005606 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607 }
5608 // read the server count again
5609 start_loop_here:
5610 framesAvail = cblk->framesAvailable_l();
5611 }
5612 }
5613
5614// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005615// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616// }
5617
5618 if (framesReq > framesAvail) {
5619 framesReq = framesAvail;
5620 }
5621
5622 uint32_t u = cblk->user;
5623 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5624
Marco Nelissena1472d92012-03-30 14:36:54 -07005625 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 framesReq = bufferEnd - u;
5627 }
5628
5629 buffer->frameCount = framesReq;
5630 buffer->raw = (void *)cblk->buffer(u);
5631 return NO_ERROR;
5632}
5633
5634
5635void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5636{
5637 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638
5639 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005640 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 delete [] pBuffer->mBuffer;
5642 delete pBuffer;
5643 }
5644 mBufferQueue.clear();
5645}
5646
5647// ----------------------------------------------------------------------------
5648
5649AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5650 : RefBase(),
5651 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005652 // 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 -07005653 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005654 mPid(pid),
5655 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656{
5657 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5658}
5659
5660// Client destructor must be called with AudioFlinger::mLock held
5661AudioFlinger::Client::~Client()
5662{
5663 mAudioFlinger->removeClient_l(mPid);
5664}
5665
Glenn Kasten435dbe62012-01-30 10:15:48 -08005666sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667{
5668 return mMemoryDealer;
5669}
5670
John Grossman4ff14ba2012-02-08 16:37:41 -08005671// Reserve one of the limited slots for a timed audio track associated
5672// with this client
5673bool AudioFlinger::Client::reserveTimedTrack()
5674{
5675 const int kMaxTimedTracksPerClient = 4;
5676
5677 Mutex::Autolock _l(mTimedTrackLock);
5678
5679 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5680 ALOGW("can not create timed track - pid %d has exceeded the limit",
5681 mPid);
5682 return false;
5683 }
5684
5685 mTimedTrackCount++;
5686 return true;
5687}
5688
5689// Release a slot for a timed audio track
5690void AudioFlinger::Client::releaseTimedTrack()
5691{
5692 Mutex::Autolock _l(mTimedTrackLock);
5693 mTimedTrackCount--;
5694}
5695
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696// ----------------------------------------------------------------------------
5697
5698AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5699 const sp<IAudioFlingerClient>& client,
5700 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005701 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702{
5703}
5704
5705AudioFlinger::NotificationClient::~NotificationClient()
5706{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707}
5708
5709void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5710{
5711 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005712 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713}
5714
5715// ----------------------------------------------------------------------------
5716
5717AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5718 : BnAudioTrack(),
5719 mTrack(track)
5720{
5721}
5722
5723AudioFlinger::TrackHandle::~TrackHandle() {
5724 // just stop the track on deletion, associated resources
5725 // will be freed from the main thread once all pending buffers have
5726 // been played. Unless it's not in the active track list, in which
5727 // case we free everything now...
5728 mTrack->destroy();
5729}
5730
Glenn Kasten90716c52012-01-26 13:40:12 -08005731sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5732 return mTrack->getCblk();
5733}
5734
Glenn Kasten3acbd052012-02-28 10:39:56 -08005735status_t AudioFlinger::TrackHandle::start() {
5736 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737}
5738
5739void AudioFlinger::TrackHandle::stop() {
5740 mTrack->stop();
5741}
5742
5743void AudioFlinger::TrackHandle::flush() {
5744 mTrack->flush();
5745}
5746
5747void AudioFlinger::TrackHandle::mute(bool e) {
5748 mTrack->mute(e);
5749}
5750
5751void AudioFlinger::TrackHandle::pause() {
5752 mTrack->pause();
5753}
5754
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5756{
5757 return mTrack->attachAuxEffect(EffectId);
5758}
5759
John Grossman4ff14ba2012-02-08 16:37:41 -08005760status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5761 sp<IMemory>* buffer) {
5762 if (!mTrack->isTimedTrack())
5763 return INVALID_OPERATION;
5764
5765 PlaybackThread::TimedTrack* tt =
5766 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5767 return tt->allocateTimedBuffer(size, buffer);
5768}
5769
5770status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5771 int64_t pts) {
5772 if (!mTrack->isTimedTrack())
5773 return INVALID_OPERATION;
5774
5775 PlaybackThread::TimedTrack* tt =
5776 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5777 return tt->queueTimedBuffer(buffer, pts);
5778}
5779
5780status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5781 const LinearTransform& xform, int target) {
5782
5783 if (!mTrack->isTimedTrack())
5784 return INVALID_OPERATION;
5785
5786 PlaybackThread::TimedTrack* tt =
5787 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5788 return tt->setMediaTimeTransform(
5789 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5790}
5791
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792status_t AudioFlinger::TrackHandle::onTransact(
5793 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5794{
5795 return BnAudioTrack::onTransact(code, data, reply, flags);
5796}
5797
5798// ----------------------------------------------------------------------------
5799
5800sp<IAudioRecord> AudioFlinger::openRecord(
5801 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005802 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005804 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005805 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005807 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 int *sessionId,
5809 status_t *status)
5810{
5811 sp<RecordThread::RecordTrack> recordTrack;
5812 sp<RecordHandle> recordHandle;
5813 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814 status_t lStatus;
5815 RecordThread *thread;
5816 size_t inFrameCount;
5817 int lSessionId;
5818
5819 // check calling permissions
5820 if (!recordingAllowed()) {
5821 lStatus = PERMISSION_DENIED;
5822 goto Exit;
5823 }
5824
5825 // add client to list
5826 { // scope for mLock
5827 Mutex::Autolock _l(mLock);
5828 thread = checkRecordThread_l(input);
5829 if (thread == NULL) {
5830 lStatus = BAD_VALUE;
5831 goto Exit;
5832 }
5833
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005834 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835
5836 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005837 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 lSessionId = *sessionId;
5839 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005840 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 if (sessionId != NULL) {
5842 *sessionId = lSessionId;
5843 }
5844 }
5845 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005846 recordTrack = thread->createRecordTrack_l(client,
5847 sampleRate,
5848 format,
5849 channelMask,
5850 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005851 lSessionId,
5852 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005853 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005854 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5856 // destructor is called by the TrackBase destructor with mLock held
5857 client.clear();
5858 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859 goto Exit;
5860 }
5861
5862 // return to handle to client
5863 recordHandle = new RecordHandle(recordTrack);
5864 lStatus = NO_ERROR;
5865
5866Exit:
5867 if (status) {
5868 *status = lStatus;
5869 }
5870 return recordHandle;
5871}
5872
5873// ----------------------------------------------------------------------------
5874
5875AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5876 : BnAudioRecord(),
5877 mRecordTrack(recordTrack)
5878{
5879}
5880
5881AudioFlinger::RecordHandle::~RecordHandle() {
5882 stop();
5883}
5884
Glenn Kasten90716c52012-01-26 13:40:12 -08005885sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5886 return mRecordTrack->getCblk();
5887}
5888
Glenn Kasten3acbd052012-02-28 10:39:56 -08005889status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005890 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005891 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892}
5893
5894void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005895 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 mRecordTrack->stop();
5897}
5898
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899status_t AudioFlinger::RecordHandle::onTransact(
5900 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5901{
5902 return BnAudioRecord::onTransact(code, data, reply, flags);
5903}
5904
5905// ----------------------------------------------------------------------------
5906
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005907AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5908 AudioStreamIn *input,
5909 uint32_t sampleRate,
5910 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005911 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005912 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005913 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005914 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5915 // mRsmpInIndex and mInputBytes set by readInputParameters()
5916 mReqChannelCount(popcount(channels)),
5917 mReqSampleRate(sampleRate)
5918 // mBytesRead is only meaningful while active, and so is cleared in start()
5919 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920{
Glenn Kasten480b4682012-02-28 12:30:08 -08005921 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005922
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 readInputParameters();
5924}
5925
5926
5927AudioFlinger::RecordThread::~RecordThread()
5928{
5929 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005930 delete mResampler;
5931 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932}
5933
5934void AudioFlinger::RecordThread::onFirstRef()
5935{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005936 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937}
5938
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005939status_t AudioFlinger::RecordThread::readyToRun()
5940{
5941 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005942 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005943 return status;
5944}
5945
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946bool AudioFlinger::RecordThread::threadLoop()
5947{
5948 AudioBufferProvider::Buffer buffer;
5949 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005950 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951
Eric Laurent44d98482010-09-30 16:12:31 -07005952 nsecs_t lastWarning = 0;
5953
Eric Laurentfeb0db62011-07-22 09:04:31 -07005954 acquireWakeLock();
5955
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 // start recording
5957 while (!exitPending()) {
5958
5959 processConfigEvents();
5960
5961 { // scope for mLock
5962 Mutex::Autolock _l(mLock);
5963 checkForNewParameters_l();
5964 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5965 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005966 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 mStandby = true;
5968 }
5969
5970 if (exitPending()) break;
5971
Eric Laurentfeb0db62011-07-22 09:04:31 -07005972 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005973 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 // go to sleep
5975 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005976 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005977 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 continue;
5979 }
5980 if (mActiveTrack != 0) {
5981 if (mActiveTrack->mState == TrackBase::PAUSING) {
5982 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005983 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 mStandby = true;
5985 }
5986 mActiveTrack.clear();
5987 mStartStopCond.broadcast();
5988 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5989 if (mReqChannelCount != mActiveTrack->channelCount()) {
5990 mActiveTrack.clear();
5991 mStartStopCond.broadcast();
5992 } else if (mBytesRead != 0) {
5993 // record start succeeds only if first read from audio input
5994 // succeeds
5995 if (mBytesRead > 0) {
5996 mActiveTrack->mState = TrackBase::ACTIVE;
5997 } else {
5998 mActiveTrack.clear();
5999 }
6000 mStartStopCond.broadcast();
6001 }
6002 mStandby = false;
6003 }
6004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006 }
6007
6008 if (mActiveTrack != 0) {
6009 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6010 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006011 unlockEffectChains(effectChains);
6012 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 continue;
6014 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006015 for (size_t i = 0; i < effectChains.size(); i ++) {
6016 effectChains[i]->process_l();
6017 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006018
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006020 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006022 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023 // no resampling
6024 while (framesOut) {
6025 size_t framesIn = mFrameCount - mRsmpInIndex;
6026 if (framesIn) {
6027 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6028 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6029 if (framesIn > framesOut)
6030 framesIn = framesOut;
6031 mRsmpInIndex += framesIn;
6032 framesOut -= framesIn;
6033 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006034 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 memcpy(dst, src, framesIn * mFrameSize);
6036 } else {
6037 int16_t *src16 = (int16_t *)src;
6038 int16_t *dst16 = (int16_t *)dst;
6039 if (mChannelCount == 1) {
6040 while (framesIn--) {
6041 *dst16++ = *src16;
6042 *dst16++ = *src16++;
6043 }
6044 } else {
6045 while (framesIn--) {
6046 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6047 src16 += 2;
6048 }
6049 }
6050 }
6051 }
6052 if (framesOut && mFrameCount == mRsmpInIndex) {
6053 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006054 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006055 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 framesOut = 0;
6057 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006058 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 mRsmpInIndex = 0;
6060 }
6061 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006062 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6064 // Force input into standby so that it tries to
6065 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006066 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006067 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 }
6069 mRsmpInIndex = mFrameCount;
6070 framesOut = 0;
6071 buffer.frameCount = 0;
6072 }
6073 }
6074 }
6075 } else {
6076 // resampling
6077
6078 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6079 // alter output frame count as if we were expecting stereo samples
6080 if (mChannelCount == 1 && mReqChannelCount == 1) {
6081 framesOut >>= 1;
6082 }
6083 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6084 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6085 // are 32 bit aligned which should be always true.
6086 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006087 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 // the resampler always outputs stereo samples: do post stereo to mono conversion
6089 int16_t *src = (int16_t *)mRsmpOutBuffer;
6090 int16_t *dst = buffer.i16;
6091 while (framesOut--) {
6092 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6093 src += 2;
6094 }
6095 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006096 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 }
6098
6099 }
Eric Laurenta011e352012-03-29 15:51:43 -07006100 if (mFramestoDrop == 0) {
6101 mActiveTrack->releaseBuffer(&buffer);
6102 } else {
6103 if (mFramestoDrop > 0) {
6104 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006105 if (mFramestoDrop <= 0) {
6106 clearSyncStartEvent();
6107 }
6108 } else {
6109 mFramestoDrop += buffer.frameCount;
6110 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6111 mSyncStartEvent->isCancelled()) {
6112 ALOGW("Synced record %s, session %d, trigger session %d",
6113 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6114 mActiveTrack->sessionId(),
6115 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6116 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006117 }
6118 }
6119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 mActiveTrack->overflow();
6121 }
6122 // client isn't retrieving buffers fast enough
6123 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006124 if (!mActiveTrack->setOverflow()) {
6125 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006126 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006127 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006128 lastWarning = now;
6129 }
6130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 // Release the processor for a while before asking for a new buffer.
6132 // This will give the application more chance to read from the buffer and
6133 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006134 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 }
6136 }
Eric Laurentec437d82011-07-26 20:54:46 -07006137 // enable changes in effect chain
6138 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006139 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 }
6141
6142 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006143 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 }
6145 mActiveTrack.clear();
6146
6147 mStartStopCond.broadcast();
6148
Eric Laurentfeb0db62011-07-22 09:04:31 -07006149 releaseWakeLock();
6150
Steve Block3856b092011-10-20 11:56:00 +01006151 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152 return false;
6153}
6154
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006155
6156sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6157 const sp<AudioFlinger::Client>& client,
6158 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006159 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 int channelMask,
6161 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006162 int sessionId,
6163 status_t *status)
6164{
6165 sp<RecordTrack> track;
6166 status_t lStatus;
6167
6168 lStatus = initCheck();
6169 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006170 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171 goto Exit;
6172 }
6173
6174 { // scope for mLock
6175 Mutex::Autolock _l(mLock);
6176
6177 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006178 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006179
Glenn Kasten7378ca52012-01-20 13:44:40 -08006180 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006181 lStatus = NO_MEMORY;
6182 goto Exit;
6183 }
6184
6185 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006186 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6187 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006188 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006189 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6190 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006191 }
6192 lStatus = NO_ERROR;
6193
6194Exit:
6195 if (status) {
6196 *status = lStatus;
6197 }
6198 return track;
6199}
6200
Eric Laurenta011e352012-03-29 15:51:43 -07006201status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006202 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006203 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204{
Glenn Kasten58912562012-04-03 10:45:00 -07006205 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006206 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006208
6209 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006210 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006211 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6212 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6213 triggerSession,
6214 recordTrack->sessionId(),
6215 syncStartEventCallback,
6216 this);
Eric Laurent29864602012-05-08 18:57:51 -07006217 // Sync event can be cancelled by the trigger session if the track is not in a
6218 // compatible state in which case we start record immediately
6219 if (mSyncStartEvent->isCancelled()) {
6220 clearSyncStartEvent();
6221 } else {
6222 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6223 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6224 }
Eric Laurenta011e352012-03-29 15:51:43 -07006225 }
6226
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006228 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 if (mActiveTrack != 0) {
6230 if (recordTrack != mActiveTrack.get()) {
6231 status = -EBUSY;
6232 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6233 mActiveTrack->mState = TrackBase::ACTIVE;
6234 }
6235 return status;
6236 }
6237
6238 recordTrack->mState = TrackBase::IDLE;
6239 mActiveTrack = recordTrack;
6240 mLock.unlock();
6241 status_t status = AudioSystem::startInput(mId);
6242 mLock.lock();
6243 if (status != NO_ERROR) {
6244 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006245 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 return status;
6247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 mRsmpInIndex = mFrameCount;
6249 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006250 if (mResampler != NULL) {
6251 mResampler->reset();
6252 }
6253 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006255 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 mWaitWorkCV.signal();
6257 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006258 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 mActiveTrack.clear();
6260 status = INVALID_OPERATION;
6261 goto startError;
6262 }
6263 mStartStopCond.wait(mLock);
6264 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006265 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 status = BAD_VALUE;
6267 goto startError;
6268 }
Steve Block3856b092011-10-20 11:56:00 +01006269 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 return status;
6271 }
6272startError:
6273 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006274 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 return status;
6276}
6277
Eric Laurenta011e352012-03-29 15:51:43 -07006278void AudioFlinger::RecordThread::clearSyncStartEvent()
6279{
6280 if (mSyncStartEvent != 0) {
6281 mSyncStartEvent->cancel();
6282 }
6283 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006284 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006285}
6286
6287void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6288{
6289 sp<SyncEvent> strongEvent = event.promote();
6290
6291 if (strongEvent != 0) {
6292 RecordThread *me = (RecordThread *)strongEvent->cookie();
6293 me->handleSyncStartEvent(strongEvent);
6294 }
6295}
6296
6297void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6298{
Eric Laurent29864602012-05-08 18:57:51 -07006299 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006300 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6301 // from audio HAL
6302 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006303 }
6304}
6305
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006307 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006308 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006310 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6312 mActiveTrack->mState = TrackBase::PAUSING;
6313 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006314 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 return;
6316 }
6317 mStartStopCond.wait(mLock);
6318 // if we have been restarted, recordTrack == mActiveTrack.get() here
6319 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6320 mLock.unlock();
6321 AudioSystem::stopInput(mId);
6322 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006323 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 }
6325 }
6326 }
6327}
6328
Eric Laurenta011e352012-03-29 15:51:43 -07006329bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6330{
6331 return false;
6332}
6333
6334status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6335{
6336 if (!isValidSyncEvent(event)) {
6337 return BAD_VALUE;
6338 }
6339
6340 Mutex::Autolock _l(mLock);
6341
6342 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6343 mTrack->setSyncEvent(event);
6344 return NO_ERROR;
6345 }
6346 return NAME_NOT_FOUND;
6347}
6348
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6350{
6351 const size_t SIZE = 256;
6352 char buffer[SIZE];
6353 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354
6355 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6356 result.append(buffer);
6357
6358 if (mActiveTrack != 0) {
6359 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006360 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 mActiveTrack->dump(buffer, SIZE);
6362 result.append(buffer);
6363
6364 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6365 result.append(buffer);
6366 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6367 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006368 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 result.append(buffer);
6370 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6371 result.append(buffer);
6372 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6373 result.append(buffer);
6374
6375
6376 } else {
6377 result.append("No record client\n");
6378 }
6379 write(fd, result.string(), result.size());
6380
6381 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006382 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383
6384 return NO_ERROR;
6385}
6386
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006387// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006388status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389{
6390 size_t framesReq = buffer->frameCount;
6391 size_t framesReady = mFrameCount - mRsmpInIndex;
6392 int channelCount;
6393
6394 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006395 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006397 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6399 // Force input into standby so that it tries to
6400 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006401 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006402 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006404 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 buffer->frameCount = 0;
6406 return NOT_ENOUGH_DATA;
6407 }
6408 mRsmpInIndex = 0;
6409 framesReady = mFrameCount;
6410 }
6411
6412 if (framesReq > framesReady) {
6413 framesReq = framesReady;
6414 }
6415
6416 if (mChannelCount == 1 && mReqChannelCount == 2) {
6417 channelCount = 1;
6418 } else {
6419 channelCount = 2;
6420 }
6421 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6422 buffer->frameCount = framesReq;
6423 return NO_ERROR;
6424}
6425
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006426// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6428{
6429 mRsmpInIndex += buffer->frameCount;
6430 buffer->frameCount = 0;
6431}
6432
6433bool AudioFlinger::RecordThread::checkForNewParameters_l()
6434{
6435 bool reconfig = false;
6436
6437 while (!mNewParameters.isEmpty()) {
6438 status_t status = NO_ERROR;
6439 String8 keyValuePair = mNewParameters[0];
6440 AudioParameter param = AudioParameter(keyValuePair);
6441 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006442 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 int reqSamplingRate = mReqSampleRate;
6444 int reqChannelCount = mReqChannelCount;
6445
6446 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6447 reqSamplingRate = value;
6448 reconfig = true;
6449 }
6450 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006451 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 reconfig = true;
6453 }
6454 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006455 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456 reconfig = true;
6457 }
6458 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6459 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006460 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 // if frame count is changed after track creation
6462 if (mActiveTrack != 0) {
6463 status = INVALID_OPERATION;
6464 } else {
6465 reconfig = true;
6466 }
6467 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006468 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6469 // forward device change to effects that have requested to be
6470 // aware of attached audio device.
6471 for (size_t i = 0; i < mEffectChains.size(); i++) {
6472 mEffectChains[i]->setDevice_l(value);
6473 }
6474 // store input device and output device but do not forward output device to audio HAL.
6475 // Note that status is ignored by the caller for output device
6476 // (see AudioFlinger::setParameters()
6477 if (value & AUDIO_DEVICE_OUT_ALL) {
6478 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6479 status = BAD_VALUE;
6480 } else {
6481 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006482 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6483 if (mTrack != NULL) {
6484 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006485 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006486 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6487 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6488 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006489 }
6490 mDevice |= (uint32_t)value;
6491 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006493 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006495 mInput->stream->common.standby(&mInput->stream->common);
6496 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6497 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498 }
6499 if (reconfig) {
6500 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006501 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006502 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006503 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006504 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6505 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506 status = NO_ERROR;
6507 }
6508 if (status == NO_ERROR) {
6509 readInputParameters();
6510 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6511 }
6512 }
6513 }
6514
6515 mNewParameters.removeAt(0);
6516
6517 mParamStatus = status;
6518 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006519 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6520 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006521 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 }
6523 return reconfig;
6524}
6525
6526String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6527{
Dima Zavinfce7a472011-04-19 22:30:36 -07006528 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006529 String8 out_s8 = String8();
6530
6531 Mutex::Autolock _l(mLock);
6532 if (initCheck() != NO_ERROR) {
6533 return out_s8;
6534 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006535
Dima Zavin799a70e2011-04-18 16:57:27 -07006536 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006537 out_s8 = String8(s);
6538 free(s);
6539 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540}
6541
6542void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6543 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006544 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545
6546 switch (event) {
6547 case AudioSystem::INPUT_OPENED:
6548 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006549 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 desc.samplingRate = mSampleRate;
6551 desc.format = mFormat;
6552 desc.frameCount = mFrameCount;
6553 desc.latency = 0;
6554 param2 = &desc;
6555 break;
6556
6557 case AudioSystem::INPUT_CLOSED:
6558 default:
6559 break;
6560 }
6561 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6562}
6563
6564void AudioFlinger::RecordThread::readInputParameters()
6565{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006566 delete mRsmpInBuffer;
6567 // mRsmpInBuffer is always assigned a new[] below
6568 delete mRsmpOutBuffer;
6569 mRsmpOutBuffer = NULL;
6570 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006571 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572
Dima Zavin799a70e2011-04-18 16:57:27 -07006573 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006574 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6575 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006576 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006577 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006578 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006580 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6582
Glenn Kasten53d76db2012-03-08 12:32:47 -08006583 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 {
6585 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006586 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6587 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588 if (mChannelCount == 1 && mReqChannelCount == 2) {
6589 channelCount = 1;
6590 } else {
6591 channelCount = 2;
6592 }
6593 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6594 mResampler->setSampleRate(mSampleRate);
6595 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6596 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6597
6598 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6599 if (mChannelCount == 1 && mReqChannelCount == 1) {
6600 mFrameCount >>= 1;
6601 }
6602
6603 }
6604 mRsmpInIndex = mFrameCount;
6605}
6606
6607unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6608{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006609 Mutex::Autolock _l(mLock);
6610 if (initCheck() != NO_ERROR) {
6611 return 0;
6612 }
6613
Dima Zavin799a70e2011-04-18 16:57:27 -07006614 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615}
6616
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006617uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6618{
6619 Mutex::Autolock _l(mLock);
6620 uint32_t result = 0;
6621 if (getEffectChain_l(sessionId) != 0) {
6622 result = EFFECT_SESSION;
6623 }
6624
6625 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6626 result |= TRACK_SESSION;
6627 }
6628
6629 return result;
6630}
6631
Eric Laurent59bd0da2011-08-01 09:52:20 -07006632AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6633{
6634 Mutex::Autolock _l(mLock);
6635 return mTrack;
6636}
6637
Glenn Kastenaed850d2012-01-26 09:46:34 -08006638AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006639{
6640 Mutex::Autolock _l(mLock);
6641 return mInput;
6642}
6643
6644AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6645{
6646 Mutex::Autolock _l(mLock);
6647 AudioStreamIn *input = mInput;
6648 mInput = NULL;
6649 return input;
6650}
6651
6652// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006653audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006654{
6655 if (mInput == NULL) {
6656 return NULL;
6657 }
6658 return &mInput->stream->common;
6659}
6660
6661
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662// ----------------------------------------------------------------------------
6663
Eric Laurenta4c5a552012-03-29 10:12:40 -07006664audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6665{
6666 if (!settingsAllowed()) {
6667 return 0;
6668 }
6669 Mutex::Autolock _l(mLock);
6670 return loadHwModule_l(name);
6671}
6672
6673// loadHwModule_l() must be called with AudioFlinger::mLock held
6674audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6675{
6676 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6677 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6678 ALOGW("loadHwModule() module %s already loaded", name);
6679 return mAudioHwDevs.keyAt(i);
6680 }
6681 }
6682
Eric Laurenta4c5a552012-03-29 10:12:40 -07006683 audio_hw_device_t *dev;
6684
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006685 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006686 if (rc) {
6687 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6688 return 0;
6689 }
6690
6691 mHardwareStatus = AUDIO_HW_INIT;
6692 rc = dev->init_check(dev);
6693 mHardwareStatus = AUDIO_HW_IDLE;
6694 if (rc) {
6695 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6696 return 0;
6697 }
6698
6699 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6700 (NULL != dev->set_master_volume)) {
6701 AutoMutex lock(mHardwareLock);
6702 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6703 dev->set_master_volume(dev, mMasterVolume);
6704 mHardwareStatus = AUDIO_HW_IDLE;
6705 }
6706
6707 audio_module_handle_t handle = nextUniqueId();
6708 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6709
6710 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006711 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006712
6713 return handle;
6714
6715}
6716
6717audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6718 audio_devices_t *pDevices,
6719 uint32_t *pSamplingRate,
6720 audio_format_t *pFormat,
6721 audio_channel_mask_t *pChannelMask,
6722 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006723 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724{
6725 status_t status;
6726 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006727 struct audio_config config = {
6728 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6729 channel_mask: pChannelMask ? *pChannelMask : 0,
6730 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6731 };
6732 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006733 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734
Eric Laurenta4c5a552012-03-29 10:12:40 -07006735 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6736 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006737 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006738 config.sample_rate,
6739 config.format,
6740 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006741 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742
6743 if (pDevices == NULL || *pDevices == 0) {
6744 return 0;
6745 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006746
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 Mutex::Autolock _l(mLock);
6748
Eric Laurenta4c5a552012-03-29 10:12:40 -07006749 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006750 if (outHwDev == NULL)
6751 return 0;
6752
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006753 audio_io_handle_t id = nextUniqueId();
6754
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006755 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006756
6757 status = outHwDev->open_output_stream(outHwDev,
6758 id,
6759 *pDevices,
6760 (audio_output_flags_t)flags,
6761 &config,
6762 &outStream);
6763
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006764 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006765 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006766 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006767 config.sample_rate,
6768 config.format,
6769 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 status);
6771
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006772 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006773 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006774
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006775 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006776 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6777 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006778 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006779 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 } else {
6781 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006782 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 }
6784 mPlaybackThreads.add(id, thread);
6785
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006786 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6787 if (pFormat != NULL) *pFormat = config.format;
6788 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006789 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790
6791 // notify client processes of the new output creation
6792 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006793
6794 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006795 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006796 ALOGI("Using module %d has the primary audio interface", module);
6797 mPrimaryHardwareDev = outHwDev;
6798
6799 AutoMutex lock(mHardwareLock);
6800 mHardwareStatus = AUDIO_HW_SET_MODE;
6801 outHwDev->set_mode(outHwDev, mMode);
6802
6803 // Determine the level of master volume support the primary audio HAL has,
6804 // and set the initial master volume at the same time.
6805 float initialVolume = 1.0;
6806 mMasterVolumeSupportLvl = MVS_NONE;
6807
6808 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6809 if ((NULL != outHwDev->get_master_volume) &&
6810 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6811 mMasterVolumeSupportLvl = MVS_FULL;
6812 } else {
6813 mMasterVolumeSupportLvl = MVS_SETONLY;
6814 initialVolume = 1.0;
6815 }
6816
6817 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6818 if ((NULL == outHwDev->set_master_volume) ||
6819 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6820 mMasterVolumeSupportLvl = MVS_NONE;
6821 }
6822 // now that we have a primary device, initialize master volume on other devices
6823 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6824 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6825
6826 if ((dev != mPrimaryHardwareDev) &&
6827 (NULL != dev->set_master_volume)) {
6828 dev->set_master_volume(dev, initialVolume);
6829 }
6830 }
6831 mHardwareStatus = AUDIO_HW_IDLE;
6832 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6833 ? initialVolume
6834 : 1.0;
6835 mMasterVolume = initialVolume;
6836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 return id;
6838 }
6839
6840 return 0;
6841}
6842
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006843audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6844 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845{
6846 Mutex::Autolock _l(mLock);
6847 MixerThread *thread1 = checkMixerThread_l(output1);
6848 MixerThread *thread2 = checkMixerThread_l(output2);
6849
6850 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006851 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852 return 0;
6853 }
6854
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006855 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6857 thread->addOutputTrack(thread2);
6858 mPlaybackThreads.add(id, thread);
6859 // notify client processes of the new output creation
6860 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6861 return id;
6862}
6863
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006864status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865{
6866 // keep strong reference on the playback thread so that
6867 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006868 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 {
6870 Mutex::Autolock _l(mLock);
6871 thread = checkPlaybackThread_l(output);
6872 if (thread == NULL) {
6873 return BAD_VALUE;
6874 }
6875
Steve Block3856b092011-10-20 11:56:00 +01006876 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006878 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006880 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6882 dupThread->removeOutputTrack((MixerThread *)thread.get());
6883 }
6884 }
6885 }
Glenn Kastena1117922012-01-26 10:53:32 -08006886 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 mPlaybackThreads.removeItem(output);
6888 }
6889 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006890 // The thread entity (active unit of execution) is no longer running here,
6891 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006893 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006894 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006895 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006896 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006897 out->hwDev->close_output_stream(out->hwDev, out->stream);
6898 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 }
6900 return NO_ERROR;
6901}
6902
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006903status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904{
6905 Mutex::Autolock _l(mLock);
6906 PlaybackThread *thread = checkPlaybackThread_l(output);
6907
6908 if (thread == NULL) {
6909 return BAD_VALUE;
6910 }
6911
Steve Block3856b092011-10-20 11:56:00 +01006912 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 thread->suspend();
6914
6915 return NO_ERROR;
6916}
6917
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006918status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919{
6920 Mutex::Autolock _l(mLock);
6921 PlaybackThread *thread = checkPlaybackThread_l(output);
6922
6923 if (thread == NULL) {
6924 return BAD_VALUE;
6925 }
6926
Steve Block3856b092011-10-20 11:56:00 +01006927 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928
6929 thread->restore();
6930
6931 return NO_ERROR;
6932}
6933
Eric Laurenta4c5a552012-03-29 10:12:40 -07006934audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6935 audio_devices_t *pDevices,
6936 uint32_t *pSamplingRate,
6937 audio_format_t *pFormat,
6938 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939{
6940 status_t status;
6941 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006942 struct audio_config config = {
6943 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6944 channel_mask: pChannelMask ? *pChannelMask : 0,
6945 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6946 };
6947 uint32_t reqSamplingRate = config.sample_rate;
6948 audio_format_t reqFormat = config.format;
6949 audio_channel_mask_t reqChannels = config.channel_mask;
6950 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006951 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952
6953 if (pDevices == NULL || *pDevices == 0) {
6954 return 0;
6955 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006956
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 Mutex::Autolock _l(mLock);
6958
Eric Laurenta4c5a552012-03-29 10:12:40 -07006959 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006960 if (inHwDev == NULL)
6961 return 0;
6962
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006963 audio_io_handle_t id = nextUniqueId();
6964
6965 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006966 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006967 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006968 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006969 config.sample_rate,
6970 config.format,
6971 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 status);
6973
6974 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6975 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6976 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006977 if (status == BAD_VALUE &&
6978 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6979 (config.sample_rate <= 2 * reqSamplingRate) &&
6980 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006981 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006982 inStream = NULL;
6983 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 }
6985
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006986 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006987 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6988
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006989 // Start record thread
6990 // RecorThread require both input and output device indication to forward to audio
6991 // pre processing modules
6992 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6993 thread = new RecordThread(this,
6994 input,
6995 reqSamplingRate,
6996 reqChannels,
6997 id,
6998 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007000 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007001 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007002 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007003 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004
Dima Zavin799a70e2011-04-18 16:57:27 -07007005 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006
7007 // notify client processes of the new input creation
7008 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7009 return id;
7010 }
7011
7012 return 0;
7013}
7014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007015status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007016{
7017 // keep strong reference on the record thread so that
7018 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007019 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 {
7021 Mutex::Autolock _l(mLock);
7022 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007023 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 return BAD_VALUE;
7025 }
7026
Steve Block3856b092011-10-20 11:56:00 +01007027 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007028 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029 mRecordThreads.removeItem(input);
7030 }
7031 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007032 // The thread entity (active unit of execution) is no longer running here,
7033 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007035 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007036 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007037 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007038 in->hwDev->close_input_stream(in->hwDev, in->stream);
7039 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040
7041 return NO_ERROR;
7042}
7043
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007044status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045{
7046 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007047 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048
7049 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7050 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007051 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053
7054 return NO_ERROR;
7055}
7056
7057
7058int AudioFlinger::newAudioSessionId()
7059{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007060 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061}
7062
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007063void AudioFlinger::acquireAudioSessionId(int audioSession)
7064{
7065 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007066 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007067 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007068 size_t num = mAudioSessionRefs.size();
7069 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007070 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007071 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7072 ref->mCnt++;
7073 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007074 return;
7075 }
7076 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007077 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7078 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007079}
7080
7081void AudioFlinger::releaseAudioSessionId(int audioSession)
7082{
7083 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007084 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007085 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007086 size_t num = mAudioSessionRefs.size();
7087 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007088 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007089 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7090 ref->mCnt--;
7091 ALOGV(" decremented refcount to %d", ref->mCnt);
7092 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007093 mAudioSessionRefs.removeAt(i);
7094 delete ref;
7095 purgeStaleEffects_l();
7096 }
7097 return;
7098 }
7099 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007100 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007101}
7102
7103void AudioFlinger::purgeStaleEffects_l() {
7104
Steve Block3856b092011-10-20 11:56:00 +01007105 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007106
7107 Vector< sp<EffectChain> > chains;
7108
7109 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7110 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7111 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7112 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007113 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7114 chains.push(ec);
7115 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007116 }
7117 }
7118 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7119 sp<RecordThread> t = mRecordThreads.valueAt(i);
7120 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7121 sp<EffectChain> ec = t->mEffectChains[j];
7122 chains.push(ec);
7123 }
7124 }
7125
7126 for (size_t i = 0; i < chains.size(); i++) {
7127 sp<EffectChain> ec = chains[i];
7128 int sessionid = ec->sessionId();
7129 sp<ThreadBase> t = ec->mThread.promote();
7130 if (t == 0) {
7131 continue;
7132 }
7133 size_t numsessionrefs = mAudioSessionRefs.size();
7134 bool found = false;
7135 for (size_t k = 0; k < numsessionrefs; k++) {
7136 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007137 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007138 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007139 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007140 found = true;
7141 break;
7142 }
7143 }
7144 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007145 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007146 // remove all effects from the chain
7147 while (ec->mEffects.size()) {
7148 sp<EffectModule> effect = ec->mEffects[0];
7149 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007150 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007151 if (effect->purgeHandles()) {
7152 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007153 }
7154 AudioSystem::unregisterEffect(effect->id());
7155 }
7156 }
7157 }
7158 return;
7159}
7160
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007162AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
Glenn Kastena1117922012-01-26 10:53:32 -08007164 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165}
7166
7167// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007168AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169{
7170 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007171 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
7174// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007175AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176{
Glenn Kastena1117922012-01-26 10:53:32 -08007177 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178}
7179
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183}
7184
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007185AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007186{
7187 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7188 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007189 AudioStreamOut *output = thread->getOutput();
7190 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007191 return thread;
7192 }
7193 }
7194 return NULL;
7195}
7196
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007197uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007198{
7199 PlaybackThread *thread = primaryPlaybackThread_l();
7200
7201 if (thread == NULL) {
7202 return 0;
7203 }
7204
7205 return thread->device();
7206}
7207
Eric Laurenta011e352012-03-29 15:51:43 -07007208sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7209 int triggerSession,
7210 int listenerSession,
7211 sync_event_callback_t callBack,
7212 void *cookie)
7213{
7214 Mutex::Autolock _l(mLock);
7215
7216 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7217 status_t playStatus = NAME_NOT_FOUND;
7218 status_t recStatus = NAME_NOT_FOUND;
7219 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7220 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7221 if (playStatus == NO_ERROR) {
7222 return event;
7223 }
7224 }
7225 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7226 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7227 if (recStatus == NO_ERROR) {
7228 return event;
7229 }
7230 }
7231 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7232 mPendingSyncEvents.add(event);
7233 } else {
7234 ALOGV("createSyncEvent() invalid event %d", event->type());
7235 event.clear();
7236 }
7237 return event;
7238}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007239
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240// ----------------------------------------------------------------------------
7241// Effect management
7242// ----------------------------------------------------------------------------
7243
7244
Glenn Kastenf587ba52012-01-26 16:25:10 -08007245status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246{
7247 Mutex::Autolock _l(mLock);
7248 return EffectQueryNumberEffects(numEffects);
7249}
7250
Glenn Kastenf587ba52012-01-26 16:25:10 -08007251status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252{
7253 Mutex::Autolock _l(mLock);
7254 return EffectQueryEffect(index, descriptor);
7255}
7256
Glenn Kasten5e92a782012-01-30 07:40:52 -08007257status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007258 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259{
7260 Mutex::Autolock _l(mLock);
7261 return EffectGetDescriptor(pUuid, descriptor);
7262}
7263
7264
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7266 effect_descriptor_t *pDesc,
7267 const sp<IEffectClient>& effectClient,
7268 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007269 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270 int sessionId,
7271 status_t *status,
7272 int *id,
7273 int *enabled)
7274{
7275 status_t lStatus = NO_ERROR;
7276 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007279 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007280 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281
7282 if (pDesc == NULL) {
7283 lStatus = BAD_VALUE;
7284 goto Exit;
7285 }
7286
Eric Laurent84e9a102010-09-23 16:10:16 -07007287 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007288 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007289 lStatus = PERMISSION_DENIED;
7290 goto Exit;
7291 }
7292
Dima Zavinfce7a472011-04-19 22:30:36 -07007293 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007294 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007295 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007296 lStatus = PERMISSION_DENIED;
7297 goto Exit;
7298 }
7299
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007300 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007301 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007302 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007303 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007304 lStatus = BAD_VALUE;
7305 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007306 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007307 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007308 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007309 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007311 }
7312 }
7313
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 {
7315 Mutex::Autolock _l(mLock);
7316
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317
7318 if (!EffectIsNullUuid(&pDesc->uuid)) {
7319 // if uuid is specified, request effect descriptor
7320 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7321 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007322 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323 goto Exit;
7324 }
7325 } else {
7326 // if uuid is not specified, look for an available implementation
7327 // of the required type in effect factory
7328 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007329 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 lStatus = BAD_VALUE;
7331 goto Exit;
7332 }
7333 uint32_t numEffects = 0;
7334 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007335 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 bool found = false;
7337
7338 lStatus = EffectQueryNumberEffects(&numEffects);
7339 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007340 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 goto Exit;
7342 }
7343 for (uint32_t i = 0; i < numEffects; i++) {
7344 lStatus = EffectQueryEffect(i, &desc);
7345 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007346 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 continue;
7348 }
7349 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7350 // If matching type found save effect descriptor. If the session is
7351 // 0 and the effect is not auxiliary, continue enumeration in case
7352 // an auxiliary version of this effect type is available
7353 found = true;
7354 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007355 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7357 break;
7358 }
7359 }
7360 }
7361 if (!found) {
7362 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007363 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 goto Exit;
7365 }
7366 // For same effect type, chose auxiliary version over insert version if
7367 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007368 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7370 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7371 }
7372 }
7373
7374 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007375 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7377 lStatus = INVALID_OPERATION;
7378 goto Exit;
7379 }
7380
Eric Laurent59255e42011-07-27 19:49:51 -07007381 // check recording permission for visualizer
7382 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7383 !recordingAllowed()) {
7384 lStatus = PERMISSION_DENIED;
7385 goto Exit;
7386 }
7387
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 // return effect descriptor
7389 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7390
7391 // If output is not specified try to find a matching audio session ID in one of the
7392 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007393 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7394 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395 // Note: io is never 0 when creating an effect on an input
7396 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007397 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7399 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007401 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007404 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7406 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7407 io = mRecordThreads.keyAt(i);
7408 break;
7409 }
7410 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007411 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007412 // If no output thread contains the requested session ID, default to
7413 // first output. The effect chain will be moved to the correct output
7414 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415 if (io == 0 && mPlaybackThreads.size()) {
7416 io = mPlaybackThreads.keyAt(0);
7417 }
Steve Block3856b092011-10-20 11:56:00 +01007418 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 }
7420 ThreadBase *thread = checkRecordThread_l(io);
7421 if (thread == NULL) {
7422 thread = checkPlaybackThread_l(io);
7423 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007424 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007425 lStatus = BAD_VALUE;
7426 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007428 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007429
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007430 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007432 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007433 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7434 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435 if (handle != 0 && id != NULL) {
7436 *id = handle->id();
7437 }
7438 }
7439
7440Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007441 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 *status = lStatus;
7443 }
7444 return handle;
7445}
7446
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007447status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7448 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007449{
Steve Block3856b092011-10-20 11:56:00 +01007450 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007451 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007452 Mutex::Autolock _l(mLock);
7453 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007454 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007455 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 }
Eric Laurentde070132010-07-13 04:45:46 -07007457 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7458 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007459 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007460 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 }
Eric Laurentde070132010-07-13 04:45:46 -07007462 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7463 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007464 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007465 return BAD_VALUE;
7466 }
7467
7468 Mutex::Autolock _dl(dstThread->mLock);
7469 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007470 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007471
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472 return NO_ERROR;
7473}
7474
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007475// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007476status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007477 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007478 AudioFlinger::PlaybackThread *dstThread,
7479 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007480{
Steve Block3856b092011-10-20 11:56:00 +01007481 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007482 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007483
Eric Laurent59255e42011-07-27 19:49:51 -07007484 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007485 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007486 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007487 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007488 return INVALID_OPERATION;
7489 }
7490
Eric Laurent39e94f82010-07-28 01:32:47 -07007491 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007492 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007493 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007494 // removed.
7495 srcThread->removeEffectChain_l(chain);
7496
7497 // transfer all effects one by one so that new effect chain is created on new thread with
7498 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007499 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007500 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007501 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007502 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7503 while (effect != 0) {
7504 srcThread->removeEffect_l(effect);
7505 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007506 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7507 if (effect->state() == EffectModule::ACTIVE ||
7508 effect->state() == EffectModule::STOPPING) {
7509 effect->start();
7510 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007511 // if the move request is not received from audio policy manager, the effect must be
7512 // re-registered with the new strategy and output
7513 if (dstChain == 0) {
7514 dstChain = effect->chain().promote();
7515 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007516 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007517 srcThread->addEffect_l(effect);
7518 return NO_INIT;
7519 }
7520 strategy = dstChain->strategy();
7521 }
7522 if (reRegister) {
7523 AudioSystem::unregisterEffect(effect->id());
7524 AudioSystem::registerEffect(&effect->desc(),
7525 dstOutput,
7526 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007527 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007528 effect->id());
7529 }
Eric Laurentde070132010-07-13 04:45:46 -07007530 effect = chain->getEffectFromId_l(0);
7531 }
7532
7533 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534}
7535
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007538sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 const sp<AudioFlinger::Client>& client,
7540 const sp<IEffectClient>& effectClient,
7541 int32_t priority,
7542 int sessionId,
7543 effect_descriptor_t *desc,
7544 int *enabled,
7545 status_t *status
7546 )
7547{
7548 sp<EffectModule> effect;
7549 sp<EffectHandle> handle;
7550 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007552 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 bool effectCreated = false;
7554 bool effectRegistered = false;
7555
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007556 lStatus = initCheck();
7557 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007558 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559 goto Exit;
7560 }
7561
7562 // Do not allow effects with session ID 0 on direct output or duplicating threads
7563 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007564 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007565 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007566 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 lStatus = BAD_VALUE;
7568 goto Exit;
7569 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007570 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007571 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007572 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007573 desc->name, desc->flags, mType);
7574 lStatus = BAD_VALUE;
7575 goto Exit;
7576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577
Steve Block3856b092011-10-20 11:56:00 +01007578 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007579
7580 { // scope for mLock
7581 Mutex::Autolock _l(mLock);
7582
7583 // check for existing effect chain with the requested audio session
7584 chain = getEffectChain_l(sessionId);
7585 if (chain == 0) {
7586 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007587 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 chain = new EffectChain(this, sessionId);
7589 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007590 chain->setStrategy(getStrategyForSession_l(sessionId));
7591 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007593 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 }
7595
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007596 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597
7598 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007599 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007601 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 if (lStatus != NO_ERROR) {
7603 goto Exit;
7604 }
7605 effectRegistered = true;
7606 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007607 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 lStatus = effect->status();
7609 if (lStatus != NO_ERROR) {
7610 goto Exit;
7611 }
Eric Laurentcab11242010-07-15 12:50:15 -07007612 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 if (lStatus != NO_ERROR) {
7614 goto Exit;
7615 }
7616 effectCreated = true;
7617
7618 effect->setDevice(mDevice);
7619 effect->setMode(mAudioFlinger->getMode());
7620 }
7621 // create effect handle and connect it to effect module
7622 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007623 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007624 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625 *enabled = (int)effect->isEnabled();
7626 }
7627 }
7628
7629Exit:
7630 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007631 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007633 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 }
7635 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007636 AudioSystem::unregisterEffect(effect->id());
7637 }
7638 if (chainCreated) {
7639 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 }
7641 handle.clear();
7642 }
7643
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007644 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 *status = lStatus;
7646 }
7647 return handle;
7648}
7649
Eric Laurent717e1282012-06-29 16:36:52 -07007650sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7651{
7652 Mutex::Autolock _l(mLock);
7653 return getEffect_l(sessionId, effectId);
7654}
7655
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007656sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7657{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007658 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007659 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007660}
7661
Eric Laurentde070132010-07-13 04:45:46 -07007662// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7663// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007664status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007665{
7666 // check for existing effect chain with the requested audio session
7667 int sessionId = effect->sessionId();
7668 sp<EffectChain> chain = getEffectChain_l(sessionId);
7669 bool chainCreated = false;
7670
7671 if (chain == 0) {
7672 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007674 chain = new EffectChain(this, sessionId);
7675 addEffectChain_l(chain);
7676 chain->setStrategy(getStrategyForSession_l(sessionId));
7677 chainCreated = true;
7678 }
Steve Block3856b092011-10-20 11:56:00 +01007679 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007680
7681 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007682 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007683 this, effect->desc().name, chain.get());
7684 return BAD_VALUE;
7685 }
7686
7687 status_t status = chain->addEffect_l(effect);
7688 if (status != NO_ERROR) {
7689 if (chainCreated) {
7690 removeEffectChain_l(chain);
7691 }
7692 return status;
7693 }
7694
7695 effect->setDevice(mDevice);
7696 effect->setMode(mAudioFlinger->getMode());
7697 return NO_ERROR;
7698}
7699
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007700void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007701
Steve Block3856b092011-10-20 11:56:00 +01007702 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007704 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7705 detachAuxEffect_l(effect->id());
7706 }
7707
7708 sp<EffectChain> chain = effect->chain().promote();
7709 if (chain != 0) {
7710 // remove effect chain if removing last effect
7711 if (chain->removeEffect_l(effect) == 0) {
7712 removeEffectChain_l(chain);
7713 }
7714 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007715 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007716 }
7717}
7718
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007720 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007721{
7722 effectChains = mEffectChains;
7723 for (size_t i = 0; i < mEffectChains.size(); i++) {
7724 mEffectChains[i]->lock();
7725 }
7726}
7727
7728void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007729 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007730{
7731 for (size_t i = 0; i < effectChains.size(); i++) {
7732 effectChains[i]->unlock();
7733 }
7734}
7735
7736sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7737{
7738 Mutex::Autolock _l(mLock);
7739 return getEffectChain_l(sessionId);
7740}
7741
7742sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7743{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007744 size_t size = mEffectChains.size();
7745 for (size_t i = 0; i < size; i++) {
7746 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007747 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007748 }
7749 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007750 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007751}
7752
Glenn Kastenf78aee72012-01-04 11:00:47 -08007753void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007754{
7755 Mutex::Autolock _l(mLock);
7756 size_t size = mEffectChains.size();
7757 for (size_t i = 0; i < size; i++) {
7758 mEffectChains[i]->setMode_l(mode);
7759 }
7760}
7761
7762void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007763 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007764 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007765
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007767 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 // delete the effect module if removing last handle on it
7769 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007770 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007771 removeEffect_l(effect);
7772 AudioSystem::unregisterEffect(effect->id());
7773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 }
7775}
7776
7777status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7778{
7779 int session = chain->sessionId();
7780 int16_t *buffer = mMixBuffer;
7781 bool ownsBuffer = false;
7782
Steve Block3856b092011-10-20 11:56:00 +01007783 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 if (session > 0) {
7785 // Only one effect chain can be present in direct output thread and it uses
7786 // the mix buffer as input
7787 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007788 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 buffer = new int16_t[numSamples];
7790 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007791 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 ownsBuffer = true;
7793 }
7794
7795 // Attach all tracks with same session ID to this chain.
7796 for (size_t i = 0; i < mTracks.size(); ++i) {
7797 sp<Track> track = mTracks[i];
7798 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007799 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007801 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 }
7803 }
7804
7805 // indicate all active tracks in the chain
7806 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7807 sp<Track> track = mActiveTracks[i].promote();
7808 if (track == 0) continue;
7809 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007810 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007811 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 }
7813 }
7814 }
7815
7816 chain->setInBuffer(buffer, ownsBuffer);
7817 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007818 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007819 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007820 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7821 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007823 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7824 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007825 // Effect chain for other sessions are inserted at beginning of effect
7826 // chains list to be processed before output mix effects. Relative order between other
7827 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 size_t size = mEffectChains.size();
7829 size_t i = 0;
7830 for (i = 0; i < size; i++) {
7831 if (mEffectChains[i]->sessionId() < session) break;
7832 }
7833 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007834 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835
7836 return NO_ERROR;
7837}
7838
7839size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7840{
7841 int session = chain->sessionId();
7842
Steve Block3856b092011-10-20 11:56:00 +01007843 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844
7845 for (size_t i = 0; i < mEffectChains.size(); i++) {
7846 if (chain == mEffectChains[i]) {
7847 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007848 // detach all active tracks from the chain
7849 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7850 sp<Track> track = mActiveTracks[i].promote();
7851 if (track == 0) continue;
7852 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007853 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007854 chain.get(), session);
7855 chain->decActiveTrackCnt();
7856 }
7857 }
7858
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859 // detach all tracks with same session ID from this chain
7860 for (size_t i = 0; i < mTracks.size(); ++i) {
7861 sp<Track> track = mTracks[i];
7862 if (session == track->sessionId()) {
7863 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007864 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 }
7866 }
Eric Laurentde070132010-07-13 04:45:46 -07007867 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868 }
7869 }
7870 return mEffectChains.size();
7871}
7872
Eric Laurentde070132010-07-13 04:45:46 -07007873status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7874 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875{
7876 Mutex::Autolock _l(mLock);
7877 return attachAuxEffect_l(track, EffectId);
7878}
7879
Eric Laurentde070132010-07-13 04:45:46 -07007880status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7881 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882{
7883 status_t status = NO_ERROR;
7884
7885 if (EffectId == 0) {
7886 track->setAuxBuffer(0, NULL);
7887 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007888 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7889 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007890 if (effect != 0) {
7891 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7892 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7893 } else {
7894 status = INVALID_OPERATION;
7895 }
7896 } else {
7897 status = BAD_VALUE;
7898 }
7899 }
7900 return status;
7901}
7902
7903void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7904{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007905 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 sp<Track> track = mTracks[i];
7907 if (track->auxEffectId() == effectId) {
7908 attachAuxEffect_l(track, 0);
7909 }
7910 }
7911}
7912
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007913status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7914{
7915 // only one chain per input thread
7916 if (mEffectChains.size() != 0) {
7917 return INVALID_OPERATION;
7918 }
Steve Block3856b092011-10-20 11:56:00 +01007919 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007920
7921 chain->setInBuffer(NULL);
7922 chain->setOutBuffer(NULL);
7923
Eric Laurent59255e42011-07-27 19:49:51 -07007924 checkSuspendOnAddEffectChain_l(chain);
7925
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007926 mEffectChains.add(chain);
7927
7928 return NO_ERROR;
7929}
7930
7931size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7932{
Steve Block3856b092011-10-20 11:56:00 +01007933 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007934 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007935 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7936 chain.get(), mEffectChains.size(), this);
7937 if (mEffectChains.size() == 1) {
7938 mEffectChains.removeAt(0);
7939 }
7940 return 0;
7941}
7942
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943// ----------------------------------------------------------------------------
7944// EffectModule implementation
7945// ----------------------------------------------------------------------------
7946
7947#undef LOG_TAG
7948#define LOG_TAG "AudioFlinger::EffectModule"
7949
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007950AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 const wp<AudioFlinger::EffectChain>& chain,
7952 effect_descriptor_t *desc,
7953 int id,
7954 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007955 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7956 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7957 // mDescriptor is set below
7958 // mConfig is set by configure() and not used before then
7959 mEffectInterface(NULL),
7960 mStatus(NO_INIT), mState(IDLE),
7961 // mMaxDisableWaitCnt is set by configure() and not used before then
7962 // mDisableWaitCnt is set by process() and updateState() and not used before then
7963 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964{
Steve Block3856b092011-10-20 11:56:00 +01007965 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007966 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007967 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968 return;
7969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970
7971 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7972
7973 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007974 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975
7976 if (mStatus != NO_ERROR) {
7977 return;
7978 }
7979 lStatus = init();
7980 if (lStatus < 0) {
7981 mStatus = lStatus;
7982 goto Error;
7983 }
7984
Steve Block3856b092011-10-20 11:56:00 +01007985 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986 return;
7987Error:
7988 EffectRelease(mEffectInterface);
7989 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007990 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991}
7992
7993AudioFlinger::EffectModule::~EffectModule()
7994{
Steve Block3856b092011-10-20 11:56:00 +01007995 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007997 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7998 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7999 sp<ThreadBase> thread = mThread.promote();
8000 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008001 audio_stream_t *stream = thread->stream();
8002 if (stream != NULL) {
8003 stream->remove_audio_effect(stream, mEffectInterface);
8004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008005 }
8006 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 // release effect engine
8008 EffectRelease(mEffectInterface);
8009 }
8010}
8011
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008012status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013{
8014 status_t status;
8015
8016 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017 int priority = handle->priority();
8018 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008019 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008020 size_t i;
8021 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008022 EffectHandle *h = mHandles[i];
8023 if (h == NULL || h->destroyed_l()) continue;
8024 // first non destroyed handle is considered in control
8025 if (controlHandle == NULL)
8026 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 if (h->priority() <= priority) break;
8028 }
8029 // if inserted in first place, move effect control from previous owner to this handle
8030 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008031 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008032 if (controlHandle != NULL) {
8033 enabled = controlHandle->enabled();
8034 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 }
Eric Laurent59255e42011-07-27 19:49:51 -07008036 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 status = NO_ERROR;
8038 } else {
8039 status = ALREADY_EXISTS;
8040 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008041 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 mHandles.insertAt(handle, i);
8043 return status;
8044}
8045
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008046size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047{
8048 Mutex::Autolock _l(mLock);
8049 size_t size = mHandles.size();
8050 size_t i;
8051 for (i = 0; i < size; i++) {
8052 if (mHandles[i] == handle) break;
8053 }
8054 if (i == size) {
8055 return size;
8056 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008057 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008058
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008061 if (i == 0) {
8062 EffectHandle *h = controlHandle_l();
8063 if (h != NULL) {
8064 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 }
8066 }
8067
Eric Laurentec437d82011-07-26 20:54:46 -07008068 // Prevent calls to process() and other functions on effect interface from now on.
8069 // The effect engine will be released by the destructor when the last strong reference on
8070 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008071 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008072 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008073 }
8074
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 return size;
8076}
8077
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008078// must be called with EffectModule::mLock held
8079AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008080{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008081 // the first valid handle in the list has control over the module
8082 for (size_t i = 0; i < mHandles.size(); i++) {
8083 EffectHandle *h = mHandles[i];
8084 if (h != NULL && !h->destroyed_l()) {
8085 return h;
8086 }
8087 }
8088
8089 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008090}
8091
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008092size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008094 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095 // keep a strong reference on this EffectModule to avoid calling the
8096 // destructor before we exit
8097 sp<EffectModule> keep(this);
8098 {
8099 sp<ThreadBase> thread = mThread.promote();
8100 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008101 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102 }
8103 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008104 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105}
8106
8107void AudioFlinger::EffectModule::updateState() {
8108 Mutex::Autolock _l(mLock);
8109
8110 switch (mState) {
8111 case RESTART:
8112 reset_l();
8113 // FALL THROUGH
8114
8115 case STARTING:
8116 // clear auxiliary effect input buffer for next accumulation
8117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8118 memset(mConfig.inputCfg.buffer.raw,
8119 0,
8120 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8121 }
8122 start_l();
8123 mState = ACTIVE;
8124 break;
8125 case STOPPING:
8126 stop_l();
8127 mDisableWaitCnt = mMaxDisableWaitCnt;
8128 mState = STOPPED;
8129 break;
8130 case STOPPED:
8131 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8132 // turn off sequence.
8133 if (--mDisableWaitCnt == 0) {
8134 reset_l();
8135 mState = IDLE;
8136 }
8137 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008138 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139 break;
8140 }
8141}
8142
8143void AudioFlinger::EffectModule::process()
8144{
8145 Mutex::Autolock _l(mLock);
8146
Eric Laurentec437d82011-07-26 20:54:46 -07008147 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148 mConfig.inputCfg.buffer.raw == NULL ||
8149 mConfig.outputCfg.buffer.raw == NULL) {
8150 return;
8151 }
8152
Eric Laurent8f45bd72010-08-31 13:50:07 -07008153 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8155 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008156 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008158 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 }
8160
8161 // do the actual processing in the effect engine
8162 int ret = (*mEffectInterface)->process(mEffectInterface,
8163 &mConfig.inputCfg.buffer,
8164 &mConfig.outputCfg.buffer);
8165
8166 // force transition to IDLE state when engine is ready
8167 if (mState == STOPPED && ret == -ENODATA) {
8168 mDisableWaitCnt = 1;
8169 }
8170
8171 // clear auxiliary effect input buffer for next accumulation
8172 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008173 memset(mConfig.inputCfg.buffer.raw, 0,
8174 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008175 }
8176 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008177 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8178 // If an insert effect is idle and input buffer is different from output buffer,
8179 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008181 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008182 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8183 int16_t *in = mConfig.inputCfg.buffer.s16;
8184 int16_t *out = mConfig.outputCfg.buffer.s16;
8185 for (size_t i = 0; i < frameCnt; i++) {
8186 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188 }
8189 }
8190}
8191
8192void AudioFlinger::EffectModule::reset_l()
8193{
8194 if (mEffectInterface == NULL) {
8195 return;
8196 }
8197 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8198}
8199
8200status_t AudioFlinger::EffectModule::configure()
8201{
8202 uint32_t channels;
8203 if (mEffectInterface == NULL) {
8204 return NO_INIT;
8205 }
8206
8207 sp<ThreadBase> thread = mThread.promote();
8208 if (thread == 0) {
8209 return DEAD_OBJECT;
8210 }
8211
8212 // TODO: handle configuration of effects replacing track process
8213 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008214 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008216 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 }
8218
8219 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008220 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 } else {
8222 mConfig.inputCfg.channels = channels;
8223 }
8224 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008225 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8226 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008227 mConfig.inputCfg.samplingRate = thread->sampleRate();
8228 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8229 mConfig.inputCfg.bufferProvider.cookie = NULL;
8230 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8231 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8232 mConfig.outputCfg.bufferProvider.cookie = NULL;
8233 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8234 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8235 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8236 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008237 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008238 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 // - in other sessions:
8240 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8241 // other effect: overwrites output buffer: input buffer == output buffer
8242 // Auxiliary effect:
8243 // accumulates in output buffer: input buffer != output buffer
8244 // Therefore: accumulate <=> input buffer != output buffer
8245 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8246 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8247 } else {
8248 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8249 }
8250 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8251 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8252 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8253 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8254
Steve Block3856b092011-10-20 11:56:00 +01008255 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008256 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8257
Mathias Agopian65ab4712010-07-14 17:59:35 -07008258 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008259 uint32_t size = sizeof(int);
8260 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008261 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008262 sizeof(effect_config_t),
8263 &mConfig,
8264 &size,
8265 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008266 if (status == 0) {
8267 status = cmdStatus;
8268 }
8269
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008270 if (status == 0 &&
8271 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8272 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8273 effect_param_t *p = (effect_param_t *)buf32;
8274
8275 p->psize = sizeof(uint32_t);
8276 p->vsize = sizeof(uint32_t);
8277 size = sizeof(int);
8278 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8279
8280 uint32_t latency = 0;
8281 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8282 if (pbt != NULL) {
8283 latency = pbt->latency_l();
8284 }
8285
8286 *((int32_t *)p->data + 1)= latency;
8287 (*mEffectInterface)->command(mEffectInterface,
8288 EFFECT_CMD_SET_PARAM,
8289 sizeof(effect_param_t) + 8,
8290 &buf32,
8291 &size,
8292 &cmdStatus);
8293 }
8294
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8296 (1000 * mConfig.outputCfg.buffer.frameCount);
8297
8298 return status;
8299}
8300
8301status_t AudioFlinger::EffectModule::init()
8302{
8303 Mutex::Autolock _l(mLock);
8304 if (mEffectInterface == NULL) {
8305 return NO_INIT;
8306 }
8307 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008308 uint32_t size = sizeof(status_t);
8309 status_t status = (*mEffectInterface)->command(mEffectInterface,
8310 EFFECT_CMD_INIT,
8311 0,
8312 NULL,
8313 &size,
8314 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315 if (status == 0) {
8316 status = cmdStatus;
8317 }
8318 return status;
8319}
8320
Eric Laurentec35a142011-10-05 17:42:25 -07008321status_t AudioFlinger::EffectModule::start()
8322{
8323 Mutex::Autolock _l(mLock);
8324 return start_l();
8325}
8326
Mathias Agopian65ab4712010-07-14 17:59:35 -07008327status_t AudioFlinger::EffectModule::start_l()
8328{
8329 if (mEffectInterface == NULL) {
8330 return NO_INIT;
8331 }
8332 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008333 uint32_t size = sizeof(status_t);
8334 status_t status = (*mEffectInterface)->command(mEffectInterface,
8335 EFFECT_CMD_ENABLE,
8336 0,
8337 NULL,
8338 &size,
8339 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340 if (status == 0) {
8341 status = cmdStatus;
8342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008343 if (status == 0 &&
8344 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8345 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8346 sp<ThreadBase> thread = mThread.promote();
8347 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008348 audio_stream_t *stream = thread->stream();
8349 if (stream != NULL) {
8350 stream->add_audio_effect(stream, mEffectInterface);
8351 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008352 }
8353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008354 return status;
8355}
8356
Eric Laurentec437d82011-07-26 20:54:46 -07008357status_t AudioFlinger::EffectModule::stop()
8358{
8359 Mutex::Autolock _l(mLock);
8360 return stop_l();
8361}
8362
Mathias Agopian65ab4712010-07-14 17:59:35 -07008363status_t AudioFlinger::EffectModule::stop_l()
8364{
8365 if (mEffectInterface == NULL) {
8366 return NO_INIT;
8367 }
8368 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008369 uint32_t size = sizeof(status_t);
8370 status_t status = (*mEffectInterface)->command(mEffectInterface,
8371 EFFECT_CMD_DISABLE,
8372 0,
8373 NULL,
8374 &size,
8375 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 if (status == 0) {
8377 status = cmdStatus;
8378 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008379 if (status == 0 &&
8380 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8381 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8382 sp<ThreadBase> thread = mThread.promote();
8383 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008384 audio_stream_t *stream = thread->stream();
8385 if (stream != NULL) {
8386 stream->remove_audio_effect(stream, mEffectInterface);
8387 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008388 }
8389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 return status;
8391}
8392
Eric Laurent25f43952010-07-28 05:40:18 -07008393status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8394 uint32_t cmdSize,
8395 void *pCmdData,
8396 uint32_t *replySize,
8397 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008398{
8399 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008400// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401
Eric Laurentec437d82011-07-26 20:54:46 -07008402 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403 return NO_INIT;
8404 }
Eric Laurent25f43952010-07-28 05:40:18 -07008405 status_t status = (*mEffectInterface)->command(mEffectInterface,
8406 cmdCode,
8407 cmdSize,
8408 pCmdData,
8409 replySize,
8410 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008412 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008414 EffectHandle *h = mHandles[i];
8415 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8417 }
8418 }
8419 }
8420 return status;
8421}
8422
8423status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8424{
8425 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008426 return setEnabled_l(enabled);
8427}
8428
8429// must be called with EffectModule::mLock held
8430status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8431{
8432
Steve Block3856b092011-10-20 11:56:00 +01008433 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008434
8435 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008436 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8437 if (enabled && status != NO_ERROR) {
8438 return status;
8439 }
8440
Mathias Agopian65ab4712010-07-14 17:59:35 -07008441 switch (mState) {
8442 // going from disabled to enabled
8443 case IDLE:
8444 mState = STARTING;
8445 break;
8446 case STOPPED:
8447 mState = RESTART;
8448 break;
8449 case STOPPING:
8450 mState = ACTIVE;
8451 break;
8452
8453 // going from enabled to disabled
8454 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008455 mState = STOPPED;
8456 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457 case STARTING:
8458 mState = IDLE;
8459 break;
8460 case ACTIVE:
8461 mState = STOPPING;
8462 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008463 case DESTROYED:
8464 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 }
8466 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008467 EffectHandle *h = mHandles[i];
8468 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008469 h->setEnabled(enabled);
8470 }
8471 }
8472 }
8473 return NO_ERROR;
8474}
8475
Glenn Kastenc59c0042012-02-02 14:06:11 -08008476bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477{
8478 switch (mState) {
8479 case RESTART:
8480 case STARTING:
8481 case ACTIVE:
8482 return true;
8483 case IDLE:
8484 case STOPPING:
8485 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008486 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487 default:
8488 return false;
8489 }
8490}
8491
Glenn Kastenc59c0042012-02-02 14:06:11 -08008492bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008493{
8494 switch (mState) {
8495 case RESTART:
8496 case ACTIVE:
8497 case STOPPING:
8498 case STOPPED:
8499 return true;
8500 case IDLE:
8501 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008502 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008503 default:
8504 return false;
8505 }
8506}
8507
Mathias Agopian65ab4712010-07-14 17:59:35 -07008508status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8509{
8510 Mutex::Autolock _l(mLock);
8511 status_t status = NO_ERROR;
8512
8513 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8514 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008515 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008516 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8517 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 status_t cmdStatus;
8519 uint32_t volume[2];
8520 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008521 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 volume[0] = *left;
8523 volume[1] = *right;
8524 if (controller) {
8525 pVolume = volume;
8526 }
Eric Laurent25f43952010-07-28 05:40:18 -07008527 status = (*mEffectInterface)->command(mEffectInterface,
8528 EFFECT_CMD_SET_VOLUME,
8529 size,
8530 volume,
8531 &size,
8532 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8534 *left = volume[0];
8535 *right = volume[1];
8536 }
8537 }
8538 return status;
8539}
8540
8541status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8542{
8543 Mutex::Autolock _l(mLock);
8544 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008545 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8546 // audio pre processing modules on RecordThread can receive both output and
8547 // input device indication in the same call
8548 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8549 if (dev) {
8550 status_t cmdStatus;
8551 uint32_t size = sizeof(status_t);
8552
8553 status = (*mEffectInterface)->command(mEffectInterface,
8554 EFFECT_CMD_SET_DEVICE,
8555 sizeof(uint32_t),
8556 &dev,
8557 &size,
8558 &cmdStatus);
8559 if (status == NO_ERROR) {
8560 status = cmdStatus;
8561 }
8562 }
8563 dev = device & AUDIO_DEVICE_IN_ALL;
8564 if (dev) {
8565 status_t cmdStatus;
8566 uint32_t size = sizeof(status_t);
8567
8568 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8569 EFFECT_CMD_SET_INPUT_DEVICE,
8570 sizeof(uint32_t),
8571 &dev,
8572 &size,
8573 &cmdStatus);
8574 if (status2 == NO_ERROR) {
8575 status2 = cmdStatus;
8576 }
8577 if (status == NO_ERROR) {
8578 status = status2;
8579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008580 }
8581 }
8582 return status;
8583}
8584
Glenn Kastenf78aee72012-01-04 11:00:47 -08008585status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586{
8587 Mutex::Autolock _l(mLock);
8588 status_t status = NO_ERROR;
8589 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008591 uint32_t size = sizeof(status_t);
8592 status = (*mEffectInterface)->command(mEffectInterface,
8593 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008594 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008595 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008596 &size,
8597 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008598 if (status == NO_ERROR) {
8599 status = cmdStatus;
8600 }
8601 }
8602 return status;
8603}
8604
Eric Laurent59255e42011-07-27 19:49:51 -07008605void AudioFlinger::EffectModule::setSuspended(bool suspended)
8606{
8607 Mutex::Autolock _l(mLock);
8608 mSuspended = suspended;
8609}
Glenn Kastena3a85482012-01-04 11:01:11 -08008610
8611bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008612{
8613 Mutex::Autolock _l(mLock);
8614 return mSuspended;
8615}
8616
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008617bool AudioFlinger::EffectModule::purgeHandles()
8618{
8619 bool enabled = false;
8620 Mutex::Autolock _l(mLock);
8621 for (size_t i = 0; i < mHandles.size(); i++) {
8622 EffectHandle *handle = mHandles[i];
8623 if (handle != NULL && !handle->destroyed_l()) {
8624 handle->effect().clear();
8625 if (handle->hasControl()) {
8626 enabled = handle->enabled();
8627 }
8628 }
8629 }
8630 return enabled;
8631}
8632
Mathias Agopian65ab4712010-07-14 17:59:35 -07008633status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8634{
8635 const size_t SIZE = 256;
8636 char buffer[SIZE];
8637 String8 result;
8638
8639 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8640 result.append(buffer);
8641
8642 bool locked = tryLock(mLock);
8643 // failed to lock - AudioFlinger is probably deadlocked
8644 if (!locked) {
8645 result.append("\t\tCould not lock Fx mutex:\n");
8646 }
8647
8648 result.append("\t\tSession Status State Engine:\n");
8649 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8650 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8651 result.append(buffer);
8652
8653 result.append("\t\tDescriptor:\n");
8654 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8655 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8656 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8657 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8658 result.append(buffer);
8659 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8660 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8661 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8662 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8663 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008664 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665 mDescriptor.apiVersion,
8666 mDescriptor.flags);
8667 result.append(buffer);
8668 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8669 mDescriptor.name);
8670 result.append(buffer);
8671 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8672 mDescriptor.implementor);
8673 result.append(buffer);
8674
8675 result.append("\t\t- Input configuration:\n");
8676 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8677 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8678 (uint32_t)mConfig.inputCfg.buffer.raw,
8679 mConfig.inputCfg.buffer.frameCount,
8680 mConfig.inputCfg.samplingRate,
8681 mConfig.inputCfg.channels,
8682 mConfig.inputCfg.format);
8683 result.append(buffer);
8684
8685 result.append("\t\t- Output configuration:\n");
8686 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8687 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8688 (uint32_t)mConfig.outputCfg.buffer.raw,
8689 mConfig.outputCfg.buffer.frameCount,
8690 mConfig.outputCfg.samplingRate,
8691 mConfig.outputCfg.channels,
8692 mConfig.outputCfg.format);
8693 result.append(buffer);
8694
8695 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8696 result.append(buffer);
8697 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8698 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008699 EffectHandle *handle = mHandles[i];
8700 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008701 handle->dump(buffer, SIZE);
8702 result.append(buffer);
8703 }
8704 }
8705
8706 result.append("\n");
8707
8708 write(fd, result.string(), result.length());
8709
8710 if (locked) {
8711 mLock.unlock();
8712 }
8713
8714 return NO_ERROR;
8715}
8716
8717// ----------------------------------------------------------------------------
8718// EffectHandle implementation
8719// ----------------------------------------------------------------------------
8720
8721#undef LOG_TAG
8722#define LOG_TAG "AudioFlinger::EffectHandle"
8723
8724AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8725 const sp<AudioFlinger::Client>& client,
8726 const sp<IEffectClient>& effectClient,
8727 int32_t priority)
8728 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008729 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008730 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008731{
Steve Block3856b092011-10-20 11:56:00 +01008732 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008734 if (client == 0) {
8735 return;
8736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8738 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8739 if (mCblkMemory != 0) {
8740 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8741
Glenn Kastena0d68332012-01-27 16:47:15 -08008742 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743 new(mCblk) effect_param_cblk_t();
8744 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008747 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748 return;
8749 }
8750}
8751
8752AudioFlinger::EffectHandle::~EffectHandle()
8753{
Steve Block3856b092011-10-20 11:56:00 +01008754 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008755
8756 if (mEffect == 0) {
8757 mDestroyed = true;
8758 return;
8759 }
8760 mEffect->lock();
8761 mDestroyed = true;
8762 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008763 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008764}
8765
8766status_t AudioFlinger::EffectHandle::enable()
8767{
Steve Block3856b092011-10-20 11:56:00 +01008768 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008769 if (!mHasControl) return INVALID_OPERATION;
8770 if (mEffect == 0) return DEAD_OBJECT;
8771
Eric Laurentdb7c0792011-08-10 10:37:50 -07008772 if (mEnabled) {
8773 return NO_ERROR;
8774 }
8775
Eric Laurent59255e42011-07-27 19:49:51 -07008776 mEnabled = true;
8777
8778 sp<ThreadBase> thread = mEffect->thread().promote();
8779 if (thread != 0) {
8780 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8781 }
8782
8783 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8784 if (mEffect->suspended()) {
8785 return NO_ERROR;
8786 }
8787
Eric Laurentdb7c0792011-08-10 10:37:50 -07008788 status_t status = mEffect->setEnabled(true);
8789 if (status != NO_ERROR) {
8790 if (thread != 0) {
8791 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8792 }
8793 mEnabled = false;
8794 }
8795 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008796}
8797
8798status_t AudioFlinger::EffectHandle::disable()
8799{
Steve Block3856b092011-10-20 11:56:00 +01008800 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008801 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008802 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008803
Eric Laurentdb7c0792011-08-10 10:37:50 -07008804 if (!mEnabled) {
8805 return NO_ERROR;
8806 }
Eric Laurent59255e42011-07-27 19:49:51 -07008807 mEnabled = false;
8808
8809 if (mEffect->suspended()) {
8810 return NO_ERROR;
8811 }
8812
8813 status_t status = mEffect->setEnabled(false);
8814
8815 sp<ThreadBase> thread = mEffect->thread().promote();
8816 if (thread != 0) {
8817 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8818 }
8819
8820 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821}
8822
8823void AudioFlinger::EffectHandle::disconnect()
8824{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008825 disconnect(true);
8826}
8827
Glenn Kasten58123c32012-02-03 10:32:24 -08008828void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008829{
Glenn Kasten58123c32012-02-03 10:32:24 -08008830 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008831 if (mEffect == 0) {
8832 return;
8833 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008834 // restore suspended effects if the disconnected handle was enabled and the last one.
8835 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008836 sp<ThreadBase> thread = mEffect->thread().promote();
8837 if (thread != 0) {
8838 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8839 }
Eric Laurent59255e42011-07-27 19:49:51 -07008840 }
8841
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842 // release sp on module => module destructor can be called now
8843 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008844 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008845 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008846 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008847 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8848 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008849 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008850 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008851 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8852 mClient.clear();
8853 }
8854}
8855
Eric Laurent25f43952010-07-28 05:40:18 -07008856status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8857 uint32_t cmdSize,
8858 void *pCmdData,
8859 uint32_t *replySize,
8860 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008861{
Steve Block3856b092011-10-20 11:56:00 +01008862// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008863// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008864
8865 // only get parameter command is permitted for applications not controlling the effect
8866 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8867 return INVALID_OPERATION;
8868 }
8869 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008870 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008871
8872 // handle commands that are not forwarded transparently to effect engine
8873 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8874 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8875 // no risk to block the whole media server process or mixer threads is we are stuck here
8876 Mutex::Autolock _l(mCblk->lock);
8877 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8878 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8879 mCblk->serverIndex = 0;
8880 mCblk->clientIndex = 0;
8881 return BAD_VALUE;
8882 }
8883 status_t status = NO_ERROR;
8884 while (mCblk->serverIndex < mCblk->clientIndex) {
8885 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008886 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887 int *p = (int *)(mBuffer + mCblk->serverIndex);
8888 int size = *p++;
8889 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008890 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008891 break;
8892 }
8893 effect_param_t *param = (effect_param_t *)p;
8894 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008895 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008896 mCblk->serverIndex += size;
8897 continue;
8898 }
Eric Laurent25f43952010-07-28 05:40:18 -07008899 uint32_t psize = sizeof(effect_param_t) +
8900 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8901 param->vsize;
8902 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8903 psize,
8904 p,
8905 &rsize,
8906 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008907 // stop at first error encountered
8908 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008909 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008910 *(int *)pReplyData = reply;
8911 break;
8912 } else if (reply != NO_ERROR) {
8913 *(int *)pReplyData = reply;
8914 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008915 }
8916 mCblk->serverIndex += size;
8917 }
8918 mCblk->serverIndex = 0;
8919 mCblk->clientIndex = 0;
8920 return status;
8921 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008922 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008923 return enable();
8924 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008925 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926 return disable();
8927 }
8928
8929 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8930}
8931
Eric Laurent59255e42011-07-27 19:49:51 -07008932void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008933{
Steve Block3856b092011-10-20 11:56:00 +01008934 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935
8936 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008937 mEnabled = enabled;
8938
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 if (signal && mEffectClient != 0) {
8940 mEffectClient->controlStatusChanged(hasControl);
8941 }
8942}
8943
Eric Laurent25f43952010-07-28 05:40:18 -07008944void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8945 uint32_t cmdSize,
8946 void *pCmdData,
8947 uint32_t replySize,
8948 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949{
8950 if (mEffectClient != 0) {
8951 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8952 }
8953}
8954
8955
8956
8957void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8958{
8959 if (mEffectClient != 0) {
8960 mEffectClient->enableStatusChanged(enabled);
8961 }
8962}
8963
8964status_t AudioFlinger::EffectHandle::onTransact(
8965 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8966{
8967 return BnEffect::onTransact(code, data, reply, flags);
8968}
8969
8970
8971void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8972{
Glenn Kastena0d68332012-01-27 16:47:15 -08008973 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974
8975 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008976 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 mPriority,
8978 mHasControl,
8979 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008980 mCblk ? mCblk->clientIndex : 0,
8981 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982 );
8983
8984 if (locked) {
8985 mCblk->lock.unlock();
8986 }
8987}
8988
8989#undef LOG_TAG
8990#define LOG_TAG "AudioFlinger::EffectChain"
8991
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008992AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008994 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008995 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8996 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997{
Dima Zavinfce7a472011-04-19 22:30:36 -07008998 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008999 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009000 return;
9001 }
9002 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9003 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009004}
9005
9006AudioFlinger::EffectChain::~EffectChain()
9007{
9008 if (mOwnInBuffer) {
9009 delete mInBuffer;
9010 }
9011
9012}
9013
Eric Laurent59255e42011-07-27 19:49:51 -07009014// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009015sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017 size_t size = mEffects.size();
9018
9019 for (size_t i = 0; i < size; i++) {
9020 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009021 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009022 }
9023 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009024 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025}
9026
Eric Laurent59255e42011-07-27 19:49:51 -07009027// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009028sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 size_t size = mEffects.size();
9031
9032 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009033 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9034 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009035 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009036 }
9037 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009038 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009039}
9040
Eric Laurent59255e42011-07-27 19:49:51 -07009041// getEffectFromType_l() must be called with ThreadBase::mLock held
9042sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9043 const effect_uuid_t *type)
9044{
Eric Laurent59255e42011-07-27 19:49:51 -07009045 size_t size = mEffects.size();
9046
9047 for (size_t i = 0; i < size; i++) {
9048 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009049 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009050 }
9051 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009052 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009053}
9054
Eric Laurent91b14c42012-05-30 12:30:29 -07009055void AudioFlinger::EffectChain::clearInputBuffer()
9056{
9057 Mutex::Autolock _l(mLock);
9058 sp<ThreadBase> thread = mThread.promote();
9059 if (thread == 0) {
9060 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9061 return;
9062 }
9063 clearInputBuffer_l(thread);
9064}
9065
9066// Must be called with EffectChain::mLock locked
9067void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9068{
9069 size_t numSamples = thread->frameCount() * thread->channelCount();
9070 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9071
9072}
9073
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074// Must be called with EffectChain::mLock locked
9075void AudioFlinger::EffectChain::process_l()
9076{
Eric Laurentdac69112010-09-28 14:09:57 -07009077 sp<ThreadBase> thread = mThread.promote();
9078 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009079 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009080 return;
9081 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009082 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9083 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009084 // always process effects unless no more tracks are on the session and the effect tail
9085 // has been rendered
9086 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009087 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009088 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009089
Eric Laurent544fe9b2011-11-11 15:42:52 -08009090 if (!tracksOnSession && mTailBufferCount == 0) {
9091 doProcess = false;
9092 }
9093
9094 if (activeTrackCnt() == 0) {
9095 // if no track is active and the effect tail has not been rendered,
9096 // the input buffer must be cleared here as the mixer process will not do it
9097 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009098 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009099 if (mTailBufferCount > 0) {
9100 mTailBufferCount--;
9101 }
9102 }
9103 }
Eric Laurentdac69112010-09-28 14:09:57 -07009104 }
9105
Mathias Agopian65ab4712010-07-14 17:59:35 -07009106 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009107 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009108 for (size_t i = 0; i < size; i++) {
9109 mEffects[i]->process();
9110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009111 }
9112 for (size_t i = 0; i < size; i++) {
9113 mEffects[i]->updateState();
9114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115}
9116
Eric Laurentcab11242010-07-15 12:50:15 -07009117// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009118status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119{
9120 effect_descriptor_t desc = effect->desc();
9121 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9122
9123 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009124 effect->setChain(this);
9125 sp<ThreadBase> thread = mThread.promote();
9126 if (thread == 0) {
9127 return NO_INIT;
9128 }
9129 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009130
9131 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9132 // Auxiliary effects are inserted at the beginning of mEffects vector as
9133 // they are processed first and accumulated in chain input buffer
9134 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009135
Mathias Agopian65ab4712010-07-14 17:59:35 -07009136 // the input buffer for auxiliary effect contains mono samples in
9137 // 32 bit format. This is to avoid saturation in AudoMixer
9138 // accumulation stage. Saturation is done in EffectModule::process() before
9139 // calling the process in effect engine
9140 size_t numSamples = thread->frameCount();
9141 int32_t *buffer = new int32_t[numSamples];
9142 memset(buffer, 0, numSamples * sizeof(int32_t));
9143 effect->setInBuffer((int16_t *)buffer);
9144 // auxiliary effects output samples to chain input buffer for further processing
9145 // by insert effects
9146 effect->setOutBuffer(mInBuffer);
9147 } else {
9148 // Insert effects are inserted at the end of mEffects vector as they are processed
9149 // after track and auxiliary effects.
9150 // Insert effect order as a function of indicated preference:
9151 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9152 // another effect is present
9153 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9154 // last effect claiming first position
9155 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9156 // first effect claiming last position
9157 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9158 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9159 // already present
9160
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009161 size_t size = mEffects.size();
9162 size_t idx_insert = size;
9163 ssize_t idx_insert_first = -1;
9164 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009166 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009167 effect_descriptor_t d = mEffects[i]->desc();
9168 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9169 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9170 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9171 // check invalid effect chaining combinations
9172 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9173 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009174 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175 return INVALID_OPERATION;
9176 }
9177 // remember position of first insert effect and by default
9178 // select this as insert position for new effect
9179 if (idx_insert == size) {
9180 idx_insert = i;
9181 }
9182 // remember position of last insert effect claiming
9183 // first position
9184 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9185 idx_insert_first = i;
9186 }
9187 // remember position of first insert effect claiming
9188 // last position
9189 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9190 idx_insert_last == -1) {
9191 idx_insert_last = i;
9192 }
9193 }
9194 }
9195
9196 // modify idx_insert from first position if needed
9197 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9198 if (idx_insert_last != -1) {
9199 idx_insert = idx_insert_last;
9200 } else {
9201 idx_insert = size;
9202 }
9203 } else {
9204 if (idx_insert_first != -1) {
9205 idx_insert = idx_insert_first + 1;
9206 }
9207 }
9208
9209 // always read samples from chain input buffer
9210 effect->setInBuffer(mInBuffer);
9211
9212 // if last effect in the chain, output samples to chain
9213 // output buffer, otherwise to chain input buffer
9214 if (idx_insert == size) {
9215 if (idx_insert != 0) {
9216 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9217 mEffects[idx_insert-1]->configure();
9218 }
9219 effect->setOutBuffer(mOutBuffer);
9220 } else {
9221 effect->setOutBuffer(mInBuffer);
9222 }
9223 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224
Steve Block3856b092011-10-20 11:56:00 +01009225 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226 }
9227 effect->configure();
9228 return NO_ERROR;
9229}
9230
Eric Laurentcab11242010-07-15 12:50:15 -07009231// removeEffect_l() must be called with PlaybackThread::mLock held
9232size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009233{
9234 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009235 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9237
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009238 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009240 // calling stop here will remove pre-processing effect from the audio HAL.
9241 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9242 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009243 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9244 mEffects[i]->state() == EffectModule::STOPPING) {
9245 mEffects[i]->stop();
9246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009247 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9248 delete[] effect->inBuffer();
9249 } else {
9250 if (i == size - 1 && i != 0) {
9251 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9252 mEffects[i - 1]->configure();
9253 }
9254 }
9255 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009256 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009257 break;
9258 }
9259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009260
9261 return mEffects.size();
9262}
9263
Eric Laurentcab11242010-07-15 12:50:15 -07009264// setDevice_l() must be called with PlaybackThread::mLock held
9265void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009266{
9267 size_t size = mEffects.size();
9268 for (size_t i = 0; i < size; i++) {
9269 mEffects[i]->setDevice(device);
9270 }
9271}
9272
Eric Laurentcab11242010-07-15 12:50:15 -07009273// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009274void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009275{
9276 size_t size = mEffects.size();
9277 for (size_t i = 0; i < size; i++) {
9278 mEffects[i]->setMode(mode);
9279 }
9280}
9281
Eric Laurentcab11242010-07-15 12:50:15 -07009282// setVolume_l() must be called with PlaybackThread::mLock held
9283bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009284{
9285 uint32_t newLeft = *left;
9286 uint32_t newRight = *right;
9287 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009288 int ctrlIdx = -1;
9289 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009290
Eric Laurentcab11242010-07-15 12:50:15 -07009291 // first update volume controller
9292 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009293 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009294 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9295 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009296 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009297 break;
9298 }
9299 }
9300
9301 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009302 if (hasControl) {
9303 *left = mNewLeftVolume;
9304 *right = mNewRightVolume;
9305 }
9306 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009307 }
9308
9309 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009310 mLeftVolume = newLeft;
9311 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009312
9313 // second get volume update from volume controller
9314 if (ctrlIdx >= 0) {
9315 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009316 mNewLeftVolume = newLeft;
9317 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009318 }
9319 // then indicate volume to all other effects in chain.
9320 // Pass altered volume to effects before volume controller
9321 // and requested volume to effects after controller
9322 uint32_t lVol = newLeft;
9323 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009324
Mathias Agopian65ab4712010-07-14 17:59:35 -07009325 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009326 if ((int)i == ctrlIdx) continue;
9327 // this also works for ctrlIdx == -1 when there is no volume controller
9328 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009329 lVol = *left;
9330 rVol = *right;
9331 }
9332 mEffects[i]->setVolume(&lVol, &rVol, false);
9333 }
9334 *left = newLeft;
9335 *right = newRight;
9336
9337 return hasControl;
9338}
9339
Mathias Agopian65ab4712010-07-14 17:59:35 -07009340status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9341{
9342 const size_t SIZE = 256;
9343 char buffer[SIZE];
9344 String8 result;
9345
9346 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9347 result.append(buffer);
9348
9349 bool locked = tryLock(mLock);
9350 // failed to lock - AudioFlinger is probably deadlocked
9351 if (!locked) {
9352 result.append("\tCould not lock mutex:\n");
9353 }
9354
Eric Laurentcab11242010-07-15 12:50:15 -07009355 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9356 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009357 mEffects.size(),
9358 (uint32_t)mInBuffer,
9359 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009360 mActiveTrackCnt);
9361 result.append(buffer);
9362 write(fd, result.string(), result.size());
9363
9364 for (size_t i = 0; i < mEffects.size(); ++i) {
9365 sp<EffectModule> effect = mEffects[i];
9366 if (effect != 0) {
9367 effect->dump(fd, args);
9368 }
9369 }
9370
9371 if (locked) {
9372 mLock.unlock();
9373 }
9374
9375 return NO_ERROR;
9376}
9377
Eric Laurent59255e42011-07-27 19:49:51 -07009378// must be called with ThreadBase::mLock held
9379void AudioFlinger::EffectChain::setEffectSuspended_l(
9380 const effect_uuid_t *type, bool suspend)
9381{
9382 sp<SuspendedEffectDesc> desc;
9383 // use effect type UUID timelow as key as there is no real risk of identical
9384 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009385 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009386 if (suspend) {
9387 if (index >= 0) {
9388 desc = mSuspendedEffects.valueAt(index);
9389 } else {
9390 desc = new SuspendedEffectDesc();
9391 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9392 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009393 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009394 }
9395 if (desc->mRefCount++ == 0) {
9396 sp<EffectModule> effect = getEffectIfEnabled(type);
9397 if (effect != 0) {
9398 desc->mEffect = effect;
9399 effect->setSuspended(true);
9400 effect->setEnabled(false);
9401 }
9402 }
9403 } else {
9404 if (index < 0) {
9405 return;
9406 }
9407 desc = mSuspendedEffects.valueAt(index);
9408 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009409 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009410 desc->mRefCount = 1;
9411 }
9412 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009413 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009414 if (desc->mEffect != 0) {
9415 sp<EffectModule> effect = desc->mEffect.promote();
9416 if (effect != 0) {
9417 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009418 effect->lock();
9419 EffectHandle *handle = effect->controlHandle_l();
9420 if (handle != NULL && !handle->destroyed_l()) {
9421 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009422 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009423 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009424 }
9425 desc->mEffect.clear();
9426 }
9427 mSuspendedEffects.removeItemsAt(index);
9428 }
9429 }
9430}
9431
9432// must be called with ThreadBase::mLock held
9433void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9434{
9435 sp<SuspendedEffectDesc> desc;
9436
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009437 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009438 if (suspend) {
9439 if (index >= 0) {
9440 desc = mSuspendedEffects.valueAt(index);
9441 } else {
9442 desc = new SuspendedEffectDesc();
9443 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009444 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009445 }
9446 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009447 Vector< sp<EffectModule> > effects;
9448 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009449 for (size_t i = 0; i < effects.size(); i++) {
9450 setEffectSuspended_l(&effects[i]->desc().type, true);
9451 }
9452 }
9453 } else {
9454 if (index < 0) {
9455 return;
9456 }
9457 desc = mSuspendedEffects.valueAt(index);
9458 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009459 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009460 desc->mRefCount = 1;
9461 }
9462 if (--desc->mRefCount == 0) {
9463 Vector<const effect_uuid_t *> types;
9464 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9465 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9466 continue;
9467 }
9468 types.add(&mSuspendedEffects.valueAt(i)->mType);
9469 }
9470 for (size_t i = 0; i < types.size(); i++) {
9471 setEffectSuspended_l(types[i], false);
9472 }
Steve Block3856b092011-10-20 11:56:00 +01009473 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009474 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9475 }
9476 }
9477}
9478
Eric Laurent6bffdb82011-09-23 08:40:41 -07009479
9480// The volume effect is used for automated tests only
9481#ifndef OPENSL_ES_H_
9482static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9483 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9484const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9485#endif //OPENSL_ES_H_
9486
Eric Laurentdb7c0792011-08-10 10:37:50 -07009487bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9488{
9489 // auxiliary effects and visualizer are never suspended on output mix
9490 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9491 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009492 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9493 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009494 return false;
9495 }
9496 return true;
9497}
9498
Glenn Kastend0539712012-01-30 12:56:03 -08009499void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009500{
Glenn Kastend0539712012-01-30 12:56:03 -08009501 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009502 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009503 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9504 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009505 }
Eric Laurent59255e42011-07-27 19:49:51 -07009506 }
Eric Laurent59255e42011-07-27 19:49:51 -07009507}
9508
9509sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9510 const effect_uuid_t *type)
9511{
Glenn Kasten090f0192012-01-30 13:00:02 -08009512 sp<EffectModule> effect = getEffectFromType_l(type);
9513 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009514}
9515
9516void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9517 bool enabled)
9518{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009519 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009520 if (enabled) {
9521 if (index < 0) {
9522 // if the effect is not suspend check if all effects are suspended
9523 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9524 if (index < 0) {
9525 return;
9526 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009527 if (!isEffectEligibleForSuspend(effect->desc())) {
9528 return;
9529 }
Eric Laurent59255e42011-07-27 19:49:51 -07009530 setEffectSuspended_l(&effect->desc().type, enabled);
9531 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009532 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009533 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009534 return;
9535 }
Eric Laurent59255e42011-07-27 19:49:51 -07009536 }
Steve Block3856b092011-10-20 11:56:00 +01009537 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009538 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009539 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9540 // if effect is requested to suspended but was not yet enabled, supend it now.
9541 if (desc->mEffect == 0) {
9542 desc->mEffect = effect;
9543 effect->setEnabled(false);
9544 effect->setSuspended(true);
9545 }
9546 } else {
9547 if (index < 0) {
9548 return;
9549 }
Steve Block3856b092011-10-20 11:56:00 +01009550 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009551 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009552 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9553 desc->mEffect.clear();
9554 effect->setSuspended(false);
9555 }
9556}
9557
Mathias Agopian65ab4712010-07-14 17:59:35 -07009558#undef LOG_TAG
9559#define LOG_TAG "AudioFlinger"
9560
9561// ----------------------------------------------------------------------------
9562
9563status_t AudioFlinger::onTransact(
9564 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9565{
9566 return BnAudioFlinger::onTransact(code, data, reply, flags);
9567}
9568
Mathias Agopian65ab4712010-07-14 17:59:35 -07009569}; // namespace android