blob: ffb00e78ab74856b3921384cff170f7fe6089cac [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
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168// ----------------------------------------------------------------------------
169
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700170#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800173 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174 if (service == NULL) {
175 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800176 return;
177 }
178
179 service->addBatteryData(params);
180}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700181#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800182
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700184{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 int rc;
187
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700188 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700193 }
194 rc = audio_hw_device_open(mod, dev);
195 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700199 }
200 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202 rc = BAD_VALUE;
203 goto out;
204 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 return 0;
206
207out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700208 *dev = NULL;
209 return rc;
210}
211
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700217 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMasterVolume(1.0f),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700219 mMasterVolumeSW(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800220 mMasterVolumeSupportLvl(MVS_NONE),
221 mMasterMute(false),
222 mNextUniqueId(1),
223 mMode(AUDIO_MODE_INVALID),
224 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700226}
227
228void AudioFlinger::onFirstRef()
229{
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700231
Eric Laurent93575202011-01-18 18:39:02 -0800232 Mutex::Autolock _l(mLock);
233
Dima Zavin799a70e2011-04-18 16:57:27 -0700234 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800235 char val_str[PROPERTY_VALUE_MAX] = { 0 };
236 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
237 uint32_t int_val;
238 if (1 == sscanf(val_str, "%u", &int_val)) {
239 mStandbyTimeInNsecs = milliseconds(int_val);
240 ALOGI("Using %u mSec as standby time.", int_val);
241 } else {
242 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
243 ALOGI("Using default %u mSec as standby time.",
244 (uint32_t)(mStandbyTimeInNsecs / 1000000));
245 }
246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247
Eric Laurenta4c5a552012-03-29 10:12:40 -0700248 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
251AudioFlinger::~AudioFlinger()
252{
253 while (!mRecordThreads.isEmpty()) {
254 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700255 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256 }
257 while (!mPlaybackThreads.isEmpty()) {
258 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700259 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700261
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800262 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700264 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266 }
267}
268
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269static const char * const audio_interfaces[] = {
270 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271 AUDIO_HARDWARE_MODULE_ID_A2DP,
272 AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700277{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 } else {
286 // check a match for the requested module handle
287 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288 if (audioHwdevice != NULL) {
289 return audioHwdevice->hwDevice();
290 }
291 }
292 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700294 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 if ((dev->get_supported_devices(dev) & devices) == devices)
296 return dev;
297 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298
Dima Zavin799a70e2011-04-18 16:57:27 -0700299 return NULL;
300}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700302void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append("Clients:\n");
309 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800310 sp<Client> client = mClients.valueAt(i).promote();
311 if (client != 0) {
312 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314 }
315 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316
317 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800321 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 result.append(buffer);
323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325}
326
327
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700328void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329{
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());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341}
342
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700343void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344{
345 const size_t SIZE = 256;
346 char buffer[SIZE];
347 String8 result;
348 snprintf(buffer, SIZE, "Permission Denial: "
349 "can't dump AudioFlinger from pid=%d, uid=%d\n",
350 IPCThreadState::self()->getCallingPid(),
351 IPCThreadState::self()->getCallingUid());
352 result.append(buffer);
353 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354}
355
356static bool tryLock(Mutex& mutex)
357{
358 bool locked = false;
359 for (int i = 0; i < kDumpLockRetries; ++i) {
360 if (mutex.tryLock() == NO_ERROR) {
361 locked = true;
362 break;
363 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800364 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365 }
366 return locked;
367}
368
369status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
370{
Glenn Kasten44deb052012-02-05 18:09:08 -0800371 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 dumpPermissionDenial(fd, args);
373 } else {
374 // get state of hardware lock
375 bool hardwareLocked = tryLock(mHardwareLock);
376 if (!hardwareLocked) {
377 String8 result(kHardwareLockedString);
378 write(fd, result.string(), result.size());
379 } else {
380 mHardwareLock.unlock();
381 }
382
383 bool locked = tryLock(mLock);
384
385 // failed to lock - AudioFlinger is probably deadlocked
386 if (!locked) {
387 String8 result(kDeadlockedString);
388 write(fd, result.string(), result.size());
389 }
390
391 dumpClients(fd, args);
392 dumpInternals(fd, args);
393
394 // dump playback threads
395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
396 mPlaybackThreads.valueAt(i)->dump(fd, args);
397 }
398
399 // dump record threads
400 for (size_t i = 0; i < mRecordThreads.size(); i++) {
401 mRecordThreads.valueAt(i)->dump(fd, args);
402 }
403
Dima Zavin799a70e2011-04-18 16:57:27 -0700404 // dump all hardware devs
405 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700406 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 }
409 if (locked) mLock.unlock();
410 }
411 return NO_ERROR;
412}
413
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800414sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
415{
416 // If pid is already in the mClients wp<> map, then use that entry
417 // (for which promote() is always != 0), otherwise create a new entry and Client.
418 sp<Client> client = mClients.valueFor(pid).promote();
419 if (client == 0) {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
424 return client;
425}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426
427// IAudioFlinger interface
428
429
430sp<IAudioTrack> AudioFlinger::createTrack(
431 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800432 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800434 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700435 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800437 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800439 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800440 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int *sessionId,
442 status_t *status)
443{
444 sp<PlaybackThread::Track> track;
445 sp<TrackHandle> trackHandle;
446 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 status_t lStatus;
448 int lSessionId;
449
Glenn Kasten263709e2012-01-06 08:40:01 -0800450 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
451 // but if someone uses binder directly they could bypass that and cause us to crash
452 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000453 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 lStatus = BAD_VALUE;
455 goto Exit;
456 }
457
458 {
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700461 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800468 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469
Steve Block3856b092011-10-20 11:56:00 +0100470 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700471 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700472 // check if an effect chain with the same session ID is present on another
473 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700474 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700475 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
476 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 if (sessions & PlaybackThread::EFFECT_SESSION) {
479 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700480 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700481 }
Eric Laurentde070132010-07-13 04:45:46 -0700482 }
483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 lSessionId = *sessionId;
485 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700486 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700487 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 if (sessionId != NULL) {
489 *sessionId = lSessionId;
490 }
491 }
Steve Block3856b092011-10-20 11:56:00 +0100492 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493
494 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800495 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700496
497 // move effect chain to this output thread if an effect on same session was waiting
498 // for a track to be created
499 if (lStatus == NO_ERROR && effectThread != NULL) {
500 Mutex::Autolock _dl(thread->mLock);
501 Mutex::Autolock _sl(effectThread->mLock);
502 moveEffectChain_l(lSessionId, effectThread, thread, true);
503 }
Eric Laurenta011e352012-03-29 15:51:43 -0700504
505 // Look for sync events awaiting for a session to be used.
506 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
507 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
508 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700509 if (lStatus == NO_ERROR) {
510 track->setSyncEvent(mPendingSyncEvents[i]);
511 } else {
512 mPendingSyncEvents[i]->cancel();
513 }
Eric Laurenta011e352012-03-29 15:51:43 -0700514 mPendingSyncEvents.removeAt(i);
515 i--;
516 }
517 }
518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 }
520 if (lStatus == NO_ERROR) {
521 trackHandle = new TrackHandle(track);
522 } else {
523 // remove local strong reference to Client before deleting the Track so that the Client
524 // destructor is called by the TrackBase destructor with mLock held
525 client.clear();
526 track.clear();
527 }
528
529Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700530 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 *status = lStatus;
532 }
533 return trackHandle;
534}
535
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800536uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537{
538 Mutex::Autolock _l(mLock);
539 PlaybackThread *thread = checkPlaybackThread_l(output);
540 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000541 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 return 0;
543 }
544 return thread->sampleRate();
545}
546
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548{
549 Mutex::Autolock _l(mLock);
550 PlaybackThread *thread = checkPlaybackThread_l(output);
551 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000552 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 return 0;
554 }
555 return thread->channelCount();
556}
557
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800558audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559{
560 Mutex::Autolock _l(mLock);
561 PlaybackThread *thread = checkPlaybackThread_l(output);
562 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000563 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800564 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 return thread->format();
567}
568
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570{
571 Mutex::Autolock _l(mLock);
572 PlaybackThread *thread = checkPlaybackThread_l(output);
573 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 return 0;
576 }
Glenn Kasten58912562012-04-03 10:45:00 -0700577 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
578 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return thread->frameCount();
580}
581
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800582uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583{
584 Mutex::Autolock _l(mLock);
585 PlaybackThread *thread = checkPlaybackThread_l(output);
586 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000587 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return 0;
589 }
590 return thread->latency();
591}
592
593status_t AudioFlinger::setMasterVolume(float value)
594{
Eric Laurenta1884f92011-08-23 08:25:03 -0700595 status_t ret = initCheck();
596 if (ret != NO_ERROR) {
597 return ret;
598 }
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 // check calling permissions
601 if (!settingsAllowed()) {
602 return PERMISSION_DENIED;
603 }
604
John Grossman4ff14ba2012-02-08 16:37:41 -0800605 float swmv = value;
606
Eric Laurenta4c5a552012-03-29 10:12:40 -0700607 Mutex::Autolock _l(mLock);
608
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 if (MVS_NONE != mMasterVolumeSupportLvl) {
611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
612 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700613 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800614
615 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
616 if (NULL != dev->set_master_volume) {
617 dev->set_master_volume(dev, value);
618 }
619 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800620 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800621
622 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
John Grossman4ff14ba2012-02-08 16:37:41 -0800625 mMasterVolume = value;
626 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800627 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700628 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
630 return NO_ERROR;
631}
632
Glenn Kastenf78aee72012-01-04 11:00:47 -0800633status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634{
Eric Laurenta1884f92011-08-23 08:25:03 -0700635 status_t ret = initCheck();
636 if (ret != NO_ERROR) {
637 return ret;
638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
640 // check calling permissions
641 if (!settingsAllowed()) {
642 return PERMISSION_DENIED;
643 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800644 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000645 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 return BAD_VALUE;
647 }
648
649 { // scope for the lock
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700652 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mHardwareStatus = AUDIO_HW_IDLE;
654 }
655
656 if (NO_ERROR == ret) {
657 Mutex::Autolock _l(mLock);
658 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800659 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700660 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 }
662
663 return ret;
664}
665
666status_t AudioFlinger::setMicMute(bool state)
667{
Eric Laurenta1884f92011-08-23 08:25:03 -0700668 status_t ret = initCheck();
669 if (ret != NO_ERROR) {
670 return ret;
671 }
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 // check calling permissions
674 if (!settingsAllowed()) {
675 return PERMISSION_DENIED;
676 }
677
678 AutoMutex lock(mHardwareLock);
679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700680 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700695 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_IDLE;
697 return state;
698}
699
700status_t AudioFlinger::setMasterMute(bool muted)
701{
702 // check calling permissions
703 if (!settingsAllowed()) {
704 return PERMISSION_DENIED;
705 }
706
Eric Laurent93575202011-01-18 18:39:02 -0800707 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800708 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800710 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700711 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712
713 return NO_ERROR;
714}
715
716float AudioFlinger::masterVolume() const
717{
Glenn Kasten98067102011-12-13 11:47:54 -0800718 Mutex::Autolock _l(mLock);
719 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720}
721
John Grossman4ff14ba2012-02-08 16:37:41 -0800722float AudioFlinger::masterVolumeSW() const
723{
724 Mutex::Autolock _l(mLock);
725 return masterVolumeSW_l();
726}
727
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728bool AudioFlinger::masterMute() const
729{
Glenn Kasten98067102011-12-13 11:47:54 -0800730 Mutex::Autolock _l(mLock);
731 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732}
733
John Grossman4ff14ba2012-02-08 16:37:41 -0800734float AudioFlinger::masterVolume_l() const
735{
736 if (MVS_FULL == mMasterVolumeSupportLvl) {
737 float ret_val;
738 AutoMutex lock(mHardwareLock);
739
740 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800741 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
742 (NULL != mPrimaryHardwareDev->get_master_volume),
743 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800744
745 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
746 mHardwareStatus = AUDIO_HW_IDLE;
747 return ret_val;
748 }
749
750 return mMasterVolume;
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
754 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755{
756 // check calling permissions
757 if (!settingsAllowed()) {
758 return PERMISSION_DENIED;
759 }
760
Glenn Kasten263709e2012-01-06 08:40:01 -0800761 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000762 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 return BAD_VALUE;
764 }
765
766 AutoMutex lock(mLock);
767 PlaybackThread *thread = NULL;
768 if (output) {
769 thread = checkPlaybackThread_l(output);
770 if (thread == NULL) {
771 return BAD_VALUE;
772 }
773 }
774
775 mStreamTypes[stream].volume = value;
776
777 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700779 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 }
781 } else {
782 thread->setStreamVolume(stream, value);
783 }
784
785 return NO_ERROR;
786}
787
Glenn Kastenfff6d712012-01-12 16:38:12 -0800788status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 // check calling permissions
791 if (!settingsAllowed()) {
792 return PERMISSION_DENIED;
793 }
794
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700796 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000797 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 return BAD_VALUE;
799 }
800
Eric Laurent93575202011-01-18 18:39:02 -0800801 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 mStreamTypes[stream].mute = muted;
803 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700804 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805
806 return NO_ERROR;
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 return 0.0f;
813 }
814
815 AutoMutex lock(mLock);
816 float volume;
817 if (output) {
818 PlaybackThread *thread = checkPlaybackThread_l(output);
819 if (thread == NULL) {
820 return 0.0f;
821 }
822 volume = thread->streamVolume(stream);
823 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800824 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 }
826
827 return volume;
828}
829
Glenn Kastenfff6d712012-01-12 16:38:12 -0800830bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
Glenn Kasten263709e2012-01-06 08:40:01 -0800832 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return true;
834 }
835
Glenn Kasten6637baa2012-01-09 09:40:36 -0800836 AutoMutex lock(mLock);
837 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838}
839
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800840status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800842 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
844 // check calling permissions
845 if (!settingsAllowed()) {
846 return PERMISSION_DENIED;
847 }
848
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 // ioHandle == 0 means the parameters are global to the audio hardware interface
850 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700851 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700852 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800853 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 AutoMutex lock(mHardwareLock);
855 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
856 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
857 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
858 status_t result = dev->set_parameters(dev, keyValuePairs.string());
859 final_result = result ?: final_result;
860 }
861 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
864 AudioParameter param = AudioParameter(keyValuePairs);
865 String8 value;
866 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700867 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
868 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 for (size_t i = 0; i < mRecordThreads.size(); i++) {
870 sp<RecordThread> thread = mRecordThreads.valueAt(i);
871 RecordThread::RecordTrack *track = thread->track();
872 if (track != NULL) {
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700873 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
Eric Laurentbee53372011-08-29 12:42:48 -0700874 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700875 thread->setEffectSuspended(FX_IID_AEC,
876 suspend,
877 track->sessionId());
878 thread->setEffectSuspended(FX_IID_NS,
879 suspend,
880 track->sessionId());
881 }
882 }
Eric Laurentbee53372011-08-29 12:42:48 -0700883 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700884 }
885 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700886 String8 screenState;
887 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
888 bool isOff = screenState == "off";
889 if (isOff != (gScreenState & 1)) {
890 gScreenState = ((gScreenState & ~1) + 2) | isOff;
891 }
892 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700893 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 }
895
896 // hold a strong ref on thread in case closeOutput() or closeInput() is called
897 // and the thread is exited once the lock is released
898 sp<ThreadBase> thread;
899 {
900 Mutex::Autolock _l(mLock);
901 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700902 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800904 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700905 // indicate output device change to all input threads for pre processing
906 AudioParameter param = AudioParameter(keyValuePairs);
907 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700908 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
909 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700910 for (size_t i = 0; i < mRecordThreads.size(); i++) {
911 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
912 }
913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 }
915 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800916 if (thread != 0) {
917 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
919 return BAD_VALUE;
920}
921
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800922String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800924// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
926
Eric Laurenta4c5a552012-03-29 10:12:40 -0700927 Mutex::Autolock _l(mLock);
928
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700930 String8 out_s8;
931
Dima Zavin799a70e2011-04-18 16:57:27 -0700932 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800933 char *s;
934 {
935 AutoMutex lock(mHardwareLock);
936 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700937 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800938 s = dev->get_parameters(dev, keys.string());
939 mHardwareStatus = AUDIO_HW_IDLE;
940 }
John Grossmanef7740b2012-02-09 11:28:36 -0800941 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700942 free(s);
943 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700944 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 }
946
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
948 if (playbackThread != NULL) {
949 return playbackThread->getParameters(keys);
950 }
951 RecordThread *recordThread = checkRecordThread_l(ioHandle);
952 if (recordThread != NULL) {
953 return recordThread->getParameters(keys);
954 }
955 return String8("");
956}
957
Glenn Kastendd8104c2012-07-02 12:42:44 -0700958size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
959 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960{
Eric Laurenta1884f92011-08-23 08:25:03 -0700961 status_t ret = initCheck();
962 if (ret != NO_ERROR) {
963 return 0;
964 }
965
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800966 AutoMutex lock(mHardwareLock);
967 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700968 struct audio_config config = {
969 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700970 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700971 format: format,
972 };
973 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800974 mHardwareStatus = AUDIO_HW_IDLE;
975 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976}
977
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800978unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 Mutex::Autolock _l(mLock);
981
982 RecordThread *recordThread = checkRecordThread_l(ioHandle);
983 if (recordThread != NULL) {
984 return recordThread->getInputFramesLost();
985 }
986 return 0;
987}
988
989status_t AudioFlinger::setVoiceVolume(float value)
990{
Eric Laurenta1884f92011-08-23 08:25:03 -0700991 status_t ret = initCheck();
992 if (ret != NO_ERROR) {
993 return ret;
994 }
995
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 // check calling permissions
997 if (!settingsAllowed()) {
998 return PERMISSION_DENIED;
999 }
1000
1001 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001002 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 mHardwareStatus = AUDIO_HW_IDLE;
1005
1006 return ret;
1007}
1008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001009status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1010 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011{
1012 status_t status;
1013
1014 Mutex::Autolock _l(mLock);
1015
1016 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1017 if (playbackThread != NULL) {
1018 return playbackThread->getRenderPosition(halFrames, dspFrames);
1019 }
1020
1021 return BAD_VALUE;
1022}
1023
1024void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1025{
1026
1027 Mutex::Autolock _l(mLock);
1028
Glenn Kastenbb001922012-02-03 11:10:26 -08001029 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 if (mNotificationClients.indexOfKey(pid) < 0) {
1031 sp<NotificationClient> notificationClient = new NotificationClient(this,
1032 client,
1033 pid);
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035
1036 mNotificationClients.add(pid, notificationClient);
1037
1038 sp<IBinder> binder = client->asBinder();
1039 binder->linkToDeath(notificationClient);
1040
1041 // the config change is always sent from playback or record threads to avoid deadlock
1042 // with AudioSystem::gLock
1043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1044 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1045 }
1046
1047 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1048 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1049 }
1050 }
1051}
1052
1053void AudioFlinger::removeNotificationClient(pid_t pid)
1054{
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastena3b09252012-01-20 09:19:01 -08001057 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001060 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001061 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001064 ALOGV(" pid %d @ %d", ref->mPid, i);
1065 if (ref->mPid == pid) {
1066 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 mAudioSessionRefs.removeAt(i);
1068 delete ref;
1069 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 } else {
1072 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 }
1074 }
1075 if (removed) {
1076 purgeStaleEffects_l();
1077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078}
1079
1080// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001081void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 size_t size = mNotificationClients.size();
1084 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1086 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088}
1089
1090// removeClient_l() must be called with AudioFlinger::mLock held
1091void AudioFlinger::removeClient_l(pid_t pid)
1092{
Steve Block3856b092011-10-20 11:56:00 +01001093 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mClients.removeItem(pid);
1095}
1096
Eric Laurent717e1282012-06-29 16:36:52 -07001097// getEffectThread_l() must be called with AudioFlinger::mLock held
1098sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1099{
1100 sp<PlaybackThread> thread;
1101
1102 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1103 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1104 ALOG_ASSERT(thread == 0);
1105 thread = mPlaybackThreads.valueAt(i);
1106 }
1107 }
1108
1109 return thread;
1110}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111
1112// ----------------------------------------------------------------------------
1113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001114AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001115 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001117 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001118 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001119 // mChannelMask
1120 mChannelCount(0),
1121 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1122 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001123 mStandby(false), mDevice(device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001124 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125{
1126}
1127
1128AudioFlinger::ThreadBase::~ThreadBase()
1129{
1130 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001131 // do not lock the mutex in destructor
1132 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001133 if (mPowerManager != 0) {
1134 sp<IBinder> binder = mPowerManager->asBinder();
1135 binder->unlinkToDeath(mDeathRecipient);
1136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137}
1138
1139void AudioFlinger::ThreadBase::exit()
1140{
Steve Block3856b092011-10-20 11:56:00 +01001141 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001143 // This lock prevents the following race in thread (uniprocessor for illustration):
1144 // if (!exitPending()) {
1145 // // context switch from here to exit()
1146 // // exit() calls requestExit(), what exitPending() observes
1147 // // exit() calls signal(), which is dropped since no waiters
1148 // // context switch back from exit() to here
1149 // mWaitWorkCV.wait(...);
1150 // // now thread is hung
1151 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001152 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 requestExit();
1154 mWaitWorkCV.signal();
1155 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001156 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1157 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 requestExitAndWait();
1159}
1160
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1162{
1163 status_t status;
1164
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 Mutex::Autolock _l(mLock);
1167
1168 mNewParameters.add(keyValuePairs);
1169 mWaitWorkCV.signal();
1170 // wait condition with timeout in case the thread loop has exited
1171 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001172 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 status = mParamStatus;
1174 mWaitWorkCV.signal();
1175 } else {
1176 status = TIMED_OUT;
1177 }
1178 return status;
1179}
1180
1181void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1182{
1183 Mutex::Autolock _l(mLock);
1184 sendConfigEvent_l(event, param);
1185}
1186
1187// sendConfigEvent_l() must be called with ThreadBase::mLock held
1188void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1189{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001190 ConfigEvent configEvent;
1191 configEvent.mEvent = event;
1192 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 mWaitWorkCV.signal();
1196}
1197
1198void AudioFlinger::ThreadBase::processConfigEvents()
1199{
1200 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001201 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001203 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 mConfigEvents.removeAt(0);
1205 // release mLock before locking AudioFlinger mLock: lock order is always
1206 // AudioFlinger then ThreadBase to avoid cross deadlock
1207 mLock.unlock();
1208 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001209 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 mLock.lock();
1212 }
1213 mLock.unlock();
1214}
1215
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001216void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217{
1218 const size_t SIZE = 256;
1219 char buffer[SIZE];
1220 String8 result;
1221
1222 bool locked = tryLock(mLock);
1223 if (!locked) {
1224 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1225 write(fd, buffer, strlen(buffer));
1226 }
1227
Eric Laurent612bbb52012-03-14 15:03:26 -07001228 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1229 result.append(buffer);
1230 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1231 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1233 result.append(buffer);
1234 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1235 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001236 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1237 result.append(buffer);
1238 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 result.append(buffer);
1240 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1241 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001242 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1243 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1245 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001246 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 result.append(buffer);
1248
1249 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1250 result.append(buffer);
1251 result.append(" Index Command");
1252 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1253 snprintf(buffer, SIZE, "\n %02d ", i);
1254 result.append(buffer);
1255 result.append(mNewParameters[i]);
1256 }
1257
1258 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1259 result.append(buffer);
1260 snprintf(buffer, SIZE, " Index event param\n");
1261 result.append(buffer);
1262 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001263 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 result.append(buffer);
1265 }
1266 result.append("\n");
1267
1268 write(fd, result.string(), result.size());
1269
1270 if (locked) {
1271 mLock.unlock();
1272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273}
1274
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001275void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001276{
1277 const size_t SIZE = 256;
1278 char buffer[SIZE];
1279 String8 result;
1280
1281 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1282 write(fd, buffer, strlen(buffer));
1283
1284 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1285 sp<EffectChain> chain = mEffectChains[i];
1286 if (chain != 0) {
1287 chain->dump(fd, args);
1288 }
1289 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001290}
1291
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292void AudioFlinger::ThreadBase::acquireWakeLock()
1293{
1294 Mutex::Autolock _l(mLock);
1295 acquireWakeLock_l();
1296}
1297
1298void AudioFlinger::ThreadBase::acquireWakeLock_l()
1299{
1300 if (mPowerManager == 0) {
1301 // use checkService() to avoid blocking if power service is not up yet
1302 sp<IBinder> binder =
1303 defaultServiceManager()->checkService(String16("power"));
1304 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001305 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001306 } else {
1307 mPowerManager = interface_cast<IPowerManager>(binder);
1308 binder->linkToDeath(mDeathRecipient);
1309 }
1310 }
1311 if (mPowerManager != 0) {
1312 sp<IBinder> binder = new BBinder();
1313 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1314 binder,
1315 String16(mName));
1316 if (status == NO_ERROR) {
1317 mWakeLockToken = binder;
1318 }
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001320 }
1321}
1322
1323void AudioFlinger::ThreadBase::releaseWakeLock()
1324{
1325 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001326 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001327}
1328
1329void AudioFlinger::ThreadBase::releaseWakeLock_l()
1330{
1331 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001332 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001333 if (mPowerManager != 0) {
1334 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1335 }
1336 mWakeLockToken.clear();
1337 }
1338}
1339
1340void AudioFlinger::ThreadBase::clearPowerManager()
1341{
1342 Mutex::Autolock _l(mLock);
1343 releaseWakeLock_l();
1344 mPowerManager.clear();
1345}
1346
1347void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1348{
1349 sp<ThreadBase> thread = mThread.promote();
1350 if (thread != 0) {
1351 thread->clearPowerManager();
1352 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001353 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001354}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001355
Eric Laurent59255e42011-07-27 19:49:51 -07001356void AudioFlinger::ThreadBase::setEffectSuspended(
1357 const effect_uuid_t *type, bool suspend, int sessionId)
1358{
1359 Mutex::Autolock _l(mLock);
1360 setEffectSuspended_l(type, suspend, sessionId);
1361}
1362
1363void AudioFlinger::ThreadBase::setEffectSuspended_l(
1364 const effect_uuid_t *type, bool suspend, int sessionId)
1365{
Glenn Kasten090f0192012-01-30 13:00:02 -08001366 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001367 if (chain != 0) {
1368 if (type != NULL) {
1369 chain->setEffectSuspended_l(type, suspend);
1370 } else {
1371 chain->setEffectSuspendedAll_l(suspend);
1372 }
1373 }
1374
1375 updateSuspendedSessions_l(type, suspend, sessionId);
1376}
1377
1378void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1379{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001380 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001381 if (index < 0) {
1382 return;
1383 }
1384
1385 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1386 mSuspendedSessions.editValueAt(index);
1387
1388 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001389 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001390 for (int j = 0; j < desc->mRefCount; j++) {
1391 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1392 chain->setEffectSuspendedAll_l(true);
1393 } else {
Steve Block3856b092011-10-20 11:56:00 +01001394 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001395 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001396 chain->setEffectSuspended_l(&desc->mType, true);
1397 }
1398 }
1399 }
1400}
1401
Eric Laurent59255e42011-07-27 19:49:51 -07001402void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1403 bool suspend,
1404 int sessionId)
1405{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001406 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001407
1408 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1409
1410 if (suspend) {
1411 if (index >= 0) {
1412 sessionEffects = mSuspendedSessions.editValueAt(index);
1413 } else {
1414 mSuspendedSessions.add(sessionId, sessionEffects);
1415 }
1416 } else {
1417 if (index < 0) {
1418 return;
1419 }
1420 sessionEffects = mSuspendedSessions.editValueAt(index);
1421 }
1422
1423
1424 int key = EffectChain::kKeyForSuspendAll;
1425 if (type != NULL) {
1426 key = type->timeLow;
1427 }
1428 index = sessionEffects.indexOfKey(key);
1429
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001430 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001431 if (suspend) {
1432 if (index >= 0) {
1433 desc = sessionEffects.valueAt(index);
1434 } else {
1435 desc = new SuspendedSessionDesc();
1436 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001437 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001438 }
1439 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001440 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001441 }
1442 desc->mRefCount++;
1443 } else {
1444 if (index < 0) {
1445 return;
1446 }
1447 desc = sessionEffects.valueAt(index);
1448 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001449 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001450 sessionEffects.removeItemsAt(index);
1451 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001453 sessionId);
1454 mSuspendedSessions.removeItem(sessionId);
1455 }
1456 }
1457 }
1458 if (!sessionEffects.isEmpty()) {
1459 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1460 }
1461}
1462
1463void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1464 bool enabled,
1465 int sessionId)
1466{
1467 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001468 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1469}
Eric Laurent59255e42011-07-27 19:49:51 -07001470
Eric Laurenta85a74a2011-10-19 11:44:54 -07001471void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1472 bool enabled,
1473 int sessionId)
1474{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001475 if (mType != RECORD) {
1476 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1477 // another session. This gives the priority to well behaved effect control panels
1478 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001479 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1480 // global effects
1481 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001482 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1483 }
1484 }
Eric Laurent59255e42011-07-27 19:49:51 -07001485
1486 sp<EffectChain> chain = getEffectChain_l(sessionId);
1487 if (chain != 0) {
1488 chain->checkSuspendOnEffectEnabled(effect, enabled);
1489 }
1490}
1491
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492// ----------------------------------------------------------------------------
1493
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001494AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1495 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001496 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001497 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001498 type_t type)
1499 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001500 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1501 // Assumes constructor is called by AudioFlinger with it's mLock held,
1502 // but it would be safer to explicitly pass initial masterMute as parameter
1503 mMasterMute(audioFlinger->masterMute_l()),
1504 // mStreamTypes[] initialized in constructor body
1505 mOutput(output),
1506 // Assumes constructor is called by AudioFlinger with it's mLock held,
1507 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001508 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001509 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001510 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001511 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001512 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001513 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001514 // index 0 is reserved for normal mixer's submix
1515 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516{
Glenn Kasten480b4682012-02-28 12:30:08 -08001517 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001518
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519 readOutputParameters();
1520
Glenn Kasten263709e2012-01-06 08:40:01 -08001521 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001522 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1523 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1524 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001525 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1526 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001528 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1529 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530}
1531
1532AudioFlinger::PlaybackThread::~PlaybackThread()
1533{
1534 delete [] mMixBuffer;
1535}
1536
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001537void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538{
1539 dumpInternals(fd, args);
1540 dumpTracks(fd, args);
1541 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542}
1543
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001544void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545{
1546 const size_t SIZE = 256;
1547 char buffer[SIZE];
1548 String8 result;
1549
Glenn Kasten58912562012-04-03 10:45:00 -07001550 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1551 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1552 const stream_type_t *st = &mStreamTypes[i];
1553 if (i > 0) {
1554 result.appendFormat(", ");
1555 }
1556 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1557 if (st->mute) {
1558 result.append("M");
1559 }
1560 }
1561 result.append("\n");
1562 write(fd, result.string(), result.length());
1563 result.clear();
1564
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1566 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001567 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 for (size_t i = 0; i < mTracks.size(); ++i) {
1569 sp<Track> track = mTracks[i];
1570 if (track != 0) {
1571 track->dump(buffer, SIZE);
1572 result.append(buffer);
1573 }
1574 }
1575
1576 snprintf(buffer, SIZE, "Output thread %p active 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 < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001580 sp<Track> track = mActiveTracks[i].promote();
1581 if (track != 0) {
1582 track->dump(buffer, SIZE);
1583 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 }
1585 }
1586 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001587
1588 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1589 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1590 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1591 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592}
1593
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001594void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595{
1596 const size_t SIZE = 256;
1597 char buffer[SIZE];
1598 String8 result;
1599
1600 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1601 result.append(buffer);
1602 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1603 result.append(buffer);
1604 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1605 result.append(buffer);
1606 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1607 result.append(buffer);
1608 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1609 result.append(buffer);
1610 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1613 result.append(buffer);
1614 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001615 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616
1617 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618}
1619
1620// Thread virtuals
1621status_t AudioFlinger::PlaybackThread::readyToRun()
1622{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001623 status_t status = initCheck();
1624 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001625 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001626 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001627 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001629 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630}
1631
1632void AudioFlinger::PlaybackThread::onFirstRef()
1633{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001634 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635}
1636
1637// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001638sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001640 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001642 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001643 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 int frameCount,
1645 const sp<IMemory>& sharedBuffer,
1646 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001647 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001648 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 status_t *status)
1650{
1651 sp<Track> track;
1652 status_t lStatus;
1653
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1655
1656 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001657 if (flags & IAudioFlinger::TRACK_FAST) {
1658 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001659 // not timed
1660 (!isTimed) &&
1661 // either of these use cases:
1662 (
1663 // use case 1: shared buffer with any frame count
1664 (
1665 (sharedBuffer != 0)
1666 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001667 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001668 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001669 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001670 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001671 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001672 )
1673 ) &&
1674 // PCM data
1675 audio_is_linear_pcm(format) &&
1676 // mono or stereo
1677 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1678 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001679#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001680 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001681 (sampleRate == mSampleRate) &&
1682#endif
1683 // normal mixer has an associated fast mixer
1684 hasFastMixer() &&
1685 // there are sufficient fast track slots available
1686 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001687 // FIXME test that MixerThread for this fast track has a capable output HAL
1688 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001689 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1691 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001692 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001693 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001694 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001695 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001696 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001697 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001698 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001699 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1700 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1701 audio_is_linear_pcm(format),
1702 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001703 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 // For compatibility with AudioTrack calculation, buffer depth is forced
1705 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1706 // This is probably too conservative, but legacy application code may depend on it.
1707 // If you change this calculation, also review the start threshold which is related.
1708 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1709 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1710 if (minBufCount < 2) {
1711 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001712 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001713 int minFrameCount = mNormalFrameCount * minBufCount;
1714 if (frameCount < minFrameCount) {
1715 frameCount = minFrameCount;
1716 }
1717 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001718 }
1719
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001721 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1722 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001723 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001724 "for output %p with format %d",
1725 sampleRate, format, channelMask, mOutput, mFormat);
1726 lStatus = BAD_VALUE;
1727 goto Exit;
1728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 }
1730 } else {
1731 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1732 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001733 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 lStatus = BAD_VALUE;
1735 goto Exit;
1736 }
1737 }
1738
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001739 lStatus = initCheck();
1740 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001741 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 goto Exit;
1743 }
1744
1745 { // scope for mLock
1746 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001747
1748 // all tracks in same audio session must share the same routing strategy otherwise
1749 // conflicts will happen when tracks are moved from one output to another by audio policy
1750 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001751 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001752 for (size_t i = 0; i < mTracks.size(); ++i) {
1753 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001754 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001755 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001756 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001757 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001758 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001759 lStatus = BAD_VALUE;
1760 goto Exit;
1761 }
1762 }
1763 }
1764
John Grossman4ff14ba2012-02-08 16:37:41 -08001765 if (!isTimed) {
1766 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001767 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001768 } else {
1769 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1770 channelMask, frameCount, sharedBuffer, sessionId);
1771 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001772 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 lStatus = NO_MEMORY;
1774 goto Exit;
1775 }
1776 mTracks.add(track);
1777
1778 sp<EffectChain> chain = getEffectChain_l(sessionId);
1779 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001780 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001782 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001783 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 }
1785 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001786
Glenn Kasten3acbd052012-02-28 10:39:56 -08001787 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1788 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1789 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1790 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001791 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001792 if (err != 0) {
1793 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001794 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001795 }
1796 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001797
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 lStatus = NO_ERROR;
1799
1800Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001801 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 *status = lStatus;
1803 }
1804 return track;
1805}
1806
Eric Laurente737cda2012-05-22 18:55:44 -07001807uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1808{
1809 if (mFastMixer != NULL) {
1810 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1811 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1812 }
1813 return latency;
1814}
1815
1816uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1817{
1818 return latency;
1819}
1820
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821uint32_t AudioFlinger::PlaybackThread::latency() const
1822{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001823 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001824 return latency_l();
1825}
1826uint32_t AudioFlinger::PlaybackThread::latency_l() const
1827{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001828 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001829 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001830 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 return 0;
1832 }
1833}
1834
Glenn Kasten6637baa2012-01-09 09:40:36 -08001835void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001837 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839}
1840
Glenn Kasten6637baa2012-01-09 09:40:36 -08001841void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001843 Mutex::Autolock _l(mLock);
1844 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845}
1846
Glenn Kasten6637baa2012-01-09 09:40:36 -08001847void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851}
1852
Glenn Kasten6637baa2012-01-09 09:40:36 -08001853void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Glenn Kastenfff6d712012-01-12 16:38:12 -08001859float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 return mStreamTypes[stream].volume;
1863}
1864
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865// addTrack_l() must be called with ThreadBase::mLock held
1866status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1867{
1868 status_t status = ALREADY_EXISTS;
1869
1870 // set retry count for buffer fill
1871 track->mRetryCount = kMaxTrackStartupRetries;
1872 if (mActiveTracks.indexOf(track) < 0) {
1873 // the track is newly added, make sure it fills up all its
1874 // buffers before playing. This is to ensure the client will
1875 // effectively get the latency it requested.
1876 track->mFillingUpStatus = Track::FS_FILLING;
1877 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001878 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 mActiveTracks.add(track);
1880 if (track->mainBuffer() != mMixBuffer) {
1881 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1882 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001883 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001884 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 }
1886 }
1887
1888 status = NO_ERROR;
1889 }
1890
Steve Block3856b092011-10-20 11:56:00 +01001891 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892 mWaitWorkCV.broadcast();
1893
1894 return status;
1895}
1896
1897// destroyTrack_l() must be called with ThreadBase::mLock held
1898void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1899{
1900 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001901 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001903 removeTrack_l(track);
1904 }
1905}
1906
1907void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1908{
Eric Laurent29864602012-05-08 18:57:51 -07001909 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001910 mTracks.remove(track);
1911 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001912 // redundant as track is about to be destroyed, for dumpsys only
1913 track->mName = -1;
1914 if (track->isFastTrack()) {
1915 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001916 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001917 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1918 mFastTrackAvailMask |= 1 << index;
1919 // redundant as track is about to be destroyed, for dumpsys only
1920 track->mFastIndex = -1;
1921 }
Eric Laurentb469b942011-05-09 12:09:06 -07001922 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1923 if (chain != 0) {
1924 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 }
1926}
1927
1928String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1929{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001930 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001931 char *s;
1932
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001933 Mutex::Autolock _l(mLock);
1934 if (initCheck() != NO_ERROR) {
1935 return out_s8;
1936 }
1937
Dima Zavin799a70e2011-04-18 16:57:27 -07001938 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001939 out_s8 = String8(s);
1940 free(s);
1941 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942}
1943
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001944// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1946 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001947 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948
Steve Block3856b092011-10-20 11:56:00 +01001949 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950
1951 switch (event) {
1952 case AudioSystem::OUTPUT_OPENED:
1953 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001954 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 desc.samplingRate = mSampleRate;
1956 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001957 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 desc.latency = latency();
1959 param2 = &desc;
1960 break;
1961
1962 case AudioSystem::STREAM_CONFIG_CHANGED:
1963 param2 = &param;
1964 case AudioSystem::OUTPUT_CLOSED:
1965 default:
1966 break;
1967 }
1968 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1969}
1970
1971void AudioFlinger::PlaybackThread::readOutputParameters()
1972{
Dima Zavin799a70e2011-04-18 16:57:27 -07001973 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001974 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1975 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001976 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001977 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001978 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001979 if (mFrameCount & 15) {
1980 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1981 mFrameCount);
1982 }
1983
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001984 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001985 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001986 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001987 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001988 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1989 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1990 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1991 maxNormalFrameCount = maxNormalFrameCount & ~15;
1992 if (maxNormalFrameCount < minNormalFrameCount) {
1993 maxNormalFrameCount = minNormalFrameCount;
1994 }
1995 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1996 if (multiplier <= 1.0) {
1997 multiplier = 1.0;
1998 } else if (multiplier <= 2.0) {
1999 if (2 * mFrameCount <= maxNormalFrameCount) {
2000 multiplier = 2.0;
2001 } else {
2002 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2003 }
2004 } else {
2005 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2006 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2007 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2008 // FIXME this rounding up should not be done if no HAL SRC
2009 uint32_t truncMult = (uint32_t) multiplier;
2010 if ((truncMult & 1)) {
2011 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2012 ++truncMult;
2013 }
2014 }
2015 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002016 }
Glenn Kasten58912562012-04-03 10:45:00 -07002017 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002018 mNormalFrameCount = multiplier * mFrameCount;
2019 // round up to nearest 16 frames to satisfy AudioMixer
2020 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002021 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022
Glenn Kastene9dd0172012-01-27 18:08:45 -08002023 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002024 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2025 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026
Eric Laurentde070132010-07-13 04:45:46 -07002027 // force reconfiguration of effect chains and engines to take new buffer size and audio
2028 // parameters into account
2029 // Note that mLock is not held when readOutputParameters() is called from the constructor
2030 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2031 // matter.
2032 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2033 Vector< sp<EffectChain> > effectChains = mEffectChains;
2034 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002035 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037}
2038
Eric Laurente737cda2012-05-22 18:55:44 -07002039
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2041{
Glenn Kastena0d68332012-01-27 16:47:15 -08002042 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 return BAD_VALUE;
2044 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002045 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002046 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 return INVALID_OPERATION;
2048 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002049 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050
Dima Zavin799a70e2011-04-18 16:57:27 -07002051 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052}
2053
Eric Laurent39e94f82010-07-28 01:32:47 -07002054uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055{
2056 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002057 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002059 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 }
2061
2062 for (size_t i = 0; i < mTracks.size(); ++i) {
2063 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002064 if (sessionId == track->sessionId() &&
2065 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002066 result |= TRACK_SESSION;
2067 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 }
2069 }
2070
Eric Laurent39e94f82010-07-28 01:32:47 -07002071 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072}
2073
Eric Laurentde070132010-07-13 04:45:46 -07002074uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2075{
Dima Zavinfce7a472011-04-19 22:30:36 -07002076 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002077 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002078 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2079 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002080 }
2081 for (size_t i = 0; i < mTracks.size(); i++) {
2082 sp<Track> track = mTracks[i];
2083 if (sessionId == track->sessionId() &&
2084 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002085 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002086 }
2087 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002088 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002089}
2090
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091
Glenn Kastenaed850d2012-01-26 09:46:34 -08002092AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002093{
2094 Mutex::Autolock _l(mLock);
2095 return mOutput;
2096}
2097
2098AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2099{
2100 Mutex::Autolock _l(mLock);
2101 AudioStreamOut *output = mOutput;
2102 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002103 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2104 // must push a NULL and wait for ack
2105 mOutputSink.clear();
2106 mPipeSink.clear();
2107 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002108 return output;
2109}
2110
2111// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002112audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002113{
2114 if (mOutput == NULL) {
2115 return NULL;
2116 }
2117 return &mOutput->stream->common;
2118}
2119
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002120uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002121{
Eric Laurentab9071b2012-06-04 13:45:29 -07002122 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002123}
2124
Eric Laurenta011e352012-03-29 15:51:43 -07002125status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2126{
2127 if (!isValidSyncEvent(event)) {
2128 return BAD_VALUE;
2129 }
2130
2131 Mutex::Autolock _l(mLock);
2132
2133 for (size_t i = 0; i < mTracks.size(); ++i) {
2134 sp<Track> track = mTracks[i];
2135 if (event->triggerSession() == track->sessionId()) {
2136 track->setSyncEvent(event);
2137 return NO_ERROR;
2138 }
2139 }
2140
2141 return NAME_NOT_FOUND;
2142}
2143
2144bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2145{
2146 switch (event->type()) {
2147 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2148 return true;
2149 default:
2150 break;
2151 }
2152 return false;
2153}
2154
Eric Laurent44a957f2012-05-15 15:26:05 -07002155void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2156{
2157 size_t count = tracksToRemove.size();
2158 if (CC_UNLIKELY(count)) {
2159 for (size_t i = 0 ; i < count ; i++) {
2160 const sp<Track>& track = tracksToRemove.itemAt(i);
2161 if ((track->sharedBuffer() != 0) &&
2162 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2163 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2164 }
2165 }
2166 }
2167
2168}
2169
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170// ----------------------------------------------------------------------------
2171
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002172AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002173 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002174 : PlaybackThread(audioFlinger, output, id, device, type),
2175 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002176 // mFastMixer below
2177 mFastMixerFutex(0)
2178 // mOutputSink below
2179 // mPipeSink below
2180 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002182 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002183 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002184 "mFrameCount=%d, mNormalFrameCount=%d",
2185 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2186 mNormalFrameCount);
2187 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2188
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002190 if (mChannelCount != FCC_2) {
2191 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 }
Glenn Kasten58912562012-04-03 10:45:00 -07002193
2194 // create an NBAIO sink for the HAL output stream, and negotiate
2195 mOutputSink = new AudioStreamOutSink(output->stream);
2196 size_t numCounterOffers = 0;
2197 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2198 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2199 ALOG_ASSERT(index == 0);
2200
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002201 // initialize fast mixer depending on configuration
2202 bool initFastMixer;
2203 switch (kUseFastMixer) {
2204 case FastMixer_Never:
2205 initFastMixer = false;
2206 break;
2207 case FastMixer_Always:
2208 initFastMixer = true;
2209 break;
2210 case FastMixer_Static:
2211 case FastMixer_Dynamic:
2212 initFastMixer = mFrameCount < mNormalFrameCount;
2213 break;
2214 }
2215 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002216
2217 // create a MonoPipe to connect our submix to FastMixer
2218 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002219 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2220 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2221 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2222 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002223 const NBAIO_Format offers[1] = {format};
2224 size_t numCounterOffers = 0;
2225 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2226 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002227 monoPipe->setAvgFrames((mScreenState & 1) ?
2228 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002229 mPipeSink = monoPipe;
2230
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002231#ifdef TEE_SINK_FRAMES
2232 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2233 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2234 numCounterOffers = 0;
2235 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2236 ALOG_ASSERT(index == 0);
2237 mTeeSink = teeSink;
2238 PipeReader *teeSource = new PipeReader(*teeSink);
2239 numCounterOffers = 0;
2240 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2241 ALOG_ASSERT(index == 0);
2242 mTeeSource = teeSource;
2243#endif
2244
Glenn Kasten58912562012-04-03 10:45:00 -07002245 // create fast mixer and configure it initially with just one fast track for our submix
2246 mFastMixer = new FastMixer();
2247 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002248#ifdef STATE_QUEUE_DUMP
2249 sq->setObserverDump(&mStateQueueObserverDump);
2250 sq->setMutatorDump(&mStateQueueMutatorDump);
2251#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002252 FastMixerState *state = sq->begin();
2253 FastTrack *fastTrack = &state->mFastTracks[0];
2254 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2255 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2256 fastTrack->mVolumeProvider = NULL;
2257 fastTrack->mGeneration++;
2258 state->mFastTracksGen++;
2259 state->mTrackMask = 1;
2260 // fast mixer will use the HAL output sink
2261 state->mOutputSink = mOutputSink.get();
2262 state->mOutputSinkGen++;
2263 state->mFrameCount = mFrameCount;
2264 state->mCommand = FastMixerState::COLD_IDLE;
2265 // already done in constructor initialization list
2266 //mFastMixerFutex = 0;
2267 state->mColdFutexAddr = &mFastMixerFutex;
2268 state->mColdGen++;
2269 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002270 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002271 sq->end();
2272 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2273
2274 // start the fast mixer
2275 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002276 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002277 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002278 if (err != 0) {
2279 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002280 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002281 }
Glenn Kasten58912562012-04-03 10:45:00 -07002282
Glenn Kastenc15d6652012-05-30 14:52:57 -07002283#ifdef AUDIO_WATCHDOG
2284 // create and start the watchdog
2285 mAudioWatchdog = new AudioWatchdog();
2286 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2287 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2288 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002289 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002290 if (err != 0) {
2291 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002292 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002293 }
2294#endif
2295
Glenn Kasten58912562012-04-03 10:45:00 -07002296 } else {
2297 mFastMixer = NULL;
2298 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002299
2300 switch (kUseFastMixer) {
2301 case FastMixer_Never:
2302 case FastMixer_Dynamic:
2303 mNormalSink = mOutputSink;
2304 break;
2305 case FastMixer_Always:
2306 mNormalSink = mPipeSink;
2307 break;
2308 case FastMixer_Static:
2309 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2310 break;
2311 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312}
2313
2314AudioFlinger::MixerThread::~MixerThread()
2315{
Glenn Kasten58912562012-04-03 10:45:00 -07002316 if (mFastMixer != NULL) {
2317 FastMixerStateQueue *sq = mFastMixer->sq();
2318 FastMixerState *state = sq->begin();
2319 if (state->mCommand == FastMixerState::COLD_IDLE) {
2320 int32_t old = android_atomic_inc(&mFastMixerFutex);
2321 if (old == -1) {
2322 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2323 }
2324 }
2325 state->mCommand = FastMixerState::EXIT;
2326 sq->end();
2327 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2328 mFastMixer->join();
2329 // Though the fast mixer thread has exited, it's state queue is still valid.
2330 // We'll use that extract the final state which contains one remaining fast track
2331 // corresponding to our sub-mix.
2332 state = sq->begin();
2333 ALOG_ASSERT(state->mTrackMask == 1);
2334 FastTrack *fastTrack = &state->mFastTracks[0];
2335 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2336 delete fastTrack->mBufferProvider;
2337 sq->end(false /*didModify*/);
2338 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002339 if (mAudioWatchdog != 0) {
2340 mAudioWatchdog->requestExit();
2341 mAudioWatchdog->requestExitAndWait();
2342 mAudioWatchdog.clear();
2343 }
Glenn Kasten58912562012-04-03 10:45:00 -07002344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 delete mAudioMixer;
2346}
2347
Glenn Kasten83efdd02012-02-24 07:21:32 -08002348class CpuStats {
2349public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002350 CpuStats();
2351 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002352#ifdef DEBUG_CPU_USAGE
2353private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002354 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2355 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2356
2357 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2358
2359 int mCpuNum; // thread's current CPU number
2360 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002361#endif
2362};
2363
Glenn Kasten190a46f2012-03-06 11:27:10 -08002364CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002365#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002366 : mCpuNum(-1), mCpukHz(-1)
2367#endif
2368{
2369}
2370
2371void CpuStats::sample(const String8 &title) {
2372#ifdef DEBUG_CPU_USAGE
2373 // get current thread's delta CPU time in wall clock ns
2374 double wcNs;
2375 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2376
2377 // record sample for wall clock statistics
2378 if (valid) {
2379 mWcStats.sample(wcNs);
2380 }
2381
2382 // get the current CPU number
2383 int cpuNum = sched_getcpu();
2384
2385 // get the current CPU frequency in kHz
2386 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2387
2388 // check if either CPU number or frequency changed
2389 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2390 mCpuNum = cpuNum;
2391 mCpukHz = cpukHz;
2392 // ignore sample for purposes of cycles
2393 valid = false;
2394 }
2395
2396 // if no change in CPU number or frequency, then record sample for cycle statistics
2397 if (valid && mCpukHz > 0) {
2398 double cycles = wcNs * cpukHz * 0.000001;
2399 mHzStats.sample(cycles);
2400 }
2401
2402 unsigned n = mWcStats.n();
2403 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002404 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002405 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002406 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2407 double perLoop = elapsed / (double) n;
2408 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002409 double perLoop1k = perLoop * 0.001;
2410 double mean = mWcStats.mean();
2411 double stddev = mWcStats.stddev();
2412 double minimum = mWcStats.minimum();
2413 double maximum = mWcStats.maximum();
2414 double meanCycles = mHzStats.mean();
2415 double stddevCycles = mHzStats.stddev();
2416 double minCycles = mHzStats.minimum();
2417 double maxCycles = mHzStats.maximum();
2418 mCpuUsage.resetElapsed();
2419 mWcStats.reset();
2420 mHzStats.reset();
2421 ALOGD("CPU usage for %s over past %.1f secs\n"
2422 " (%u mixer loops at %.1f mean ms per loop):\n"
2423 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2424 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2425 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2426 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002427 elapsed * .000000001, n, perLoop * .000001,
2428 mean * .001,
2429 stddev * .001,
2430 minimum * .001,
2431 maximum * .001,
2432 mean / perLoop100,
2433 stddev / perLoop100,
2434 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002435 maximum / perLoop100,
2436 meanCycles / perLoop1k,
2437 stddevCycles / perLoop1k,
2438 minCycles / perLoop1k,
2439 maxCycles / perLoop1k);
2440
Glenn Kasten83efdd02012-02-24 07:21:32 -08002441 }
2442 }
2443#endif
2444};
2445
Glenn Kasten37d825e2012-02-24 07:21:48 -08002446void AudioFlinger::PlaybackThread::checkSilentMode_l()
2447{
2448 if (!mMasterMute) {
2449 char value[PROPERTY_VALUE_MAX];
2450 if (property_get("ro.audio.silent", value, "0") > 0) {
2451 char *endptr;
2452 unsigned long ul = strtoul(value, &endptr, 0);
2453 if (*endptr == '\0' && ul != 0) {
2454 ALOGD("Silence is golden");
2455 // The setprop command will not allow a property to be changed after
2456 // the first time it is set, so we don't have to worry about un-muting.
2457 setMasterMute_l(true);
2458 }
2459 }
2460 }
2461}
2462
Glenn Kasten000f0e32012-03-01 17:10:56 -08002463bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464{
2465 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002466
Glenn Kasten000f0e32012-03-01 17:10:56 -08002467 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002468
2469 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002471
Glenn Kasten000f0e32012-03-01 17:10:56 -08002472 // DUPLICATING
2473 // FIXME could this be made local to while loop?
2474 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002475
Glenn Kasten66fcab92012-02-24 14:59:21 -08002476 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002477 sleepTime = idleSleepTime;
2478
Glenn Kasten9f34a362012-03-20 16:46:41 -07002479 if (mType == MIXER) {
2480 sleepTimeShift = 0;
2481 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002482
Glenn Kasten83efdd02012-02-24 07:21:32 -08002483 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002484 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
Eric Laurentfeb0db62011-07-22 09:04:31 -07002486 acquireWakeLock();
2487
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488 while (!exitPending())
2489 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002490 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002491
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002492 Vector< sp<EffectChain> > effectChains;
2493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 processConfigEvents();
2495
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 { // scope for mLock
2497
2498 Mutex::Autolock _l(mLock);
2499
2500 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002501 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 }
2503
Glenn Kastenfa26a852012-03-06 11:28:04 -08002504 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002505
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002507 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002508 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002510
2511 threadLoop_standby();
2512
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 mStandby = true;
2514 mBytesWritten = 0;
2515 }
2516
Glenn Kasten3e074702012-02-28 18:40:35 -08002517 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 // we're about to wait, flush the binder command buffer
2519 IPCThreadState::self()->flushCommands();
2520
Glenn Kastenfa26a852012-03-06 11:28:04 -08002521 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002522
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 if (exitPending()) break;
2524
Eric Laurentfeb0db62011-07-22 09:04:31 -07002525 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002529 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002530 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531
Eric Laurentda747442012-04-25 18:53:13 -07002532 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002533 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
Glenn Kasten37d825e2012-02-24 07:21:48 -08002535 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536
Glenn Kasten000f0e32012-03-01 17:10:56 -08002537 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002539 if (mType == MIXER) {
2540 sleepTimeShift = 0;
2541 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002542
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 continue;
2544 }
2545 }
2546
Glenn Kasten81028042012-04-30 18:15:12 -07002547 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002548 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549
2550 // prevent any changes in effect chain list and in each effect chain
2551 // during mixing and effect process as the audio buffers could be deleted
2552 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002553 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555
Glenn Kastenfec279f2012-03-08 07:47:15 -08002556 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002557 threadLoop_mix();
2558 } else {
2559 threadLoop_sleepTime();
2560 }
2561
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002562 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563 sleepTime = suspendSleepTimeUs();
2564 }
2565
2566 // only process effects if we're going to write
2567 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002568 for (size_t i = 0; i < effectChains.size(); i ++) {
2569 effectChains[i]->process_l();
2570 }
2571 }
2572
2573 // enable changes in effect chain
2574 unlockEffectChains(effectChains);
2575
2576 // sleepTime == 0 means we must write to audio hardware
2577 if (sleepTime == 0) {
2578
2579 threadLoop_write();
2580
2581if (mType == MIXER) {
2582 // write blocked detection
2583 nsecs_t now = systemTime();
2584 nsecs_t delta = now - mLastWriteTime;
2585 if (!mStandby && delta > maxPeriod) {
2586 mNumDelayedWrites++;
2587 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002588#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002589 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002590#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002591 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2592 ns2ms(delta), mNumDelayedWrites, this);
2593 lastWarning = now;
2594 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002595 }
2596}
2597
2598 mStandby = false;
2599 } else {
2600 usleep(sleepTime);
2601 }
2602
Glenn Kasten58912562012-04-03 10:45:00 -07002603 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002604 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002605 // same lock. This will also mutate and push a new fast mixer state.
2606 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002607 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002608
Glenn Kastenfa26a852012-03-06 11:28:04 -08002609 // FIXME I don't understand the need for this here;
2610 // it was in the original code but maybe the
2611 // assignment in saveOutputTracks() makes this unnecessary?
2612 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002613
2614 // Effect chains will be actually deleted here if they were removed from
2615 // mEffectChains list during mixing or effects processing
2616 effectChains.clear();
2617
2618 // FIXME Note that the above .clear() is no longer necessary since effectChains
2619 // is now local to this block, but will keep it for now (at least until merge done).
2620 }
2621
Glenn Kasten9f34a362012-03-20 16:46:41 -07002622 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2623 if (mType == MIXER || mType == DIRECT) {
2624 // put output stream into standby mode
2625 if (!mStandby) {
2626 mOutput->stream->common.standby(&mOutput->stream->common);
2627 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002628 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002629
2630 releaseWakeLock();
2631
2632 ALOGV("Thread %p type %d exiting", this, mType);
2633 return false;
2634}
2635
Glenn Kasten58912562012-04-03 10:45:00 -07002636void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2637{
Glenn Kasten58912562012-04-03 10:45:00 -07002638 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2639}
2640
2641void AudioFlinger::MixerThread::threadLoop_write()
2642{
2643 // FIXME we should only do one push per cycle; confirm this is true
2644 // Start the fast mixer if it's not already running
2645 if (mFastMixer != NULL) {
2646 FastMixerStateQueue *sq = mFastMixer->sq();
2647 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002648 if (state->mCommand != FastMixerState::MIX_WRITE &&
2649 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002650 if (state->mCommand == FastMixerState::COLD_IDLE) {
2651 int32_t old = android_atomic_inc(&mFastMixerFutex);
2652 if (old == -1) {
2653 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2654 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002655 if (mAudioWatchdog != 0) {
2656 mAudioWatchdog->resume();
2657 }
Glenn Kasten58912562012-04-03 10:45:00 -07002658 }
2659 state->mCommand = FastMixerState::MIX_WRITE;
2660 sq->end();
2661 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002662 if (kUseFastMixer == FastMixer_Dynamic) {
2663 mNormalSink = mPipeSink;
2664 }
Glenn Kasten58912562012-04-03 10:45:00 -07002665 } else {
2666 sq->end(false /*didModify*/);
2667 }
2668 }
2669 PlaybackThread::threadLoop_write();
2670}
2671
Glenn Kasten000f0e32012-03-01 17:10:56 -08002672// shared by MIXER and DIRECT, overridden by DUPLICATING
2673void AudioFlinger::PlaybackThread::threadLoop_write()
2674{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002675 // FIXME rewrite to reduce number of system calls
2676 mLastWriteTime = systemTime();
2677 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002678 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002679
Eric Laurent67c0a582012-05-01 19:31:12 -07002680 // If an NBAIO sink is present, use it to write the normal mixer's submix
2681 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002682#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002683 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002684#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002685 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002686#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002687 // update the setpoint when gScreenState changes
2688 uint32_t screenState = gScreenState;
2689 if (screenState != mScreenState) {
2690 mScreenState = screenState;
2691 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2692 if (pipe != NULL) {
2693 pipe->setAvgFrames((mScreenState & 1) ?
2694 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2695 }
2696 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002697 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002698#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002699 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002700#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002701 if (framesWritten > 0) {
2702 bytesWritten = framesWritten << mBitShift;
2703 } else {
2704 bytesWritten = framesWritten;
2705 }
2706 // otherwise use the HAL / AudioStreamOut directly
2707 } else {
2708 // Direct output thread.
2709 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002710 }
2711
Eric Laurent67c0a582012-05-01 19:31:12 -07002712 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002713 mNumWrites++;
2714 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002715}
2716
Glenn Kasten58912562012-04-03 10:45:00 -07002717void AudioFlinger::MixerThread::threadLoop_standby()
2718{
2719 // Idle the fast mixer if it's currently running
2720 if (mFastMixer != NULL) {
2721 FastMixerStateQueue *sq = mFastMixer->sq();
2722 FastMixerState *state = sq->begin();
2723 if (!(state->mCommand & FastMixerState::IDLE)) {
2724 state->mCommand = FastMixerState::COLD_IDLE;
2725 state->mColdFutexAddr = &mFastMixerFutex;
2726 state->mColdGen++;
2727 mFastMixerFutex = 0;
2728 sq->end();
2729 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002731 if (kUseFastMixer == FastMixer_Dynamic) {
2732 mNormalSink = mOutputSink;
2733 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002734 if (mAudioWatchdog != 0) {
2735 mAudioWatchdog->pause();
2736 }
Glenn Kasten58912562012-04-03 10:45:00 -07002737 } else {
2738 sq->end(false /*didModify*/);
2739 }
2740 }
2741 PlaybackThread::threadLoop_standby();
2742}
2743
Glenn Kasten000f0e32012-03-01 17:10:56 -08002744// shared by MIXER and DIRECT, overridden by DUPLICATING
2745void AudioFlinger::PlaybackThread::threadLoop_standby()
2746{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002747 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002748 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002749}
2750
2751void AudioFlinger::MixerThread::threadLoop_mix()
2752{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002753 // obtain the presentation timestamp of the next output buffer
2754 int64_t pts;
2755 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002756
Glenn Kasten952eeb22012-03-06 11:30:57 -08002757 if (NULL != mOutput->stream->get_next_write_timestamp) {
2758 status = mOutput->stream->get_next_write_timestamp(
2759 mOutput->stream, &pts);
2760 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002761
Glenn Kasten952eeb22012-03-06 11:30:57 -08002762 if (status != NO_ERROR) {
2763 pts = AudioBufferProvider::kInvalidPTS;
2764 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002765
Glenn Kasten952eeb22012-03-06 11:30:57 -08002766 // mix buffers...
2767 mAudioMixer->process(pts);
2768 // increase sleep time progressively when application underrun condition clears.
2769 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2770 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2771 // such that we would underrun the audio HAL.
2772 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2773 sleepTimeShift--;
2774 }
2775 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002776 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002777 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002778}
2779
2780void AudioFlinger::MixerThread::threadLoop_sleepTime()
2781{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002782 // If no tracks are ready, sleep once for the duration of an output
2783 // buffer size, then write 0s to the output
2784 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002785 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002786 sleepTime = activeSleepTime >> sleepTimeShift;
2787 if (sleepTime < kMinThreadSleepTimeUs) {
2788 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 // reduce sleep time in case of consecutive application underruns to avoid
2791 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2792 // duration we would end up writing less data than needed by the audio HAL if
2793 // the condition persists.
2794 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2795 sleepTimeShift++;
2796 }
2797 } else {
2798 sleepTime = idleSleepTime;
2799 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002800 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 memset (mMixBuffer, 0, mixBufferSize);
2802 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002803 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 }
2805 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806}
2807
2808// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002809AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002810 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811{
2812
Glenn Kasten29c23c32012-01-26 13:37:52 -08002813 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002815 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 size_t mixedTracks = 0;
2817 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002818 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002819 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002820 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821
2822 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002823 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824
Eric Laurent571d49c2010-08-11 05:20:11 -07002825 if (masterMute) {
2826 masterVolume = 0;
2827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002829 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002831 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002832 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 masterVolume = (float)((v + (1 << 23)) >> 24);
2834 chain.clear();
2835 }
2836
Glenn Kasten288ed212012-04-25 17:52:27 -07002837 // prepare a new state to push
2838 FastMixerStateQueue *sq = NULL;
2839 FastMixerState *state = NULL;
2840 bool didModify = false;
2841 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2842 if (mFastMixer != NULL) {
2843 sq = mFastMixer->sq();
2844 state = sq->begin();
2845 }
2846
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002848 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 if (t == 0) continue;
2850
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002851 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002853
Glenn Kasten288ed212012-04-25 17:52:27 -07002854 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002855 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002856
2857 // It's theoretically possible (though unlikely) for a fast track to be created
2858 // and then removed within the same normal mix cycle. This is not a problem, as
2859 // the track never becomes active so it's fast mixer slot is never touched.
2860 // The converse, of removing an (active) track and then creating a new track
2861 // at the identical fast mixer slot within the same normal mix cycle,
2862 // is impossible because the slot isn't marked available until the end of each cycle.
2863 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002864 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2865 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002866 FastTrack *fastTrack = &state->mFastTracks[j];
2867
2868 // Determine whether the track is currently in underrun condition,
2869 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002870 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2871 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002872 uint32_t recentFull = (underruns.mBitFields.mFull -
2873 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2874 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2875 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2876 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2877 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2878 uint32_t recentUnderruns = recentPartial + recentEmpty;
2879 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002880 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002881 // or stopped which can occur when flush() is called while active
2882 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002883 track->mUnderrunCount += recentUnderruns;
2884 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002885
Glenn Kastend08f48c2012-05-01 18:14:02 -07002886 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002887 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002888 bool isActive = true;
2889 switch (track->mState) {
2890 case TrackBase::STOPPING_1:
2891 // track stays active in STOPPING_1 state until first underrun
2892 if (recentUnderruns > 0) {
2893 track->mState = TrackBase::STOPPING_2;
2894 }
2895 break;
2896 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002897 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002898 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002899 break;
2900 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002901 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002902 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002903 break;
2904 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002905 if (recentFull > 0 || recentPartial > 0) {
2906 // track has provided at least some frames recently: reset retry count
2907 track->mRetryCount = kMaxTrackRetries;
2908 }
2909 if (recentUnderruns == 0) {
2910 // no recent underruns: stay active
2911 break;
2912 }
2913 // there has recently been an underrun of some kind
2914 if (track->sharedBuffer() == 0) {
2915 // were any of the recent underruns "empty" (no frames available)?
2916 if (recentEmpty == 0) {
2917 // no, then ignore the partial underruns as they are allowed indefinitely
2918 break;
2919 }
2920 // there has recently been an "empty" underrun: decrement the retry counter
2921 if (--(track->mRetryCount) > 0) {
2922 break;
2923 }
2924 // indicate to client process that the track was disabled because of underrun;
2925 // it will then automatically call start() when data is available
2926 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2927 // remove from active list, but state remains ACTIVE [confusing but true]
2928 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002929 break;
2930 }
2931 // fall through
2932 case TrackBase::STOPPING_2:
2933 case TrackBase::PAUSED:
2934 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002935 case TrackBase::STOPPED:
2936 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002937 // Check for presentation complete if track is inactive
2938 // We have consumed all the buffers of this track.
2939 // This would be incomplete if we auto-paused on underrun
2940 {
2941 size_t audioHALFrames =
2942 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2943 size_t framesWritten =
2944 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2945 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2946 // track stays in active list until presentation is complete
2947 break;
2948 }
2949 }
2950 if (track->isStopping_2()) {
2951 track->mState = TrackBase::STOPPED;
2952 }
2953 if (track->isStopped()) {
2954 // Can't reset directly, as fast mixer is still polling this track
2955 // track->reset();
2956 // So instead mark this track as needing to be reset after push with ack
2957 resetMask |= 1 << i;
2958 }
2959 isActive = false;
2960 break;
2961 case TrackBase::IDLE:
2962 default:
2963 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002964 }
2965
2966 if (isActive) {
2967 // was it previously inactive?
2968 if (!(state->mTrackMask & (1 << j))) {
2969 ExtendedAudioBufferProvider *eabp = track;
2970 VolumeProvider *vp = track;
2971 fastTrack->mBufferProvider = eabp;
2972 fastTrack->mVolumeProvider = vp;
2973 fastTrack->mSampleRate = track->mSampleRate;
2974 fastTrack->mChannelMask = track->mChannelMask;
2975 fastTrack->mGeneration++;
2976 state->mTrackMask |= 1 << j;
2977 didModify = true;
2978 // no acknowledgement required for newly active tracks
2979 }
2980 // cache the combined master volume and stream type volume for fast mixer; this
2981 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2982 track->mCachedVolume = track->isMuted() ?
2983 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2984 ++fastTracks;
2985 } else {
2986 // was it previously active?
2987 if (state->mTrackMask & (1 << j)) {
2988 fastTrack->mBufferProvider = NULL;
2989 fastTrack->mGeneration++;
2990 state->mTrackMask &= ~(1 << j);
2991 didModify = true;
2992 // If any fast tracks were removed, we must wait for acknowledgement
2993 // because we're about to decrement the last sp<> on those tracks.
2994 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002995 } else {
2996 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002997 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002998 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002999 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003000 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003001 }
3002 continue;
3003 }
3004
3005 { // local variable scope to avoid goto warning
3006
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 audio_track_cblk_t* cblk = track->cblk();
3008
3009 // The first time a track is added we wait
3010 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003011 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003012 // make sure that we have enough frames to mix one full buffer.
3013 // enforce this condition only once to enable draining the buffer in case the client
3014 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003015 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003016 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003017 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003018 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003019 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003020 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003021 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003022 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003023 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003024 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003025 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003026 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003027 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3028 // the minimum track buffer size is normally twice the number of frames necessary
3029 // to fill one buffer and the resampler should not leave more than one buffer worth
3030 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003031 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003032 }
3033 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003034 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 !track->isPaused() && !track->isTerminated())
3036 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003037 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038
3039 mixedTracks++;
3040
3041 // track->mainBuffer() != mMixBuffer means there is an effect chain
3042 // connected to the track
3043 chain.clear();
3044 if (track->mainBuffer() != mMixBuffer) {
3045 chain = getEffectChain_l(track->sessionId());
3046 // Delegate volume control to effect in track effect chain if needed
3047 if (chain != 0) {
3048 tracksWithEffect++;
3049 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003050 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003051 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 }
3053 }
3054
3055
3056 int param = AudioMixer::VOLUME;
3057 if (track->mFillingUpStatus == Track::FS_FILLED) {
3058 // no ramp for the first volume setting
3059 track->mFillingUpStatus = Track::FS_ACTIVE;
3060 if (track->mState == TrackBase::RESUMING) {
3061 track->mState = TrackBase::ACTIVE;
3062 param = AudioMixer::RAMP_VOLUME;
3063 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003064 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065 } else if (cblk->server != 0) {
3066 // If the track is stopped before the first frame was mixed,
3067 // do not apply ramp
3068 param = AudioMixer::RAMP_VOLUME;
3069 }
3070
3071 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003072 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003073 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003074 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003075 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 if (track->isPausing()) {
3077 track->setPaused();
3078 }
3079 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003080
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003082 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003084 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003085 vl = vlr & 0xFFFF;
3086 vr = vlr >> 16;
3087 // track volumes come from shared memory, so can't be trusted and must be clamped
3088 if (vl > MAX_GAIN_INT) {
3089 ALOGV("Track left volume out of range: %04X", vl);
3090 vl = MAX_GAIN_INT;
3091 }
3092 if (vr > MAX_GAIN_INT) {
3093 ALOGV("Track right volume out of range: %04X", vr);
3094 vr = MAX_GAIN_INT;
3095 }
3096 // now apply the master volume and stream type volume
3097 vl = (uint32_t)(v * vl) << 12;
3098 vr = (uint32_t)(v * vr) << 12;
3099 // assuming master volume and stream type volume each go up to 1.0,
3100 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101
Glenn Kasten05632a52012-01-03 14:22:33 -08003102 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3103 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003104 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003105 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003106 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003107 }
3108 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003110 // Delegate volume control to effect in track effect chain if needed
3111 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3112 // Do not ramp volume if volume is controlled by effect
3113 param = AudioMixer::VOLUME;
3114 track->mHasVolumeController = true;
3115 } else {
3116 // force no volume ramp when volume controller was just disabled or removed
3117 // from effect chain to avoid volume spike
3118 if (track->mHasVolumeController) {
3119 param = AudioMixer::VOLUME;
3120 }
3121 track->mHasVolumeController = false;
3122 }
3123
3124 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003125 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003126 vl = (vl + (1 << 11)) >> 12;
3127 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3128 vr = (vr + (1 << 11)) >> 12;
3129 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003130
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003131 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 -07003132
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003134 mAudioMixer->setBufferProvider(name, track);
3135 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003137 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3138 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3139 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003141 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 AudioMixer::TRACK,
3143 AudioMixer::FORMAT, (void *)track->format());
3144 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003145 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003147 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003149 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 AudioMixer::RESAMPLE,
3151 AudioMixer::SAMPLE_RATE,
3152 (void *)(cblk->sampleRate));
3153 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003154 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 AudioMixer::TRACK,
3156 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3157 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003158 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 AudioMixer::TRACK,
3160 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3161
3162 // reset retry count
3163 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003164
Eric Laurent27741442012-01-17 19:20:12 -08003165 // If one track is ready, set the mixer ready if:
3166 // - the mixer was not ready during previous round OR
3167 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003168 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003169 mixerStatus != MIXER_TRACKS_ENABLED) {
3170 mixerStatus = MIXER_TRACKS_READY;
3171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003173 // clear effect chain input buffer if an active track underruns to avoid sending
3174 // previous audio buffer again to effects
3175 chain = getEffectChain_l(track->sessionId());
3176 if (chain != 0) {
3177 chain->clearInputBuffer();
3178 }
3179
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003180 //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 -07003181 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3182 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 // We have consumed all the buffers of this track.
3184 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003185 // TODO: use actual buffer filling status instead of latency when available from
3186 // audio HAL
3187 size_t audioHALFrames =
3188 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3189 size_t framesWritten =
3190 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3191 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003192 if (track->isStopped()) {
3193 track->reset();
3194 }
Eric Laurenta011e352012-03-29 15:51:43 -07003195 tracksToRemove->add(track);
3196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003198 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 // No buffers for this track. Give it a few chances to
3200 // fill a buffer, then remove it from active list.
3201 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003202 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003204 // indicate to client process that the track was disabled because of underrun;
3205 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003206 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003207 // If one track is not ready, mark the mixer also not ready if:
3208 // - the mixer was ready during previous round OR
3209 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003210 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003211 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 mixerStatus = MIXER_TRACKS_ENABLED;
3213 }
3214 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003215 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 }
Glenn Kasten58912562012-04-03 10:45:00 -07003217
3218 } // local variable scope to avoid goto warning
3219track_is_ready: ;
3220
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221 }
3222
Glenn Kasten288ed212012-04-25 17:52:27 -07003223 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003224 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003225 if (didModify) {
3226 state->mFastTracksGen++;
3227 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3228 if (kUseFastMixer == FastMixer_Dynamic &&
3229 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3230 state->mCommand = FastMixerState::COLD_IDLE;
3231 state->mColdFutexAddr = &mFastMixerFutex;
3232 state->mColdGen++;
3233 mFastMixerFutex = 0;
3234 if (kUseFastMixer == FastMixer_Dynamic) {
3235 mNormalSink = mOutputSink;
3236 }
3237 // If we go into cold idle, need to wait for acknowledgement
3238 // so that fast mixer stops doing I/O.
3239 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003240 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003241 }
3242 sq->end();
3243 }
3244 if (sq != NULL) {
3245 sq->end(didModify);
3246 sq->push(block);
3247 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003248 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3249 mAudioWatchdog->pause();
3250 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003251
3252 // Now perform the deferred reset on fast tracks that have stopped
3253 while (resetMask != 0) {
3254 size_t i = __builtin_ctz(resetMask);
3255 ALOG_ASSERT(i < count);
3256 resetMask &= ~(1 << i);
3257 sp<Track> t = mActiveTracks[i].promote();
3258 if (t == 0) continue;
3259 Track* track = t.get();
3260 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3261 track->reset();
3262 }
Glenn Kasten58912562012-04-03 10:45:00 -07003263
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 // remove all the tracks that need to be...
3265 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003266 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 for (size_t i=0 ; i<count ; i++) {
3268 const sp<Track>& track = tracksToRemove->itemAt(i);
3269 mActiveTracks.remove(track);
3270 if (track->mainBuffer() != mMixBuffer) {
3271 chain = getEffectChain_l(track->sessionId());
3272 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003273 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003274 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 }
3276 }
3277 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003278 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 }
3280 }
3281 }
3282
3283 // mix buffer must be cleared if all tracks are connected to an
3284 // effect chain as in this case the mixer will not write to
3285 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003286 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3287 // FIXME as a performance optimization, should remember previous zero status
3288 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 }
3290
Glenn Kasten58912562012-04-03 10:45:00 -07003291 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003292 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003293 if (fastTracks > 0) {
3294 mixerStatus = MIXER_TRACKS_READY;
3295 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 return mixerStatus;
3297}
3298
Glenn Kasten66fcab92012-02-24 14:59:21 -08003299/*
3300The derived values that are cached:
3301 - mixBufferSize from frame count * frame size
3302 - activeSleepTime from activeSleepTimeUs()
3303 - idleSleepTime from idleSleepTimeUs()
3304 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3305 - maxPeriod from frame count and sample rate (MIXER only)
3306
3307The parameters that affect these derived values are:
3308 - frame count
3309 - frame size
3310 - sample rate
3311 - device type: A2DP or not
3312 - device latency
3313 - format: PCM or not
3314 - active sleep time
3315 - idle sleep time
3316*/
3317
3318void AudioFlinger::PlaybackThread::cacheParameters_l()
3319{
Glenn Kasten58912562012-04-03 10:45:00 -07003320 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003321 activeSleepTime = activeSleepTimeUs();
3322 idleSleepTime = idleSleepTimeUs();
3323}
3324
Eric Laurent22167852012-06-20 12:26:32 -07003325void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326{
Steve Block3856b092011-10-20 11:56:00 +01003327 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003328 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003330
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 size_t size = mTracks.size();
3332 for (size_t i = 0; i < size; i++) {
3333 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003334 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003335 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 }
3338 }
3339}
3340
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003342int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003344 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345}
3346
3347// deleteTrackName_l() must be called with ThreadBase::mLock held
3348void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3349{
Steve Block3856b092011-10-20 11:56:00 +01003350 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 mAudioMixer->deleteTrackName(name);
3352}
3353
3354// checkForNewParameters_l() must be called with ThreadBase::mLock held
3355bool AudioFlinger::MixerThread::checkForNewParameters_l()
3356{
Glenn Kasten58912562012-04-03 10:45:00 -07003357 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3358 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 bool reconfig = false;
3360
3361 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003362
3363 if (mFastMixer != NULL) {
3364 FastMixerStateQueue *sq = mFastMixer->sq();
3365 FastMixerState *state = sq->begin();
3366 if (!(state->mCommand & FastMixerState::IDLE)) {
3367 previousCommand = state->mCommand;
3368 state->mCommand = FastMixerState::HOT_IDLE;
3369 sq->end();
3370 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3371 } else {
3372 sq->end(false /*didModify*/);
3373 }
3374 }
3375
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 status_t status = NO_ERROR;
3377 String8 keyValuePair = mNewParameters[0];
3378 AudioParameter param = AudioParameter(keyValuePair);
3379 int value;
3380
3381 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3382 reconfig = true;
3383 }
3384 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003385 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 status = BAD_VALUE;
3387 } else {
3388 reconfig = true;
3389 }
3390 }
3391 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003392 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 status = BAD_VALUE;
3394 } else {
3395 reconfig = true;
3396 }
3397 }
3398 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3399 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003400 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 // if frame count is changed after track creation
3402 if (!mTracks.isEmpty()) {
3403 status = INVALID_OPERATION;
3404 } else {
3405 reconfig = true;
3406 }
3407 }
3408 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003409#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003410 // when changing the audio output device, call addBatteryData to notify
3411 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003412 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003413 uint32_t params = 0;
3414 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003415 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003416 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3417 }
3418
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003419 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003420 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003421 // check if any other device (except speaker) is on
3422 if (value & deviceWithoutSpeaker ) {
3423 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3424 }
3425
3426 if (params != 0) {
3427 addBatteryData(params);
3428 }
3429 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003430#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003431
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432 // forward device change to effects that have requested to be
3433 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003434 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003436 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 }
3438 }
3439
3440 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003441 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003442 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003444 mOutput->stream->common.standby(&mOutput->stream->common);
3445 mStandby = true;
3446 mBytesWritten = 0;
3447 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003448 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 }
3450 if (status == NO_ERROR && reconfig) {
3451 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003452 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3453 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003455 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003457 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 if (name < 0) break;
3459 mTracks[i]->mName = name;
3460 // limit track sample rate to 2 x new output sample rate
3461 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3462 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3463 }
3464 }
3465 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3466 }
3467 }
3468
3469 mNewParameters.removeAt(0);
3470
3471 mParamStatus = status;
3472 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003473 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3474 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003475 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
Glenn Kasten58912562012-04-03 10:45:00 -07003477
3478 if (!(previousCommand & FastMixerState::IDLE)) {
3479 ALOG_ASSERT(mFastMixer != NULL);
3480 FastMixerStateQueue *sq = mFastMixer->sq();
3481 FastMixerState *state = sq->begin();
3482 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3483 state->mCommand = previousCommand;
3484 sq->end();
3485 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3486 }
3487
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 return reconfig;
3489}
3490
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003491void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492{
3493 const size_t SIZE = 256;
3494 char buffer[SIZE];
3495 String8 result;
3496
3497 PlaybackThread::dumpInternals(fd, args);
3498
3499 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3500 result.append(buffer);
3501 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003502
3503 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3504 FastMixerDumpState copy = mFastMixerDumpState;
3505 copy.dump(fd);
3506
Glenn Kasten39993082012-05-31 13:40:27 -07003507#ifdef STATE_QUEUE_DUMP
3508 // Similar for state queue
3509 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3510 observerCopy.dump(fd);
3511 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3512 mutatorCopy.dump(fd);
3513#endif
3514
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003515 // Write the tee output to a .wav file
3516 NBAIO_Source *teeSource = mTeeSource.get();
3517 if (teeSource != NULL) {
3518 char teePath[64];
3519 struct timeval tv;
3520 gettimeofday(&tv, NULL);
3521 struct tm tm;
3522 localtime_r(&tv.tv_sec, &tm);
3523 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3524 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3525 if (teeFd >= 0) {
3526 char wavHeader[44];
3527 memcpy(wavHeader,
3528 "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",
3529 sizeof(wavHeader));
3530 NBAIO_Format format = teeSource->format();
3531 unsigned channelCount = Format_channelCount(format);
3532 ALOG_ASSERT(channelCount <= FCC_2);
3533 unsigned sampleRate = Format_sampleRate(format);
3534 wavHeader[22] = channelCount; // number of channels
3535 wavHeader[24] = sampleRate; // sample rate
3536 wavHeader[25] = sampleRate >> 8;
3537 wavHeader[32] = channelCount * 2; // block alignment
3538 write(teeFd, wavHeader, sizeof(wavHeader));
3539 size_t total = 0;
3540 bool firstRead = true;
3541 for (;;) {
3542#define TEE_SINK_READ 1024
3543 short buffer[TEE_SINK_READ * FCC_2];
3544 size_t count = TEE_SINK_READ;
3545 ssize_t actual = teeSource->read(buffer, count);
3546 bool wasFirstRead = firstRead;
3547 firstRead = false;
3548 if (actual <= 0) {
3549 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3550 continue;
3551 }
3552 break;
3553 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003554 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003555 write(teeFd, buffer, actual * channelCount * sizeof(short));
3556 total += actual;
3557 }
3558 lseek(teeFd, (off_t) 4, SEEK_SET);
3559 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3560 write(teeFd, &temp, sizeof(temp));
3561 lseek(teeFd, (off_t) 40, SEEK_SET);
3562 temp = total * channelCount * sizeof(short);
3563 write(teeFd, &temp, sizeof(temp));
3564 close(teeFd);
3565 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3566 } else {
3567 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3568 }
3569 }
3570
Glenn Kastenc15d6652012-05-30 14:52:57 -07003571 if (mAudioWatchdog != 0) {
3572 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3573 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3574 wdCopy.dump(fd);
3575 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576}
3577
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003578uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579{
Glenn Kasten58912562012-04-03 10:45:00 -07003580 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581}
3582
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003583uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003584{
Glenn Kasten58912562012-04-03 10:45:00 -07003585 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003586}
3587
Glenn Kasten66fcab92012-02-24 14:59:21 -08003588void AudioFlinger::MixerThread::cacheParameters_l()
3589{
3590 PlaybackThread::cacheParameters_l();
3591
3592 // FIXME: Relaxed timing because of a certain device that can't meet latency
3593 // Should be reduced to 2x after the vendor fixes the driver issue
3594 // increase threshold again due to low power audio mode. The way this warning
3595 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003596 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003597}
3598
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003600AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003601 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003602 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003603 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605}
3606
3607AudioFlinger::DirectOutputThread::~DirectOutputThread()
3608{
3609}
3610
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003611AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3612 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003613)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003615 sp<Track> trackToRemove;
3616
Glenn Kastenfec279f2012-03-08 07:47:15 -08003617 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618
Glenn Kasten952eeb22012-03-06 11:30:57 -08003619 // find out which tracks need to be processed
3620 if (mActiveTracks.size() != 0) {
3621 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003622 // The track died recently
3623 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624
Glenn Kasten952eeb22012-03-06 11:30:57 -08003625 Track* const track = t.get();
3626 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627
Glenn Kasten952eeb22012-03-06 11:30:57 -08003628 // The first time a track is added we wait
3629 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003630 uint32_t minFrames;
3631 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3632 minFrames = mNormalFrameCount;
3633 } else {
3634 minFrames = 1;
3635 }
3636 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003637 !track->isPaused() && !track->isTerminated())
3638 {
3639 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640
Glenn Kasten952eeb22012-03-06 11:30:57 -08003641 if (track->mFillingUpStatus == Track::FS_FILLED) {
3642 track->mFillingUpStatus = Track::FS_ACTIVE;
3643 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003644 if (track->mState == TrackBase::RESUMING) {
3645 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003646 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003647 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003648
Glenn Kasten952eeb22012-03-06 11:30:57 -08003649 // compute volume for this track
3650 float left, right;
3651 if (track->isMuted() || mMasterMute || track->isPausing() ||
3652 mStreamTypes[track->streamType()].mute) {
3653 left = right = 0;
3654 if (track->isPausing()) {
3655 track->setPaused();
3656 }
3657 } else {
3658 float typeVolume = mStreamTypes[track->streamType()].volume;
3659 float v = mMasterVolume * typeVolume;
3660 uint32_t vlr = cblk->getVolumeLR();
3661 float v_clamped = v * (vlr & 0xFFFF);
3662 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3663 left = v_clamped/MAX_GAIN;
3664 v_clamped = v * (vlr >> 16);
3665 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3666 right = v_clamped/MAX_GAIN;
3667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668
Glenn Kasten952eeb22012-03-06 11:30:57 -08003669 if (left != mLeftVolFloat || right != mRightVolFloat) {
3670 mLeftVolFloat = left;
3671 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672
Glenn Kasten952eeb22012-03-06 11:30:57 -08003673 // Convert volumes from float to 8.24
3674 uint32_t vl = (uint32_t)(left * (1 << 24));
3675 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676
Glenn Kasten952eeb22012-03-06 11:30:57 -08003677 // Delegate volume control to effect in track effect chain if needed
3678 // only one effect chain can be present on DirectOutputThread, so if
3679 // there is one, the track is connected to it
3680 if (!mEffectChains.isEmpty()) {
3681 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003682 mEffectChains[0]->setVolume_l(&vl, &vr);
3683 left = (float)vl / (1 << 24);
3684 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003685 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003686 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 }
3688
3689 // reset retry count
3690 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003691 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003692 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003693 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003694 // clear effect chain input buffer if an active track underruns to avoid sending
3695 // previous audio buffer again to effects
3696 if (!mEffectChains.isEmpty()) {
3697 mEffectChains[0]->clearInputBuffer();
3698 }
3699
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003701 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3702 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 // We have consumed all the buffers of this track.
3704 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003705 // TODO: implement behavior for compressed audio
3706 size_t audioHALFrames =
3707 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3708 size_t framesWritten =
3709 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3710 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003711 if (track->isStopped()) {
3712 track->reset();
3713 }
Eric Laurenta011e352012-03-29 15:51:43 -07003714 trackToRemove = track;
3715 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 } else {
3717 // No buffers for this track. Give it a few chances to
3718 // fill a buffer, then remove it from active list.
3719 if (--(track->mRetryCount) <= 0) {
3720 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3721 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003723 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 }
3725 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 }
3727 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003729 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 // remove all the tracks that need to be...
3731 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003732 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003733 mActiveTracks.remove(trackToRemove);
3734 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003735 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003736 trackToRemove->sessionId());
3737 mEffectChains[0]->decActiveTrackCnt();
3738 }
3739 if (trackToRemove->isTerminated()) {
3740 removeTrack_l(trackToRemove);
3741 }
3742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743
Glenn Kastenfec279f2012-03-08 07:47:15 -08003744 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003745}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746
Glenn Kasten000f0e32012-03-01 17:10:56 -08003747void AudioFlinger::DirectOutputThread::threadLoop_mix()
3748{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 AudioBufferProvider::Buffer buffer;
3750 size_t frameCount = mFrameCount;
3751 int8_t *curBuf = (int8_t *)mMixBuffer;
3752 // output audio to hardware
3753 while (frameCount) {
3754 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003755 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003756 if (CC_UNLIKELY(buffer.raw == NULL)) {
3757 memset(curBuf, 0, frameCount * mFrameSize);
3758 break;
3759 }
3760 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3761 frameCount -= buffer.frameCount;
3762 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003763 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003764 }
3765 sleepTime = 0;
3766 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003767 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003768
Glenn Kasten000f0e32012-03-01 17:10:56 -08003769}
3770
3771void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3772{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003774 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 sleepTime = activeSleepTime;
3776 } else {
3777 sleepTime = idleSleepTime;
3778 }
3779 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003780 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 sleepTime = 0;
3782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783}
3784
3785// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003786int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787{
3788 return 0;
3789}
3790
3791// deleteTrackName_l() must be called with ThreadBase::mLock held
3792void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3793{
3794}
3795
3796// checkForNewParameters_l() must be called with ThreadBase::mLock held
3797bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3798{
3799 bool reconfig = false;
3800
3801 while (!mNewParameters.isEmpty()) {
3802 status_t status = NO_ERROR;
3803 String8 keyValuePair = mNewParameters[0];
3804 AudioParameter param = AudioParameter(keyValuePair);
3805 int value;
3806
3807 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3808 // do not accept frame count changes if tracks are open as the track buffer
3809 // size depends on frame count and correct behavior would not be garantied
3810 // if frame count is changed after track creation
3811 if (!mTracks.isEmpty()) {
3812 status = INVALID_OPERATION;
3813 } else {
3814 reconfig = true;
3815 }
3816 }
3817 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003818 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003819 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003821 mOutput->stream->common.standby(&mOutput->stream->common);
3822 mStandby = true;
3823 mBytesWritten = 0;
3824 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003825 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 }
3827 if (status == NO_ERROR && reconfig) {
3828 readOutputParameters();
3829 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3830 }
3831 }
3832
3833 mNewParameters.removeAt(0);
3834
3835 mParamStatus = status;
3836 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003837 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3838 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003839 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 }
3841 return reconfig;
3842}
3843
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003844uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003845{
3846 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003847 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003848 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003849 } else {
3850 time = 10000;
3851 }
3852 return time;
3853}
3854
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003855uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856{
3857 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003858 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003859 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860 } else {
3861 time = 10000;
3862 }
3863 return time;
3864}
3865
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003866uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003867{
3868 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003869 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003870 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3871 } else {
3872 time = 10000;
3873 }
3874 return time;
3875}
3876
Glenn Kasten66fcab92012-02-24 14:59:21 -08003877void AudioFlinger::DirectOutputThread::cacheParameters_l()
3878{
3879 PlaybackThread::cacheParameters_l();
3880
3881 // use shorter standby delay as on normal output to release
3882 // hardware resources as soon as possible
3883 standbyDelay = microseconds(activeSleepTime*2);
3884}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003885
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886// ----------------------------------------------------------------------------
3887
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003888AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003889 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003890 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3891 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 addOutputTrack(mainThread);
3894}
3895
3896AudioFlinger::DuplicatingThread::~DuplicatingThread()
3897{
3898 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3899 mOutputTracks[i]->destroy();
3900 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003901}
3902
Glenn Kasten000f0e32012-03-01 17:10:56 -08003903void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003905 // mix buffers...
3906 if (outputsReady(outputTracks)) {
3907 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3908 } else {
3909 memset(mMixBuffer, 0, mixBufferSize);
3910 }
3911 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003912 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003913 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003914}
3915
3916void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3917{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003918 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003919 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003920 sleepTime = activeSleepTime;
3921 } else {
3922 sleepTime = idleSleepTime;
3923 }
3924 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003925 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3926 writeFrames = mNormalFrameCount;
3927 memset(mMixBuffer, 0, mixBufferSize);
3928 } else {
3929 // flush remaining overflow buffers in output tracks
3930 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003931 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003932 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003933 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003934}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935
Glenn Kasten000f0e32012-03-01 17:10:56 -08003936void AudioFlinger::DuplicatingThread::threadLoop_write()
3937{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003938 for (size_t i = 0; i < outputTracks.size(); i++) {
3939 outputTracks[i]->write(mMixBuffer, writeFrames);
3940 }
3941 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003942}
Glenn Kasten688a6402012-02-29 07:57:06 -08003943
Glenn Kasten000f0e32012-03-01 17:10:56 -08003944void AudioFlinger::DuplicatingThread::threadLoop_standby()
3945{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003946 // DuplicatingThread implements standby by stopping all tracks
3947 for (size_t i = 0; i < outputTracks.size(); i++) {
3948 outputTracks[i]->stop();
3949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950}
3951
Glenn Kastenfa26a852012-03-06 11:28:04 -08003952void AudioFlinger::DuplicatingThread::saveOutputTracks()
3953{
3954 outputTracks = mOutputTracks;
3955}
3956
3957void AudioFlinger::DuplicatingThread::clearOutputTracks()
3958{
3959 outputTracks.clear();
3960}
3961
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3963{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003964 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003965 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003966 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003967 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 this,
3969 mSampleRate,
3970 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003971 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 frameCount);
3973 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003974 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003976 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003977 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 }
3979}
3980
3981void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3982{
3983 Mutex::Autolock _l(mLock);
3984 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003985 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 mOutputTracks[i]->destroy();
3987 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003988 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 return;
3990 }
3991 }
Steve Block3856b092011-10-20 11:56:00 +01003992 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993}
3994
Glenn Kasten438b0362012-03-06 11:24:48 -08003995// caller must hold mLock
3996void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997{
3998 mWaitTimeMs = UINT_MAX;
3999 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4000 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004001 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4003 if (waitTimeMs < mWaitTimeMs) {
4004 mWaitTimeMs = waitTimeMs;
4005 }
4006 }
4007 }
4008}
4009
4010
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004011bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012{
4013 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004014 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004016 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 return false;
4018 }
4019 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004020 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004022 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023 return false;
4024 }
4025 }
4026 return true;
4027}
4028
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004029uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030{
4031 return (mWaitTimeMs * 1000) / 2;
4032}
4033
Glenn Kasten66fcab92012-02-24 14:59:21 -08004034void AudioFlinger::DuplicatingThread::cacheParameters_l()
4035{
4036 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4037 updateWaitTime_l();
4038
4039 MixerThread::cacheParameters_l();
4040}
4041
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042// ----------------------------------------------------------------------------
4043
4044// TrackBase constructor must be called with AudioFlinger::mLock held
4045AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004046 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 const sp<Client>& client,
4048 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004049 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004050 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052 const sp<IMemory>& sharedBuffer,
4053 int sessionId)
4054 : RefBase(),
4055 mThread(thread),
4056 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004057 mCblk(NULL),
4058 // mBuffer
4059 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 mFrameCount(0),
4061 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004062 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004064 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004066 // mChannelCount
4067 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068{
Steve Block3856b092011-10-20 11:56:00 +01004069 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070
Steve Blockb8a80522011-12-20 16:23:08 +00004071 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004072 size_t size = sizeof(audio_track_cblk_t);
4073 uint8_t channelCount = popcount(channelMask);
4074 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4075 if (sharedBuffer == 0) {
4076 size += bufferSize;
4077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004079 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 mCblkMemory = client->heap()->allocate(size);
4081 if (mCblkMemory != 0) {
4082 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004083 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084 new(mCblk) audio_track_cblk_t();
4085 // clear all buffers
4086 mCblk->frameCount = frameCount;
4087 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004088// uncomment the following lines to quickly test 32-bit wraparound
4089// mCblk->user = 0xffff0000;
4090// mCblk->server = 0xffff0000;
4091// mCblk->userBase = 0xffff0000;
4092// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004093 mChannelCount = channelCount;
4094 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 if (sharedBuffer == 0) {
4096 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4097 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4098 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004099 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 mCblk->flags = CBLK_UNDERRUN_ON;
4101 } else {
4102 mBuffer = sharedBuffer->pointer();
4103 }
4104 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4105 }
4106 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004107 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 client->heap()->dump("AudioTrack");
4109 return;
4110 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004111 } else {
4112 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004113 // construct the shared structure in-place.
4114 new(mCblk) audio_track_cblk_t();
4115 // clear all buffers
4116 mCblk->frameCount = frameCount;
4117 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004118// uncomment the following lines to quickly test 32-bit wraparound
4119// mCblk->user = 0xffff0000;
4120// mCblk->server = 0xffff0000;
4121// mCblk->userBase = 0xffff0000;
4122// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004123 mChannelCount = channelCount;
4124 mChannelMask = channelMask;
4125 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4126 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4127 // Force underrun condition to avoid false underrun callback until first data is
4128 // written to buffer (other flags are cleared)
4129 mCblk->flags = CBLK_UNDERRUN_ON;
4130 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132}
4133
4134AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4135{
Glenn Kastena0d68332012-01-27 16:47:15 -08004136 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004137 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004139 } else {
4140 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141 }
4142 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004143 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004144 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004145 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004147 // If the client's reference count drops to zero, the associated destructor
4148 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4149 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 mClient.clear();
4151 }
4152}
4153
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004154// AudioBufferProvider interface
4155// getNextBuffer() = 0;
4156// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4158{
Glenn Kastene0feee32011-12-13 11:53:26 -08004159 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004161 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004162 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 buffer->frameCount = 0;
4164}
4165
4166bool AudioFlinger::ThreadBase::TrackBase::step() {
4167 bool result;
4168 audio_track_cblk_t* cblk = this->cblk();
4169
4170 result = cblk->stepServer(mFrameCount);
4171 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004172 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004173 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 }
4175 return result;
4176}
4177
4178void AudioFlinger::ThreadBase::TrackBase::reset() {
4179 audio_track_cblk_t* cblk = this->cblk();
4180
4181 cblk->user = 0;
4182 cblk->server = 0;
4183 cblk->userBase = 0;
4184 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004185 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004186 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187}
4188
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4190 return (int)mCblk->sampleRate;
4191}
4192
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4194 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004195 size_t frameSize = cblk->frameSize;
4196 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4197 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198
4199 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004200 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4201 "TrackBase::getBuffer buffer out of range:\n"
4202 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4203 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004205 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206
4207 return bufferStart;
4208}
4209
Eric Laurenta011e352012-03-29 15:51:43 -07004210status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4211{
4212 mSyncEvents.add(event);
4213 return NO_ERROR;
4214}
4215
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216// ----------------------------------------------------------------------------
4217
4218// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4219AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004220 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004222 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004224 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004225 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 int frameCount,
4227 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004228 int sessionId,
4229 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004230 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004231 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004232 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004233 // mRetryCount initialized later when needed
4234 mSharedBuffer(sharedBuffer),
4235 mStreamType(streamType),
4236 mName(-1), // see note below
4237 mMainBuffer(thread->mixBuffer()),
4238 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004239 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004240 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004241 mFlags(flags),
4242 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004243 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004244 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245{
4246 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4248 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004249 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004250 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004251 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004252 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004253 if (mName < 0) {
4254 ALOGE("no more track names available");
4255 return;
4256 }
4257 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004258 if (flags & IAudioFlinger::TRACK_FAST) {
4259 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4260 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4261 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004262 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004263 // FIXME This is too eager. We allocate a fast track index before the
4264 // fast track becomes active. Since fast tracks are a scarce resource,
4265 // this means we are potentially denying other more important fast tracks from
4266 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004267 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004268 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004269 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004270 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004271 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004274 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275}
4276
4277AudioFlinger::PlaybackThread::Track::~Track()
4278{
Steve Block3856b092011-10-20 11:56:00 +01004279 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 sp<ThreadBase> thread = mThread.promote();
4281 if (thread != 0) {
4282 Mutex::Autolock _l(thread->mLock);
4283 mState = TERMINATED;
4284 }
4285}
4286
4287void AudioFlinger::PlaybackThread::Track::destroy()
4288{
4289 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4290 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004291 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 // we must acquire a strong reference on this Track before locking mLock
4293 // here so that the destructor is called only when exiting this function.
4294 // On the other hand, as long as Track::destroy() is only called by
4295 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4296 // this Track with its member mTrack.
4297 sp<Track> keep(this);
4298 { // scope for mLock
4299 sp<ThreadBase> thread = mThread.promote();
4300 if (thread != 0) {
4301 if (!isOutputTrack()) {
4302 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004303 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004304
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004305#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004306 // to track the speaker usage
4307 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004308#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 }
4310 AudioSystem::releaseOutput(thread->id());
4311 }
4312 Mutex::Autolock _l(thread->mLock);
4313 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4314 playbackThread->destroyTrack_l(this);
4315 }
4316 }
4317}
4318
Glenn Kasten288ed212012-04-25 17:52:27 -07004319/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4320{
Glenn Kastene213c862012-04-25 13:46:15 -07004321 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 -07004322 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004323}
4324
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4326{
Glenn Kasten83d86532012-01-17 14:39:34 -08004327 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004328 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004329 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004330 } else {
4331 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4332 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004333 track_state state = mState;
4334 char stateChar;
4335 switch (state) {
4336 case IDLE:
4337 stateChar = 'I';
4338 break;
4339 case TERMINATED:
4340 stateChar = 'T';
4341 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004342 case STOPPING_1:
4343 stateChar = 's';
4344 break;
4345 case STOPPING_2:
4346 stateChar = '5';
4347 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004348 case STOPPED:
4349 stateChar = 'S';
4350 break;
4351 case RESUMING:
4352 stateChar = 'R';
4353 break;
4354 case ACTIVE:
4355 stateChar = 'A';
4356 break;
4357 case PAUSING:
4358 stateChar = 'p';
4359 break;
4360 case PAUSED:
4361 stateChar = 'P';
4362 break;
Eric Laurent29864602012-05-08 18:57:51 -07004363 case FLUSHED:
4364 stateChar = 'F';
4365 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004366 default:
4367 stateChar = '?';
4368 break;
4369 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004370 char nowInUnderrun;
4371 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4372 case UNDERRUN_FULL:
4373 nowInUnderrun = ' ';
4374 break;
4375 case UNDERRUN_PARTIAL:
4376 nowInUnderrun = '<';
4377 break;
4378 case UNDERRUN_EMPTY:
4379 nowInUnderrun = '*';
4380 break;
4381 default:
4382 nowInUnderrun = '?';
4383 break;
4384 }
Glenn Kastene213c862012-04-25 13:46:15 -07004385 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4386 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004387 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 mStreamType,
4389 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004390 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 mSessionId,
4392 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004393 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004394 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 mMute,
4396 mFillingUpStatus,
4397 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004398 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4399 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 mCblk->server,
4401 mCblk->user,
4402 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004403 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004404 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004405 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004406 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407}
4408
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004409// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004410status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004411 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004413 audio_track_cblk_t* cblk = this->cblk();
4414 uint32_t framesReady;
4415 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004417 // Check if last stepServer failed, try to step now
4418 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004419 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4420 // Since the fast mixer is higher priority than client callback thread,
4421 // it does not result in priority inversion for client.
4422 // But a non-blocking solution would be preferable to avoid
4423 // fast mixer being unable to tryLock(), and
4424 // to avoid the extra context switches if the client wakes up,
4425 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004426 if (!step()) goto getNextBuffer_exit;
4427 ALOGV("stepServer recovered");
4428 mStepServerFailed = false;
4429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430
Glenn Kasten288ed212012-04-25 17:52:27 -07004431 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004432 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004434 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 uint32_t s = cblk->server;
4436 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4437
4438 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4439 if (framesReq > framesReady) {
4440 framesReq = framesReady;
4441 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004442 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 framesReq = bufferEnd - s;
4444 }
4445
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004446 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004449 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450
4451getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004452 buffer->raw = NULL;
4453 buffer->frameCount = 0;
4454 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4455 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004456}
4457
Glenn Kasten288ed212012-04-25 17:52:27 -07004458// Note that framesReady() takes a mutex on the control block using tryLock().
4459// This could result in priority inversion if framesReady() is called by the normal mixer,
4460// as the normal mixer thread runs at lower
4461// priority than the client's callback thread: there is a short window within framesReady()
4462// during which the normal mixer could be preempted, and the client callback would block.
4463// Another problem can occur if framesReady() is called by the fast mixer:
4464// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4465// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4466size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004467 return mCblk->framesReady();
4468}
4469
Glenn Kasten288ed212012-04-25 17:52:27 -07004470// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004472 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004473
John Grossman4ff14ba2012-02-08 16:37:41 -08004474 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4476 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004477 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 return true;
4479 }
4480 return false;
4481}
4482
Glenn Kasten3acbd052012-02-28 10:39:56 -08004483status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004484 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485{
4486 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004487 ALOGV("start(%d), calling pid %d session %d",
4488 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004489
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 sp<ThreadBase> thread = mThread.promote();
4491 if (thread != 0) {
4492 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004493 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 // here the track could be either new, or restarted
4495 // in both cases "unstop" the track
4496 if (mState == PAUSED) {
4497 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004498 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499 } else {
4500 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004501 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 }
4503
4504 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4505 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004506 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004508
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004509#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004510 // to track the speaker usage
4511 if (status == NO_ERROR) {
4512 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4513 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004514#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 }
4516 if (status == NO_ERROR) {
4517 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4518 playbackThread->addTrack_l(this);
4519 } else {
4520 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004521 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 }
4523 } else {
4524 status = BAD_VALUE;
4525 }
4526 return status;
4527}
4528
4529void AudioFlinger::PlaybackThread::Track::stop()
4530{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004531 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 sp<ThreadBase> thread = mThread.promote();
4533 if (thread != 0) {
4534 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004535 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004536 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 // If the track is not active (PAUSED and buffers full), flush buffers
4538 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4539 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4540 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004541 mState = STOPPED;
4542 } else if (!isFastTrack()) {
4543 mState = STOPPED;
4544 } else {
4545 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4546 // and then to STOPPED and reset() when presentation is complete
4547 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004549 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 }
4551 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4552 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004553 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004555
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004556#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004557 // to track the speaker usage
4558 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004559#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
4561 }
4562}
4563
4564void AudioFlinger::PlaybackThread::Track::pause()
4565{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004566 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 sp<ThreadBase> thread = mThread.promote();
4568 if (thread != 0) {
4569 Mutex::Autolock _l(thread->mLock);
4570 if (mState == ACTIVE || mState == RESUMING) {
4571 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004572 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 if (!isOutputTrack()) {
4574 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004575 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004577
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004578#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004579 // to track the speaker usage
4580 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004581#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 }
4583 }
4584 }
4585}
4586
4587void AudioFlinger::PlaybackThread::Track::flush()
4588{
Steve Block3856b092011-10-20 11:56:00 +01004589 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 sp<ThreadBase> thread = mThread.promote();
4591 if (thread != 0) {
4592 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004593 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4594 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 return;
4596 }
4597 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004598 // FLUSHED state
4599 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004600 // do not reset the track if it is still in the process of being stopped or paused.
4601 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004602 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004603 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004604 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4605 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4606 reset();
4607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 }
4609}
4610
4611void AudioFlinger::PlaybackThread::Track::reset()
4612{
4613 // Do not reset twice to avoid discarding data written just after a flush and before
4614 // the audioflinger thread detects the track is stopped.
4615 if (!mResetDone) {
4616 TrackBase::reset();
4617 // Force underrun condition to avoid false underrun callback until first data is
4618 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004619 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4620 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 mFillingUpStatus = FS_FILLING;
4622 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004623 if (mState == FLUSHED) {
4624 mState = IDLE;
4625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 }
4627}
4628
4629void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4630{
4631 mMute = muted;
4632}
4633
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4635{
4636 status_t status = DEAD_OBJECT;
4637 sp<ThreadBase> thread = mThread.promote();
4638 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004639 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004640 sp<AudioFlinger> af = mClient->audioFlinger();
4641
4642 Mutex::Autolock _l(af->mLock);
4643
4644 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004645
Eric Laurent109347d2012-07-02 12:31:03 -07004646 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004647 Mutex::Autolock _dl(playbackThread->mLock);
4648 Mutex::Autolock _sl(srcThread->mLock);
4649 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4650 if (chain == 0) {
4651 return INVALID_OPERATION;
4652 }
4653
4654 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4655 if (effect == 0) {
4656 return INVALID_OPERATION;
4657 }
4658 srcThread->removeEffect_l(effect);
4659 playbackThread->addEffect_l(effect);
4660 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4661 if (effect->state() == EffectModule::ACTIVE ||
4662 effect->state() == EffectModule::STOPPING) {
4663 effect->start();
4664 }
4665
4666 sp<EffectChain> dstChain = effect->chain().promote();
4667 if (dstChain == 0) {
4668 srcThread->addEffect_l(effect);
4669 return INVALID_OPERATION;
4670 }
4671 AudioSystem::unregisterEffect(effect->id());
4672 AudioSystem::registerEffect(&effect->desc(),
4673 srcThread->id(),
4674 dstChain->strategy(),
4675 AUDIO_SESSION_OUTPUT_MIX,
4676 effect->id());
4677 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004678 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 }
4680 return status;
4681}
4682
4683void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4684{
4685 mAuxEffectId = EffectId;
4686 mAuxBuffer = buffer;
4687}
4688
Eric Laurenta011e352012-03-29 15:51:43 -07004689bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4690 size_t audioHalFrames)
4691{
4692 // a track is considered presented when the total number of frames written to audio HAL
4693 // corresponds to the number of frames written when presentationComplete() is called for the
4694 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4695 if (mPresentationCompleteFrames == 0) {
4696 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4697 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4698 mPresentationCompleteFrames, audioHalFrames);
4699 }
4700 if (framesWritten >= mPresentationCompleteFrames) {
4701 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4702 mSessionId, framesWritten);
4703 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004704 return true;
4705 }
4706 return false;
4707}
4708
4709void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4710{
4711 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4712 if (mSyncEvents[i]->type() == type) {
4713 mSyncEvents[i]->trigger();
4714 mSyncEvents.removeAt(i);
4715 i--;
4716 }
4717 }
4718}
4719
Glenn Kasten58912562012-04-03 10:45:00 -07004720// implement VolumeBufferProvider interface
4721
4722uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4723{
4724 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4725 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4726 uint32_t vlr = mCblk->getVolumeLR();
4727 uint32_t vl = vlr & 0xFFFF;
4728 uint32_t vr = vlr >> 16;
4729 // track volumes come from shared memory, so can't be trusted and must be clamped
4730 if (vl > MAX_GAIN_INT) {
4731 vl = MAX_GAIN_INT;
4732 }
4733 if (vr > MAX_GAIN_INT) {
4734 vr = MAX_GAIN_INT;
4735 }
4736 // now apply the cached master volume and stream type volume;
4737 // this is trusted but lacks any synchronization or barrier so may be stale
4738 float v = mCachedVolume;
4739 vl *= v;
4740 vr *= v;
4741 // re-combine into U4.16
4742 vlr = (vr << 16) | (vl & 0xFFFF);
4743 // FIXME look at mute, pause, and stop flags
4744 return vlr;
4745}
Eric Laurenta011e352012-03-29 15:51:43 -07004746
Eric Laurent29864602012-05-08 18:57:51 -07004747status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4748{
4749 if (mState == TERMINATED || mState == PAUSED ||
4750 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4751 (mState == STOPPED)))) {
4752 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4753 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4754 event->cancel();
4755 return INVALID_OPERATION;
4756 }
4757 TrackBase::setSyncEvent(event);
4758 return NO_ERROR;
4759}
4760
John Grossman4ff14ba2012-02-08 16:37:41 -08004761// timed audio tracks
4762
4763sp<AudioFlinger::PlaybackThread::TimedTrack>
4764AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004765 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004766 const sp<Client>& client,
4767 audio_stream_type_t streamType,
4768 uint32_t sampleRate,
4769 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004770 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004771 int frameCount,
4772 const sp<IMemory>& sharedBuffer,
4773 int sessionId) {
4774 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004775 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004776
Glenn Kastena0356762012-03-19 10:38:51 -07004777 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004778 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4779 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004780}
4781
4782AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004783 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004784 const sp<Client>& client,
4785 audio_stream_type_t streamType,
4786 uint32_t sampleRate,
4787 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004788 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004789 int frameCount,
4790 const sp<IMemory>& sharedBuffer,
4791 int sessionId)
4792 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004793 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004794 mQueueHeadInFlight(false),
4795 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004796 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004797 mTimedSilenceBuffer(NULL),
4798 mTimedSilenceBufferSize(0),
4799 mTimedAudioOutputOnTime(false),
4800 mMediaTimeTransformValid(false)
4801{
4802 LocalClock lc;
4803 mLocalTimeFreq = lc.getLocalFreq();
4804
4805 mLocalTimeToSampleTransform.a_zero = 0;
4806 mLocalTimeToSampleTransform.b_zero = 0;
4807 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4808 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4809 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4810 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004811
4812 mMediaTimeToSampleTransform.a_zero = 0;
4813 mMediaTimeToSampleTransform.b_zero = 0;
4814 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4815 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4816 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4817 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004818}
4819
4820AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4821 mClient->releaseTimedTrack();
4822 delete [] mTimedSilenceBuffer;
4823}
4824
4825status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4826 size_t size, sp<IMemory>* buffer) {
4827
4828 Mutex::Autolock _l(mTimedBufferQueueLock);
4829
4830 trimTimedBufferQueue_l();
4831
4832 // lazily initialize the shared memory heap for timed buffers
4833 if (mTimedMemoryDealer == NULL) {
4834 const int kTimedBufferHeapSize = 512 << 10;
4835
4836 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4837 "AudioFlingerTimed");
4838 if (mTimedMemoryDealer == NULL)
4839 return NO_MEMORY;
4840 }
4841
4842 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4843 if (newBuffer == NULL) {
4844 newBuffer = mTimedMemoryDealer->allocate(size);
4845 if (newBuffer == NULL)
4846 return NO_MEMORY;
4847 }
4848
4849 *buffer = newBuffer;
4850 return NO_ERROR;
4851}
4852
4853// caller must hold mTimedBufferQueueLock
4854void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4855 int64_t mediaTimeNow;
4856 {
4857 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4858 if (!mMediaTimeTransformValid)
4859 return;
4860
4861 int64_t targetTimeNow;
4862 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4863 ? mCCHelper.getCommonTime(&targetTimeNow)
4864 : mCCHelper.getLocalTime(&targetTimeNow);
4865
4866 if (OK != res)
4867 return;
4868
4869 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4870 &mediaTimeNow)) {
4871 return;
4872 }
4873 }
4874
John Grossman1c345192012-03-27 14:00:17 -07004875 size_t trimEnd;
4876 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004877 int64_t bufEnd;
4878
John Grossmanc95cfbb2012-04-12 11:53:11 -07004879 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4880 // We have a next buffer. Just use its PTS as the PTS of the frame
4881 // following the last frame in this buffer. If the stream is sparse
4882 // (ie, there are deliberate gaps left in the stream which should be
4883 // filled with silence by the TimedAudioTrack), then this can result
4884 // in one extra buffer being left un-trimmed when it could have
4885 // been. In general, this is not typical, and we would rather
4886 // optimized away the TS calculation below for the more common case
4887 // where PTSes are contiguous.
4888 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4889 } else {
4890 // We have no next buffer. Compute the PTS of the frame following
4891 // the last frame in this buffer by computing the duration of of
4892 // this frame in media time units and adding it to the PTS of the
4893 // buffer.
4894 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4895 / mCblk->frameSize;
4896
4897 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4898 &bufEnd)) {
4899 ALOGE("Failed to convert frame count of %lld to media time"
4900 " duration" " (scale factor %d/%u) in %s",
4901 frameCount,
4902 mMediaTimeToSampleTransform.a_to_b_numer,
4903 mMediaTimeToSampleTransform.a_to_b_denom,
4904 __PRETTY_FUNCTION__);
4905 break;
4906 }
4907 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004908 }
John Grossman9fbdee12012-03-26 17:51:46 -07004909
4910 if (bufEnd > mediaTimeNow)
4911 break;
4912
4913 // Is the buffer we want to use in the middle of a mix operation right
4914 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4915 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004916 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004917 mTrimQueueHeadOnRelease = true;
4918 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004919 }
4920
John Grossman9fbdee12012-03-26 17:51:46 -07004921 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004922 if (trimStart < trimEnd) {
4923 // Update the bookkeeping for framesReady()
4924 for (size_t i = trimStart; i < trimEnd; ++i) {
4925 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4926 }
4927
4928 // Now actually remove the buffers from the queue.
4929 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004930 }
4931}
4932
John Grossman1c345192012-03-27 14:00:17 -07004933void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4934 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004935 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4936 "%s called (reason \"%s\"), but timed buffer queue has no"
4937 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004938
4939 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4940 mTimedBufferQueue.removeAt(0);
4941}
4942
4943void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4944 const TimedBuffer& buf,
4945 const char* logTag) {
4946 uint32_t bufBytes = buf.buffer()->size();
4947 uint32_t consumedAlready = buf.position();
4948
Eric Laurentb388e532012-04-14 13:32:48 -07004949 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004950 "Bad bookkeeping while updating frames pending. Timed buffer is"
4951 " only %u bytes long, but claims to have consumed %u"
4952 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004953 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004954
4955 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004956 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4957 "Bad bookkeeping while updating frames pending. Should have at"
4958 " least %u queued frames, but we think we have only %u. (update"
4959 " reason: \"%s\")",
4960 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004961
4962 mFramesPendingInQueue -= bufFrames;
4963}
4964
John Grossman4ff14ba2012-02-08 16:37:41 -08004965status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4966 const sp<IMemory>& buffer, int64_t pts) {
4967
4968 {
4969 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4970 if (!mMediaTimeTransformValid)
4971 return INVALID_OPERATION;
4972 }
4973
4974 Mutex::Autolock _l(mTimedBufferQueueLock);
4975
John Grossman1c345192012-03-27 14:00:17 -07004976 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4977 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004978 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4979
4980 return NO_ERROR;
4981}
4982
4983status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4984 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4985
John Grossman1c345192012-03-27 14:00:17 -07004986 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4987 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4988 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004989
4990 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4991 target == TimedAudioTrack::COMMON_TIME)) {
4992 return BAD_VALUE;
4993 }
4994
4995 Mutex::Autolock lock(mMediaTimeTransformLock);
4996 mMediaTimeTransform = xform;
4997 mMediaTimeTransformTarget = target;
4998 mMediaTimeTransformValid = true;
4999
5000 return NO_ERROR;
5001}
5002
5003#define min(a, b) ((a) < (b) ? (a) : (b))
5004
5005// implementation of getNextBuffer for tracks whose buffers have timestamps
5006status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5007 AudioBufferProvider::Buffer* buffer, int64_t pts)
5008{
5009 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005010 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005011 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005012 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005013 return INVALID_OPERATION;
5014 }
5015
John Grossman4ff14ba2012-02-08 16:37:41 -08005016 Mutex::Autolock _l(mTimedBufferQueueLock);
5017
John Grossman9fbdee12012-03-26 17:51:46 -07005018 ALOG_ASSERT(!mQueueHeadInFlight,
5019 "getNextBuffer called without releaseBuffer!");
5020
John Grossman4ff14ba2012-02-08 16:37:41 -08005021 while (true) {
5022
5023 // if we have no timed buffers, then fail
5024 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005025 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005026 buffer->frameCount = 0;
5027 return NOT_ENOUGH_DATA;
5028 }
5029
5030 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5031
5032 // calculate the PTS of the head of the timed buffer queue expressed in
5033 // local time
5034 int64_t headLocalPTS;
5035 {
5036 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5037
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005038 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005039
5040 if (mMediaTimeTransform.a_to_b_denom == 0) {
5041 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005042 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005043 return NO_ERROR;
5044 }
5045
5046 int64_t transformedPTS;
5047 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5048 &transformedPTS)) {
5049 // the transform failed. this shouldn't happen, but if it does
5050 // then just drop this buffer
5051 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005052 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005053 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005054 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005055 return NO_ERROR;
5056 }
5057
5058 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5059 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5060 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005061 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 buffer->frameCount = 0;
5063 return INVALID_OPERATION;
5064 }
5065 } else {
5066 headLocalPTS = transformedPTS;
5067 }
5068 }
5069
5070 // adjust the head buffer's PTS to reflect the portion of the head buffer
5071 // that has already been consumed
5072 int64_t effectivePTS = headLocalPTS +
5073 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5074
5075 // Calculate the delta in samples between the head of the input buffer
5076 // queue and the start of the next output buffer that will be written.
5077 // If the transformation fails because of over or underflow, it means
5078 // that the sample's position in the output stream is so far out of
5079 // whack that it should just be dropped.
5080 int64_t sampleDelta;
5081 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5082 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005083 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5084 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005085 continue;
5086 }
5087 if (!mLocalTimeToSampleTransform.doForwardTransform(
5088 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005089 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005090 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005091 continue;
5092 }
5093
John Grossman1c345192012-03-27 14:00:17 -07005094 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5095 " sampleDelta=[%d.%08x]",
5096 head.pts(), head.position(), pts,
5097 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5098 + (sampleDelta >> 32)),
5099 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005100
5101 // if the delta between the ideal placement for the next input sample and
5102 // the current output position is within this threshold, then we will
5103 // concatenate the next input samples to the previous output
5104 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005105 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005106
5107 // if this is the first buffer of audio that we're emitting from this track
5108 // then it should be almost exactly on time.
5109 const int64_t kSampleStartupThreshold = 1LL << 32;
5110
5111 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005112 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005113 // the next input is close enough to being on time, so concatenate it
5114 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005115 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005116
John Grossman1c345192012-03-27 14:00:17 -07005117 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5118 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005119 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005120 }
5121
5122 // Looks like our output is not on time. Reset our on timed status.
5123 // Next time we mix samples from our input queue, then should be within
5124 // the StartupThreshold.
5125 mTimedAudioOutputOnTime = false;
5126 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005127 // the gap between the current output position and the proper start of
5128 // the next input sample is too big, so fill it with silence
5129 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5130
John Grossman9fbdee12012-03-26 17:51:46 -07005131 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005132 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5133 return NO_ERROR;
5134 } else {
5135 // the next input sample is late
5136 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5137 size_t onTimeSamplePosition =
5138 head.position() + lateFrames * mCblk->frameSize;
5139
5140 if (onTimeSamplePosition > head.buffer()->size()) {
5141 // all the remaining samples in the head are too late, so
5142 // drop it and move on
5143 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005144 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 continue;
5146 } else {
5147 // skip over the late samples
5148 head.setPosition(onTimeSamplePosition);
5149
5150 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005151 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005152
5153 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5154 return NO_ERROR;
5155 }
5156 }
5157 }
5158}
5159
5160// Yield samples from the timed buffer queue head up to the given output
5161// buffer's capacity.
5162//
5163// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005164void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 AudioBufferProvider::Buffer* buffer) {
5166
5167 const TimedBuffer& head = mTimedBufferQueue[0];
5168
5169 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5170 head.position());
5171
5172 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5173 mCblk->frameSize);
5174 size_t framesRequested = buffer->frameCount;
5175 buffer->frameCount = min(framesLeftInHead, framesRequested);
5176
John Grossman9fbdee12012-03-26 17:51:46 -07005177 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005178 mTimedAudioOutputOnTime = true;
5179}
5180
5181// Yield samples of silence up to the given output buffer's capacity
5182//
5183// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005184void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5186
5187 // lazily allocate a buffer filled with silence
5188 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5189 delete [] mTimedSilenceBuffer;
5190 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5191 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5192 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5193 }
5194
5195 buffer->raw = mTimedSilenceBuffer;
5196 size_t framesRequested = buffer->frameCount;
5197 buffer->frameCount = min(numFrames, framesRequested);
5198
5199 mTimedAudioOutputOnTime = false;
5200}
5201
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005202// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005203void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5204 AudioBufferProvider::Buffer* buffer) {
5205
5206 Mutex::Autolock _l(mTimedBufferQueueLock);
5207
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005208 // If the buffer which was just released is part of the buffer at the head
5209 // of the queue, be sure to update the amt of the buffer which has been
5210 // consumed. If the buffer being returned is not part of the head of the
5211 // queue, its either because the buffer is part of the silence buffer, or
5212 // because the head of the timed queue was trimmed after the mixer called
5213 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005214 if (buffer->raw == mTimedSilenceBuffer) {
5215 ALOG_ASSERT(!mQueueHeadInFlight,
5216 "Queue head in flight during release of silence buffer!");
5217 goto done;
5218 }
5219
5220 ALOG_ASSERT(mQueueHeadInFlight,
5221 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5222 " head in flight.");
5223
5224 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005225 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005226
5227 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005228 void* end = reinterpret_cast<void*>(
5229 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5230 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005231
John Grossman9fbdee12012-03-26 17:51:46 -07005232 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5233 "released buffer not within the head of the timed buffer"
5234 " queue; qHead = [%p, %p], released buffer = %p",
5235 start, end, buffer->raw);
5236
5237 head.setPosition(head.position() +
5238 (buffer->frameCount * mCblk->frameSize));
5239 mQueueHeadInFlight = false;
5240
John Grossman1c345192012-03-27 14:00:17 -07005241 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5242 "Bad bookkeeping during releaseBuffer! Should have at"
5243 " least %u queued frames, but we think we have only %u",
5244 buffer->frameCount, mFramesPendingInQueue);
5245
5246 mFramesPendingInQueue -= buffer->frameCount;
5247
John Grossman9fbdee12012-03-26 17:51:46 -07005248 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5249 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005250 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005251 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005252 }
John Grossman9fbdee12012-03-26 17:51:46 -07005253 } else {
5254 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5255 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005256 }
5257
John Grossman9fbdee12012-03-26 17:51:46 -07005258done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005259 buffer->raw = 0;
5260 buffer->frameCount = 0;
5261}
5262
Glenn Kasten288ed212012-04-25 17:52:27 -07005263size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005264 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005265 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005266}
5267
5268AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5269 : mPTS(0), mPosition(0) {}
5270
5271AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5272 const sp<IMemory>& buffer, int64_t pts)
5273 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5274
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275// ----------------------------------------------------------------------------
5276
5277// RecordTrack constructor must be called with AudioFlinger::mLock held
5278AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005279 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280 const sp<Client>& client,
5281 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005282 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005283 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285 int sessionId)
5286 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005287 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 mOverflow(false)
5289{
5290 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005291 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5292 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5293 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5294 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5295 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5296 } else {
5297 mCblk->frameSize = sizeof(int8_t);
5298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 }
5300}
5301
5302AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5303{
5304 sp<ThreadBase> thread = mThread.promote();
5305 if (thread != 0) {
5306 AudioSystem::releaseInput(thread->id());
5307 }
5308}
5309
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005310// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005311status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312{
5313 audio_track_cblk_t* cblk = this->cblk();
5314 uint32_t framesAvail;
5315 uint32_t framesReq = buffer->frameCount;
5316
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005317 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005318 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005320 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005321 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 }
5323
5324 framesAvail = cblk->framesAvailable_l();
5325
Glenn Kastenf6b16782011-12-15 09:51:17 -08005326 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327 uint32_t s = cblk->server;
5328 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5329
5330 if (framesReq > framesAvail) {
5331 framesReq = framesAvail;
5332 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005333 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 framesReq = bufferEnd - s;
5335 }
5336
5337 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 buffer->frameCount = framesReq;
5339 return NO_ERROR;
5340 }
5341
5342getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005343 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 buffer->frameCount = 0;
5345 return NOT_ENOUGH_DATA;
5346}
5347
Glenn Kasten3acbd052012-02-28 10:39:56 -08005348status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005349 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350{
5351 sp<ThreadBase> thread = mThread.promote();
5352 if (thread != 0) {
5353 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005354 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 } else {
5356 return BAD_VALUE;
5357 }
5358}
5359
5360void AudioFlinger::RecordThread::RecordTrack::stop()
5361{
5362 sp<ThreadBase> thread = mThread.promote();
5363 if (thread != 0) {
5364 RecordThread *recordThread = (RecordThread *)thread.get();
5365 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005366 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005367 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005368 // read from buffer
5369 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 }
5371}
5372
5373void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5374{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005375 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005376 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005378 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 mSessionId,
5380 mFrameCount,
5381 mState,
5382 mCblk->sampleRate,
5383 mCblk->server,
5384 mCblk->user);
5385}
5386
5387
5388// ----------------------------------------------------------------------------
5389
5390AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005391 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 DuplicatingThread *sourceThread,
5393 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005394 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005395 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005397 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5398 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 mActive(false), mSourceThread(sourceThread)
5400{
5401
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 if (mCblk != NULL) {
5403 mCblk->flags |= CBLK_DIRECTION_OUT;
5404 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 mOutBuffer.frameCount = 0;
5406 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005407 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005408 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5409 mCblk, mBuffer, mCblk->buffers,
5410 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005412 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 }
5414}
5415
5416AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5417{
5418 clearBufferQueue();
5419}
5420
Glenn Kasten3acbd052012-02-28 10:39:56 -08005421status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005422 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005424 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 if (status != NO_ERROR) {
5426 return status;
5427 }
5428
5429 mActive = true;
5430 mRetryCount = 127;
5431 return status;
5432}
5433
5434void AudioFlinger::PlaybackThread::OutputTrack::stop()
5435{
5436 Track::stop();
5437 clearBufferQueue();
5438 mOutBuffer.frameCount = 0;
5439 mActive = false;
5440}
5441
5442bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5443{
5444 Buffer *pInBuffer;
5445 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005446 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 bool outputBufferFull = false;
5448 inBuffer.frameCount = frames;
5449 inBuffer.i16 = data;
5450
5451 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5452
5453 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005454 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 sp<ThreadBase> thread = mThread.promote();
5456 if (thread != 0) {
5457 MixerThread *mixerThread = (MixerThread *)thread.get();
5458 if (mCblk->frameCount > frames){
5459 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5460 uint32_t startFrames = (mCblk->frameCount - frames);
5461 pInBuffer = new Buffer;
5462 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5463 pInBuffer->frameCount = startFrames;
5464 pInBuffer->i16 = pInBuffer->mBuffer;
5465 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5466 mBufferQueue.add(pInBuffer);
5467 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 }
5470 }
5471 }
5472 }
5473
5474 while (waitTimeLeftMs) {
5475 // First write pending buffers, then new data
5476 if (mBufferQueue.size()) {
5477 pInBuffer = mBufferQueue.itemAt(0);
5478 } else {
5479 pInBuffer = &inBuffer;
5480 }
5481
5482 if (pInBuffer->frameCount == 0) {
5483 break;
5484 }
5485
5486 if (mOutBuffer.frameCount == 0) {
5487 mOutBuffer.frameCount = pInBuffer->frameCount;
5488 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005489 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005490 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 outputBufferFull = true;
5492 break;
5493 }
5494 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5495 if (waitTimeLeftMs >= waitTimeMs) {
5496 waitTimeLeftMs -= waitTimeMs;
5497 } else {
5498 waitTimeLeftMs = 0;
5499 }
5500 }
5501
5502 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5503 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5504 mCblk->stepUser(outFrames);
5505 pInBuffer->frameCount -= outFrames;
5506 pInBuffer->i16 += outFrames * channelCount;
5507 mOutBuffer.frameCount -= outFrames;
5508 mOutBuffer.i16 += outFrames * channelCount;
5509
5510 if (pInBuffer->frameCount == 0) {
5511 if (mBufferQueue.size()) {
5512 mBufferQueue.removeAt(0);
5513 delete [] pInBuffer->mBuffer;
5514 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005515 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 } else {
5517 break;
5518 }
5519 }
5520 }
5521
5522 // If we could not write all frames, allocate a buffer and queue it for next time.
5523 if (inBuffer.frameCount) {
5524 sp<ThreadBase> thread = mThread.promote();
5525 if (thread != 0 && !thread->standby()) {
5526 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5527 pInBuffer = new Buffer;
5528 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5529 pInBuffer->frameCount = inBuffer.frameCount;
5530 pInBuffer->i16 = pInBuffer->mBuffer;
5531 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5532 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005533 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005535 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 }
5537 }
5538 }
5539
5540 // Calling write() with a 0 length buffer, means that no more data will be written:
5541 // If no more buffers are pending, fill output track buffer to make sure it is started
5542 // by output mixer.
5543 if (frames == 0 && mBufferQueue.size() == 0) {
5544 if (mCblk->user < mCblk->frameCount) {
5545 frames = mCblk->frameCount - mCblk->user;
5546 pInBuffer = new Buffer;
5547 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5548 pInBuffer->frameCount = frames;
5549 pInBuffer->i16 = pInBuffer->mBuffer;
5550 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5551 mBufferQueue.add(pInBuffer);
5552 } else if (mActive) {
5553 stop();
5554 }
5555 }
5556
5557 return outputBufferFull;
5558}
5559
5560status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5561{
5562 int active;
5563 status_t result;
5564 audio_track_cblk_t* cblk = mCblk;
5565 uint32_t framesReq = buffer->frameCount;
5566
Steve Block3856b092011-10-20 11:56:00 +01005567// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 buffer->frameCount = 0;
5569
5570 uint32_t framesAvail = cblk->framesAvailable();
5571
5572
5573 if (framesAvail == 0) {
5574 Mutex::Autolock _l(cblk->lock);
5575 goto start_loop_here;
5576 while (framesAvail == 0) {
5577 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005578 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005579 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005580 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
5582 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5583 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005584 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 }
5586 // read the server count again
5587 start_loop_here:
5588 framesAvail = cblk->framesAvailable_l();
5589 }
5590 }
5591
5592// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005593// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594// }
5595
5596 if (framesReq > framesAvail) {
5597 framesReq = framesAvail;
5598 }
5599
5600 uint32_t u = cblk->user;
5601 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5602
Marco Nelissena1472d92012-03-30 14:36:54 -07005603 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 framesReq = bufferEnd - u;
5605 }
5606
5607 buffer->frameCount = framesReq;
5608 buffer->raw = (void *)cblk->buffer(u);
5609 return NO_ERROR;
5610}
5611
5612
5613void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5614{
5615 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616
5617 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005618 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 delete [] pBuffer->mBuffer;
5620 delete pBuffer;
5621 }
5622 mBufferQueue.clear();
5623}
5624
5625// ----------------------------------------------------------------------------
5626
5627AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5628 : RefBase(),
5629 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005630 // 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 -07005631 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005632 mPid(pid),
5633 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634{
5635 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5636}
5637
5638// Client destructor must be called with AudioFlinger::mLock held
5639AudioFlinger::Client::~Client()
5640{
5641 mAudioFlinger->removeClient_l(mPid);
5642}
5643
Glenn Kasten435dbe62012-01-30 10:15:48 -08005644sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645{
5646 return mMemoryDealer;
5647}
5648
John Grossman4ff14ba2012-02-08 16:37:41 -08005649// Reserve one of the limited slots for a timed audio track associated
5650// with this client
5651bool AudioFlinger::Client::reserveTimedTrack()
5652{
5653 const int kMaxTimedTracksPerClient = 4;
5654
5655 Mutex::Autolock _l(mTimedTrackLock);
5656
5657 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5658 ALOGW("can not create timed track - pid %d has exceeded the limit",
5659 mPid);
5660 return false;
5661 }
5662
5663 mTimedTrackCount++;
5664 return true;
5665}
5666
5667// Release a slot for a timed audio track
5668void AudioFlinger::Client::releaseTimedTrack()
5669{
5670 Mutex::Autolock _l(mTimedTrackLock);
5671 mTimedTrackCount--;
5672}
5673
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674// ----------------------------------------------------------------------------
5675
5676AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5677 const sp<IAudioFlingerClient>& client,
5678 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005679 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680{
5681}
5682
5683AudioFlinger::NotificationClient::~NotificationClient()
5684{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685}
5686
5687void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5688{
5689 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005690 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691}
5692
5693// ----------------------------------------------------------------------------
5694
5695AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5696 : BnAudioTrack(),
5697 mTrack(track)
5698{
5699}
5700
5701AudioFlinger::TrackHandle::~TrackHandle() {
5702 // just stop the track on deletion, associated resources
5703 // will be freed from the main thread once all pending buffers have
5704 // been played. Unless it's not in the active track list, in which
5705 // case we free everything now...
5706 mTrack->destroy();
5707}
5708
Glenn Kasten90716c52012-01-26 13:40:12 -08005709sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5710 return mTrack->getCblk();
5711}
5712
Glenn Kasten3acbd052012-02-28 10:39:56 -08005713status_t AudioFlinger::TrackHandle::start() {
5714 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715}
5716
5717void AudioFlinger::TrackHandle::stop() {
5718 mTrack->stop();
5719}
5720
5721void AudioFlinger::TrackHandle::flush() {
5722 mTrack->flush();
5723}
5724
5725void AudioFlinger::TrackHandle::mute(bool e) {
5726 mTrack->mute(e);
5727}
5728
5729void AudioFlinger::TrackHandle::pause() {
5730 mTrack->pause();
5731}
5732
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5734{
5735 return mTrack->attachAuxEffect(EffectId);
5736}
5737
John Grossman4ff14ba2012-02-08 16:37:41 -08005738status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5739 sp<IMemory>* buffer) {
5740 if (!mTrack->isTimedTrack())
5741 return INVALID_OPERATION;
5742
5743 PlaybackThread::TimedTrack* tt =
5744 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5745 return tt->allocateTimedBuffer(size, buffer);
5746}
5747
5748status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5749 int64_t pts) {
5750 if (!mTrack->isTimedTrack())
5751 return INVALID_OPERATION;
5752
5753 PlaybackThread::TimedTrack* tt =
5754 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5755 return tt->queueTimedBuffer(buffer, pts);
5756}
5757
5758status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5759 const LinearTransform& xform, int target) {
5760
5761 if (!mTrack->isTimedTrack())
5762 return INVALID_OPERATION;
5763
5764 PlaybackThread::TimedTrack* tt =
5765 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5766 return tt->setMediaTimeTransform(
5767 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5768}
5769
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770status_t AudioFlinger::TrackHandle::onTransact(
5771 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5772{
5773 return BnAudioTrack::onTransact(code, data, reply, flags);
5774}
5775
5776// ----------------------------------------------------------------------------
5777
5778sp<IAudioRecord> AudioFlinger::openRecord(
5779 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005780 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005782 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005783 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005785 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005786 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787 int *sessionId,
5788 status_t *status)
5789{
5790 sp<RecordThread::RecordTrack> recordTrack;
5791 sp<RecordHandle> recordHandle;
5792 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 status_t lStatus;
5794 RecordThread *thread;
5795 size_t inFrameCount;
5796 int lSessionId;
5797
5798 // check calling permissions
5799 if (!recordingAllowed()) {
5800 lStatus = PERMISSION_DENIED;
5801 goto Exit;
5802 }
5803
5804 // add client to list
5805 { // scope for mLock
5806 Mutex::Autolock _l(mLock);
5807 thread = checkRecordThread_l(input);
5808 if (thread == NULL) {
5809 lStatus = BAD_VALUE;
5810 goto Exit;
5811 }
5812
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005813 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814
5815 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005816 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 lSessionId = *sessionId;
5818 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005819 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005820 if (sessionId != NULL) {
5821 *sessionId = lSessionId;
5822 }
5823 }
5824 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005825 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5826 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5830 // destructor is called by the TrackBase destructor with mLock held
5831 client.clear();
5832 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 goto Exit;
5834 }
5835
5836 // return to handle to client
5837 recordHandle = new RecordHandle(recordTrack);
5838 lStatus = NO_ERROR;
5839
5840Exit:
5841 if (status) {
5842 *status = lStatus;
5843 }
5844 return recordHandle;
5845}
5846
5847// ----------------------------------------------------------------------------
5848
5849AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5850 : BnAudioRecord(),
5851 mRecordTrack(recordTrack)
5852{
5853}
5854
5855AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005856 stop_nonvirtual();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857}
5858
Glenn Kasten90716c52012-01-26 13:40:12 -08005859sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5860 return mRecordTrack->getCblk();
5861}
5862
Glenn Kasten3acbd052012-02-28 10:39:56 -08005863status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005864 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005865 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866}
5867
5868void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005869 stop_nonvirtual();
5870}
5871
5872void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005873 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 mRecordTrack->stop();
5875}
5876
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877status_t AudioFlinger::RecordHandle::onTransact(
5878 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5879{
5880 return BnAudioRecord::onTransact(code, data, reply, flags);
5881}
5882
5883// ----------------------------------------------------------------------------
5884
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005885AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5886 AudioStreamIn *input,
5887 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005888 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005889 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005890 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005891 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005892 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5893 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005894 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005895 mReqSampleRate(sampleRate)
5896 // mBytesRead is only meaningful while active, and so is cleared in start()
5897 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898{
Glenn Kasten480b4682012-02-28 12:30:08 -08005899 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005900
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 readInputParameters();
5902}
5903
5904
5905AudioFlinger::RecordThread::~RecordThread()
5906{
5907 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005908 delete mResampler;
5909 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910}
5911
5912void AudioFlinger::RecordThread::onFirstRef()
5913{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005914 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915}
5916
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005917status_t AudioFlinger::RecordThread::readyToRun()
5918{
5919 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005920 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005921 return status;
5922}
5923
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924bool AudioFlinger::RecordThread::threadLoop()
5925{
5926 AudioBufferProvider::Buffer buffer;
5927 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005928 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929
Eric Laurent44d98482010-09-30 16:12:31 -07005930 nsecs_t lastWarning = 0;
5931
Eric Laurentfeb0db62011-07-22 09:04:31 -07005932 acquireWakeLock();
5933
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 // start recording
5935 while (!exitPending()) {
5936
5937 processConfigEvents();
5938
5939 { // scope for mLock
5940 Mutex::Autolock _l(mLock);
5941 checkForNewParameters_l();
5942 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5943 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005944 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 mStandby = true;
5946 }
5947
5948 if (exitPending()) break;
5949
Eric Laurentfeb0db62011-07-22 09:04:31 -07005950 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005951 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 // go to sleep
5953 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005954 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005955 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 continue;
5957 }
5958 if (mActiveTrack != 0) {
5959 if (mActiveTrack->mState == TrackBase::PAUSING) {
5960 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005961 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 mStandby = true;
5963 }
5964 mActiveTrack.clear();
5965 mStartStopCond.broadcast();
5966 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5967 if (mReqChannelCount != mActiveTrack->channelCount()) {
5968 mActiveTrack.clear();
5969 mStartStopCond.broadcast();
5970 } else if (mBytesRead != 0) {
5971 // record start succeeds only if first read from audio input
5972 // succeeds
5973 if (mBytesRead > 0) {
5974 mActiveTrack->mState = TrackBase::ACTIVE;
5975 } else {
5976 mActiveTrack.clear();
5977 }
5978 mStartStopCond.broadcast();
5979 }
5980 mStandby = false;
5981 }
5982 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005983 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 }
5985
5986 if (mActiveTrack != 0) {
5987 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5988 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 unlockEffectChains(effectChains);
5990 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 continue;
5992 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005993 for (size_t i = 0; i < effectChains.size(); i ++) {
5994 effectChains[i]->process_l();
5995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005996
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005998 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006000 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 // no resampling
6002 while (framesOut) {
6003 size_t framesIn = mFrameCount - mRsmpInIndex;
6004 if (framesIn) {
6005 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6006 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6007 if (framesIn > framesOut)
6008 framesIn = framesOut;
6009 mRsmpInIndex += framesIn;
6010 framesOut -= framesIn;
6011 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006012 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 memcpy(dst, src, framesIn * mFrameSize);
6014 } else {
6015 int16_t *src16 = (int16_t *)src;
6016 int16_t *dst16 = (int16_t *)dst;
6017 if (mChannelCount == 1) {
6018 while (framesIn--) {
6019 *dst16++ = *src16;
6020 *dst16++ = *src16++;
6021 }
6022 } else {
6023 while (framesIn--) {
6024 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6025 src16 += 2;
6026 }
6027 }
6028 }
6029 }
6030 if (framesOut && mFrameCount == mRsmpInIndex) {
6031 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006032 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006033 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 framesOut = 0;
6035 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006036 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 mRsmpInIndex = 0;
6038 }
6039 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006040 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6042 // Force input into standby so that it tries to
6043 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006044 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 }
6047 mRsmpInIndex = mFrameCount;
6048 framesOut = 0;
6049 buffer.frameCount = 0;
6050 }
6051 }
6052 }
6053 } else {
6054 // resampling
6055
6056 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6057 // alter output frame count as if we were expecting stereo samples
6058 if (mChannelCount == 1 && mReqChannelCount == 1) {
6059 framesOut >>= 1;
6060 }
6061 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6062 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6063 // are 32 bit aligned which should be always true.
6064 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006065 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 // the resampler always outputs stereo samples: do post stereo to mono conversion
6067 int16_t *src = (int16_t *)mRsmpOutBuffer;
6068 int16_t *dst = buffer.i16;
6069 while (framesOut--) {
6070 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6071 src += 2;
6072 }
6073 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006074 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 }
6076
6077 }
Eric Laurenta011e352012-03-29 15:51:43 -07006078 if (mFramestoDrop == 0) {
6079 mActiveTrack->releaseBuffer(&buffer);
6080 } else {
6081 if (mFramestoDrop > 0) {
6082 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006083 if (mFramestoDrop <= 0) {
6084 clearSyncStartEvent();
6085 }
6086 } else {
6087 mFramestoDrop += buffer.frameCount;
6088 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6089 mSyncStartEvent->isCancelled()) {
6090 ALOGW("Synced record %s, session %d, trigger session %d",
6091 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6092 mActiveTrack->sessionId(),
6093 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6094 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006095 }
6096 }
6097 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006098 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 }
6100 // client isn't retrieving buffers fast enough
6101 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006102 if (!mActiveTrack->setOverflow()) {
6103 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006104 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006105 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006106 lastWarning = now;
6107 }
6108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 // Release the processor for a while before asking for a new buffer.
6110 // This will give the application more chance to read from the buffer and
6111 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006112 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 }
6114 }
Eric Laurentec437d82011-07-26 20:54:46 -07006115 // enable changes in effect chain
6116 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 }
6119
6120 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006121 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123
Glenn Kasten33e6e352012-07-16 15:56:57 -07006124 {
6125 Mutex::Autolock _l(mLock);
6126 mActiveTrack.clear();
6127 mStartStopCond.broadcast();
6128 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129
Eric Laurentfeb0db62011-07-22 09:04:31 -07006130 releaseWakeLock();
6131
Steve Block3856b092011-10-20 11:56:00 +01006132 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 return false;
6134}
6135
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006136
6137sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6138 const sp<AudioFlinger::Client>& client,
6139 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006140 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006141 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006144 IAudioFlinger::track_flags_t flags,
6145 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006146 status_t *status)
6147{
6148 sp<RecordTrack> track;
6149 status_t lStatus;
6150
6151 lStatus = initCheck();
6152 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006153 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006154 goto Exit;
6155 }
6156
Glenn Kasten1879fff2012-07-11 15:36:59 -07006157 // FIXME use flags and tid similar to createTrack_l()
6158
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159 { // scope for mLock
6160 Mutex::Autolock _l(mLock);
6161
6162 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006163 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006164
Glenn Kasten7378ca52012-01-20 13:44:40 -08006165 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006166 lStatus = NO_MEMORY;
6167 goto Exit;
6168 }
6169
6170 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006171 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006172 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6173 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006174 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6175 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176 }
6177 lStatus = NO_ERROR;
6178
6179Exit:
6180 if (status) {
6181 *status = lStatus;
6182 }
6183 return track;
6184}
6185
Eric Laurenta011e352012-03-29 15:51:43 -07006186status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006187 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006188 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189{
Glenn Kasten58912562012-04-03 10:45:00 -07006190 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006191 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006193
6194 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006195 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006196 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6197 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6198 triggerSession,
6199 recordTrack->sessionId(),
6200 syncStartEventCallback,
6201 this);
Eric Laurent29864602012-05-08 18:57:51 -07006202 // Sync event can be cancelled by the trigger session if the track is not in a
6203 // compatible state in which case we start record immediately
6204 if (mSyncStartEvent->isCancelled()) {
6205 clearSyncStartEvent();
6206 } else {
6207 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6208 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6209 }
Eric Laurenta011e352012-03-29 15:51:43 -07006210 }
6211
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006213 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 if (mActiveTrack != 0) {
6215 if (recordTrack != mActiveTrack.get()) {
6216 status = -EBUSY;
6217 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6218 mActiveTrack->mState = TrackBase::ACTIVE;
6219 }
6220 return status;
6221 }
6222
6223 recordTrack->mState = TrackBase::IDLE;
6224 mActiveTrack = recordTrack;
6225 mLock.unlock();
6226 status_t status = AudioSystem::startInput(mId);
6227 mLock.lock();
6228 if (status != NO_ERROR) {
6229 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006230 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 return status;
6232 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 mRsmpInIndex = mFrameCount;
6234 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006235 if (mResampler != NULL) {
6236 mResampler->reset();
6237 }
6238 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006240 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 mWaitWorkCV.signal();
6242 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006243 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 mActiveTrack.clear();
6245 status = INVALID_OPERATION;
6246 goto startError;
6247 }
6248 mStartStopCond.wait(mLock);
6249 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006250 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 status = BAD_VALUE;
6252 goto startError;
6253 }
Steve Block3856b092011-10-20 11:56:00 +01006254 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 return status;
6256 }
6257startError:
6258 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006259 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 return status;
6261}
6262
Eric Laurenta011e352012-03-29 15:51:43 -07006263void AudioFlinger::RecordThread::clearSyncStartEvent()
6264{
6265 if (mSyncStartEvent != 0) {
6266 mSyncStartEvent->cancel();
6267 }
6268 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006269 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006270}
6271
6272void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6273{
6274 sp<SyncEvent> strongEvent = event.promote();
6275
6276 if (strongEvent != 0) {
6277 RecordThread *me = (RecordThread *)strongEvent->cookie();
6278 me->handleSyncStartEvent(strongEvent);
6279 }
6280}
6281
6282void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6283{
Eric Laurent29864602012-05-08 18:57:51 -07006284 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006285 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6286 // from audio HAL
6287 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006288 }
6289}
6290
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006292 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006293 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006295 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6297 mActiveTrack->mState = TrackBase::PAUSING;
6298 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006299 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 return;
6301 }
6302 mStartStopCond.wait(mLock);
6303 // if we have been restarted, recordTrack == mActiveTrack.get() here
Glenn Kasten33e6e352012-07-16 15:56:57 -07006304 if (exitPending() || mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 mLock.unlock();
6306 AudioSystem::stopInput(mId);
6307 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006308 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 }
6310 }
6311 }
6312}
6313
Eric Laurenta011e352012-03-29 15:51:43 -07006314bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6315{
6316 return false;
6317}
6318
6319status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6320{
6321 if (!isValidSyncEvent(event)) {
6322 return BAD_VALUE;
6323 }
6324
6325 Mutex::Autolock _l(mLock);
6326
6327 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6328 mTrack->setSyncEvent(event);
6329 return NO_ERROR;
6330 }
6331 return NAME_NOT_FOUND;
6332}
6333
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006334void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335{
6336 const size_t SIZE = 256;
6337 char buffer[SIZE];
6338 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339
6340 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6341 result.append(buffer);
6342
6343 if (mActiveTrack != 0) {
6344 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006345 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 mActiveTrack->dump(buffer, SIZE);
6347 result.append(buffer);
6348
6349 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6350 result.append(buffer);
6351 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6352 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006353 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 result.append(buffer);
6355 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6356 result.append(buffer);
6357 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6358 result.append(buffer);
6359
6360
6361 } else {
6362 result.append("No record client\n");
6363 }
6364 write(fd, result.string(), result.size());
6365
6366 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006367 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368}
6369
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006370// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006371status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006372{
6373 size_t framesReq = buffer->frameCount;
6374 size_t framesReady = mFrameCount - mRsmpInIndex;
6375 int channelCount;
6376
6377 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006378 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006380 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6382 // Force input into standby so that it tries to
6383 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006384 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006385 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006387 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388 buffer->frameCount = 0;
6389 return NOT_ENOUGH_DATA;
6390 }
6391 mRsmpInIndex = 0;
6392 framesReady = mFrameCount;
6393 }
6394
6395 if (framesReq > framesReady) {
6396 framesReq = framesReady;
6397 }
6398
6399 if (mChannelCount == 1 && mReqChannelCount == 2) {
6400 channelCount = 1;
6401 } else {
6402 channelCount = 2;
6403 }
6404 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6405 buffer->frameCount = framesReq;
6406 return NO_ERROR;
6407}
6408
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006409// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6411{
6412 mRsmpInIndex += buffer->frameCount;
6413 buffer->frameCount = 0;
6414}
6415
6416bool AudioFlinger::RecordThread::checkForNewParameters_l()
6417{
6418 bool reconfig = false;
6419
6420 while (!mNewParameters.isEmpty()) {
6421 status_t status = NO_ERROR;
6422 String8 keyValuePair = mNewParameters[0];
6423 AudioParameter param = AudioParameter(keyValuePair);
6424 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006425 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 int reqSamplingRate = mReqSampleRate;
6427 int reqChannelCount = mReqChannelCount;
6428
6429 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6430 reqSamplingRate = value;
6431 reconfig = true;
6432 }
6433 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006434 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 reconfig = true;
6436 }
6437 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006438 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 reconfig = true;
6440 }
6441 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6442 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006443 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 // if frame count is changed after track creation
6445 if (mActiveTrack != 0) {
6446 status = INVALID_OPERATION;
6447 } else {
6448 reconfig = true;
6449 }
6450 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006451 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6452 // forward device change to effects that have requested to be
6453 // aware of attached audio device.
6454 for (size_t i = 0; i < mEffectChains.size(); i++) {
6455 mEffectChains[i]->setDevice_l(value);
6456 }
6457 // store input device and output device but do not forward output device to audio HAL.
6458 // Note that status is ignored by the caller for output device
6459 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006460 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006461 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006462 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006463 status = BAD_VALUE;
6464 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006465 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006466 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6467 if (mTrack != NULL) {
6468 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006469 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006470 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6471 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6472 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006473 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006474 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006475 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006478 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006480 mInput->stream->common.standby(&mInput->stream->common);
6481 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6482 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 }
6484 if (reconfig) {
6485 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006486 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006487 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006488 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006489 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6490 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 status = NO_ERROR;
6492 }
6493 if (status == NO_ERROR) {
6494 readInputParameters();
6495 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6496 }
6497 }
6498 }
6499
6500 mNewParameters.removeAt(0);
6501
6502 mParamStatus = status;
6503 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006504 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6505 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006506 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 }
6508 return reconfig;
6509}
6510
6511String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6512{
Dima Zavinfce7a472011-04-19 22:30:36 -07006513 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006514 String8 out_s8 = String8();
6515
6516 Mutex::Autolock _l(mLock);
6517 if (initCheck() != NO_ERROR) {
6518 return out_s8;
6519 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006520
Dima Zavin799a70e2011-04-18 16:57:27 -07006521 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006522 out_s8 = String8(s);
6523 free(s);
6524 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525}
6526
6527void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6528 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006529 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530
6531 switch (event) {
6532 case AudioSystem::INPUT_OPENED:
6533 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006534 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 desc.samplingRate = mSampleRate;
6536 desc.format = mFormat;
6537 desc.frameCount = mFrameCount;
6538 desc.latency = 0;
6539 param2 = &desc;
6540 break;
6541
6542 case AudioSystem::INPUT_CLOSED:
6543 default:
6544 break;
6545 }
6546 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6547}
6548
6549void AudioFlinger::RecordThread::readInputParameters()
6550{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006551 delete mRsmpInBuffer;
6552 // mRsmpInBuffer is always assigned a new[] below
6553 delete mRsmpOutBuffer;
6554 mRsmpOutBuffer = NULL;
6555 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006556 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557
Dima Zavin799a70e2011-04-18 16:57:27 -07006558 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006559 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6560 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006561 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006562 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006563 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006565 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6567
Glenn Kasten53d76db2012-03-08 12:32:47 -08006568 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 {
6570 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006571 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6572 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 if (mChannelCount == 1 && mReqChannelCount == 2) {
6574 channelCount = 1;
6575 } else {
6576 channelCount = 2;
6577 }
6578 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6579 mResampler->setSampleRate(mSampleRate);
6580 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6581 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6582
6583 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6584 if (mChannelCount == 1 && mReqChannelCount == 1) {
6585 mFrameCount >>= 1;
6586 }
6587
6588 }
6589 mRsmpInIndex = mFrameCount;
6590}
6591
6592unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6593{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006594 Mutex::Autolock _l(mLock);
6595 if (initCheck() != NO_ERROR) {
6596 return 0;
6597 }
6598
Dima Zavin799a70e2011-04-18 16:57:27 -07006599 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600}
6601
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006602uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6603{
6604 Mutex::Autolock _l(mLock);
6605 uint32_t result = 0;
6606 if (getEffectChain_l(sessionId) != 0) {
6607 result = EFFECT_SESSION;
6608 }
6609
6610 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6611 result |= TRACK_SESSION;
6612 }
6613
6614 return result;
6615}
6616
Eric Laurent59bd0da2011-08-01 09:52:20 -07006617AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6618{
6619 Mutex::Autolock _l(mLock);
6620 return mTrack;
6621}
6622
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006623AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6624{
6625 Mutex::Autolock _l(mLock);
6626 AudioStreamIn *input = mInput;
6627 mInput = NULL;
6628 return input;
6629}
6630
6631// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006632audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006633{
6634 if (mInput == NULL) {
6635 return NULL;
6636 }
6637 return &mInput->stream->common;
6638}
6639
6640
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641// ----------------------------------------------------------------------------
6642
Eric Laurenta4c5a552012-03-29 10:12:40 -07006643audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6644{
6645 if (!settingsAllowed()) {
6646 return 0;
6647 }
6648 Mutex::Autolock _l(mLock);
6649 return loadHwModule_l(name);
6650}
6651
6652// loadHwModule_l() must be called with AudioFlinger::mLock held
6653audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6654{
6655 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6656 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6657 ALOGW("loadHwModule() module %s already loaded", name);
6658 return mAudioHwDevs.keyAt(i);
6659 }
6660 }
6661
Eric Laurenta4c5a552012-03-29 10:12:40 -07006662 audio_hw_device_t *dev;
6663
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006664 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006665 if (rc) {
6666 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6667 return 0;
6668 }
6669
6670 mHardwareStatus = AUDIO_HW_INIT;
6671 rc = dev->init_check(dev);
6672 mHardwareStatus = AUDIO_HW_IDLE;
6673 if (rc) {
6674 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6675 return 0;
6676 }
6677
6678 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6679 (NULL != dev->set_master_volume)) {
6680 AutoMutex lock(mHardwareLock);
6681 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6682 dev->set_master_volume(dev, mMasterVolume);
6683 mHardwareStatus = AUDIO_HW_IDLE;
6684 }
6685
6686 audio_module_handle_t handle = nextUniqueId();
6687 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6688
6689 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006690 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006691
6692 return handle;
6693
6694}
6695
6696audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6697 audio_devices_t *pDevices,
6698 uint32_t *pSamplingRate,
6699 audio_format_t *pFormat,
6700 audio_channel_mask_t *pChannelMask,
6701 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006702 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006703{
6704 status_t status;
6705 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006706 struct audio_config config = {
6707 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6708 channel_mask: pChannelMask ? *pChannelMask : 0,
6709 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6710 };
6711 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006712 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713
Eric Laurenta4c5a552012-03-29 10:12:40 -07006714 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6715 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006716 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006717 config.sample_rate,
6718 config.format,
6719 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006720 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721
6722 if (pDevices == NULL || *pDevices == 0) {
6723 return 0;
6724 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006725
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 Mutex::Autolock _l(mLock);
6727
Eric Laurenta4c5a552012-03-29 10:12:40 -07006728 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006729 if (outHwDev == NULL)
6730 return 0;
6731
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006732 audio_io_handle_t id = nextUniqueId();
6733
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006734 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006735
6736 status = outHwDev->open_output_stream(outHwDev,
6737 id,
6738 *pDevices,
6739 (audio_output_flags_t)flags,
6740 &config,
6741 &outStream);
6742
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006743 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006744 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006745 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006746 config.sample_rate,
6747 config.format,
6748 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749 status);
6750
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006751 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006752 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006753
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006754 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006755 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6756 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006758 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 } else {
6760 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006761 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 }
6763 mPlaybackThreads.add(id, thread);
6764
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006765 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6766 if (pFormat != NULL) *pFormat = config.format;
6767 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006768 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769
6770 // notify client processes of the new output creation
6771 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006772
6773 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006774 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006775 ALOGI("Using module %d has the primary audio interface", module);
6776 mPrimaryHardwareDev = outHwDev;
6777
6778 AutoMutex lock(mHardwareLock);
6779 mHardwareStatus = AUDIO_HW_SET_MODE;
6780 outHwDev->set_mode(outHwDev, mMode);
6781
6782 // Determine the level of master volume support the primary audio HAL has,
6783 // and set the initial master volume at the same time.
6784 float initialVolume = 1.0;
6785 mMasterVolumeSupportLvl = MVS_NONE;
6786
6787 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6788 if ((NULL != outHwDev->get_master_volume) &&
6789 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6790 mMasterVolumeSupportLvl = MVS_FULL;
6791 } else {
6792 mMasterVolumeSupportLvl = MVS_SETONLY;
6793 initialVolume = 1.0;
6794 }
6795
6796 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6797 if ((NULL == outHwDev->set_master_volume) ||
6798 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6799 mMasterVolumeSupportLvl = MVS_NONE;
6800 }
6801 // now that we have a primary device, initialize master volume on other devices
6802 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6803 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6804
6805 if ((dev != mPrimaryHardwareDev) &&
6806 (NULL != dev->set_master_volume)) {
6807 dev->set_master_volume(dev, initialVolume);
6808 }
6809 }
6810 mHardwareStatus = AUDIO_HW_IDLE;
6811 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6812 ? initialVolume
6813 : 1.0;
6814 mMasterVolume = initialVolume;
6815 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006816 return id;
6817 }
6818
6819 return 0;
6820}
6821
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006822audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6823 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006824{
6825 Mutex::Autolock _l(mLock);
6826 MixerThread *thread1 = checkMixerThread_l(output1);
6827 MixerThread *thread2 = checkMixerThread_l(output2);
6828
6829 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006830 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831 return 0;
6832 }
6833
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006834 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6836 thread->addOutputTrack(thread2);
6837 mPlaybackThreads.add(id, thread);
6838 // notify client processes of the new output creation
6839 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6840 return id;
6841}
6842
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006843status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844{
Glenn Kastend96c5722012-04-25 13:44:49 -07006845 return closeOutput_nonvirtual(output);
6846}
6847
6848status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6849{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 // keep strong reference on the playback thread so that
6851 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006852 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 {
6854 Mutex::Autolock _l(mLock);
6855 thread = checkPlaybackThread_l(output);
6856 if (thread == NULL) {
6857 return BAD_VALUE;
6858 }
6859
Steve Block3856b092011-10-20 11:56:00 +01006860 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006862 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6866 dupThread->removeOutputTrack((MixerThread *)thread.get());
6867 }
6868 }
6869 }
Glenn Kastena1117922012-01-26 10:53:32 -08006870 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 mPlaybackThreads.removeItem(output);
6872 }
6873 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006874 // The thread entity (active unit of execution) is no longer running here,
6875 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006878 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006879 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006880 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006881 out->hwDev->close_output_stream(out->hwDev, out->stream);
6882 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 }
6884 return NO_ERROR;
6885}
6886
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006887status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888{
6889 Mutex::Autolock _l(mLock);
6890 PlaybackThread *thread = checkPlaybackThread_l(output);
6891
6892 if (thread == NULL) {
6893 return BAD_VALUE;
6894 }
6895
Steve Block3856b092011-10-20 11:56:00 +01006896 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 thread->suspend();
6898
6899 return NO_ERROR;
6900}
6901
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006902status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903{
6904 Mutex::Autolock _l(mLock);
6905 PlaybackThread *thread = checkPlaybackThread_l(output);
6906
6907 if (thread == NULL) {
6908 return BAD_VALUE;
6909 }
6910
Steve Block3856b092011-10-20 11:56:00 +01006911 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912
6913 thread->restore();
6914
6915 return NO_ERROR;
6916}
6917
Eric Laurenta4c5a552012-03-29 10:12:40 -07006918audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6919 audio_devices_t *pDevices,
6920 uint32_t *pSamplingRate,
6921 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006922 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923{
6924 status_t status;
6925 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006926 struct audio_config config = {
6927 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6928 channel_mask: pChannelMask ? *pChannelMask : 0,
6929 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6930 };
6931 uint32_t reqSamplingRate = config.sample_rate;
6932 audio_format_t reqFormat = config.format;
6933 audio_channel_mask_t reqChannels = config.channel_mask;
6934 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006935 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936
6937 if (pDevices == NULL || *pDevices == 0) {
6938 return 0;
6939 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006940
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 Mutex::Autolock _l(mLock);
6942
Eric Laurenta4c5a552012-03-29 10:12:40 -07006943 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006944 if (inHwDev == NULL)
6945 return 0;
6946
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006947 audio_io_handle_t id = nextUniqueId();
6948
6949 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006950 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006951 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006952 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006953 config.sample_rate,
6954 config.format,
6955 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 status);
6957
6958 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6959 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6960 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006961 if (status == BAD_VALUE &&
6962 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6963 (config.sample_rate <= 2 * reqSamplingRate) &&
6964 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006965 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006966 inStream = NULL;
6967 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 }
6969
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006970 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006971 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6972
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006973 // Start record thread
6974 // RecorThread require both input and output device indication to forward to audio
6975 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006976 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006977 thread = new RecordThread(this,
6978 input,
6979 reqSamplingRate,
6980 reqChannels,
6981 id,
6982 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006985 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006986 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006987 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988
Dima Zavin799a70e2011-04-18 16:57:27 -07006989 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990
6991 // notify client processes of the new input creation
6992 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6993 return id;
6994 }
6995
6996 return 0;
6997}
6998
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006999status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000{
Glenn Kastend96c5722012-04-25 13:44:49 -07007001 return closeInput_nonvirtual(input);
7002}
7003
7004status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7005{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 // keep strong reference on the record thread so that
7007 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007008 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 {
7010 Mutex::Autolock _l(mLock);
7011 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007012 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 return BAD_VALUE;
7014 }
7015
Steve Block3856b092011-10-20 11:56:00 +01007016 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007017 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 mRecordThreads.removeItem(input);
7019 }
7020 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007021 // The thread entity (active unit of execution) is no longer running here,
7022 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007024 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007025 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007026 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007027 in->hwDev->close_input_stream(in->hwDev, in->stream);
7028 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029
7030 return NO_ERROR;
7031}
7032
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007033status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034{
7035 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007036 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
7038 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7039 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007040 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007041 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042
7043 return NO_ERROR;
7044}
7045
7046
7047int AudioFlinger::newAudioSessionId()
7048{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007049 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050}
7051
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007052void AudioFlinger::acquireAudioSessionId(int audioSession)
7053{
7054 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007055 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007056 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007057 size_t num = mAudioSessionRefs.size();
7058 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007059 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007060 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7061 ref->mCnt++;
7062 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007063 return;
7064 }
7065 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007066 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7067 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007068}
7069
7070void AudioFlinger::releaseAudioSessionId(int audioSession)
7071{
7072 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007073 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007074 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007075 size_t num = mAudioSessionRefs.size();
7076 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007077 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007078 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7079 ref->mCnt--;
7080 ALOGV(" decremented refcount to %d", ref->mCnt);
7081 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007082 mAudioSessionRefs.removeAt(i);
7083 delete ref;
7084 purgeStaleEffects_l();
7085 }
7086 return;
7087 }
7088 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007089 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007090}
7091
7092void AudioFlinger::purgeStaleEffects_l() {
7093
Steve Block3856b092011-10-20 11:56:00 +01007094 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007095
7096 Vector< sp<EffectChain> > chains;
7097
7098 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7099 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7100 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7101 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007102 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7103 chains.push(ec);
7104 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007105 }
7106 }
7107 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7108 sp<RecordThread> t = mRecordThreads.valueAt(i);
7109 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7110 sp<EffectChain> ec = t->mEffectChains[j];
7111 chains.push(ec);
7112 }
7113 }
7114
7115 for (size_t i = 0; i < chains.size(); i++) {
7116 sp<EffectChain> ec = chains[i];
7117 int sessionid = ec->sessionId();
7118 sp<ThreadBase> t = ec->mThread.promote();
7119 if (t == 0) {
7120 continue;
7121 }
7122 size_t numsessionrefs = mAudioSessionRefs.size();
7123 bool found = false;
7124 for (size_t k = 0; k < numsessionrefs; k++) {
7125 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007126 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007127 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007128 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007129 found = true;
7130 break;
7131 }
7132 }
7133 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007134 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007135 // remove all effects from the chain
7136 while (ec->mEffects.size()) {
7137 sp<EffectModule> effect = ec->mEffects[0];
7138 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007139 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007140 if (effect->purgeHandles()) {
7141 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007142 }
7143 AudioSystem::unregisterEffect(effect->id());
7144 }
7145 }
7146 }
7147 return;
7148}
7149
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007151AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152{
Glenn Kastena1117922012-01-26 10:53:32 -08007153 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154}
7155
7156// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007157AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158{
7159 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007160 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161}
7162
7163// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007164AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
Glenn Kastena1117922012-01-26 10:53:32 -08007166 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167}
7168
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007169uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007171 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007174AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007175{
7176 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7177 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007178 AudioStreamOut *output = thread->getOutput();
7179 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180 return thread;
7181 }
7182 }
7183 return NULL;
7184}
7185
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007186audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007187{
7188 PlaybackThread *thread = primaryPlaybackThread_l();
7189
7190 if (thread == NULL) {
7191 return 0;
7192 }
7193
7194 return thread->device();
7195}
7196
Eric Laurenta011e352012-03-29 15:51:43 -07007197sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7198 int triggerSession,
7199 int listenerSession,
7200 sync_event_callback_t callBack,
7201 void *cookie)
7202{
7203 Mutex::Autolock _l(mLock);
7204
7205 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7206 status_t playStatus = NAME_NOT_FOUND;
7207 status_t recStatus = NAME_NOT_FOUND;
7208 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7209 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7210 if (playStatus == NO_ERROR) {
7211 return event;
7212 }
7213 }
7214 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7215 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7216 if (recStatus == NO_ERROR) {
7217 return event;
7218 }
7219 }
7220 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7221 mPendingSyncEvents.add(event);
7222 } else {
7223 ALOGV("createSyncEvent() invalid event %d", event->type());
7224 event.clear();
7225 }
7226 return event;
7227}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007228
Mathias Agopian65ab4712010-07-14 17:59:35 -07007229// ----------------------------------------------------------------------------
7230// Effect management
7231// ----------------------------------------------------------------------------
7232
7233
Glenn Kastenf587ba52012-01-26 16:25:10 -08007234status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235{
7236 Mutex::Autolock _l(mLock);
7237 return EffectQueryNumberEffects(numEffects);
7238}
7239
Glenn Kastenf587ba52012-01-26 16:25:10 -08007240status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241{
7242 Mutex::Autolock _l(mLock);
7243 return EffectQueryEffect(index, descriptor);
7244}
7245
Glenn Kasten5e92a782012-01-30 07:40:52 -08007246status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007247 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248{
7249 Mutex::Autolock _l(mLock);
7250 return EffectGetDescriptor(pUuid, descriptor);
7251}
7252
7253
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7255 effect_descriptor_t *pDesc,
7256 const sp<IEffectClient>& effectClient,
7257 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007258 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259 int sessionId,
7260 status_t *status,
7261 int *id,
7262 int *enabled)
7263{
7264 status_t lStatus = NO_ERROR;
7265 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007268 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007269 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270
7271 if (pDesc == NULL) {
7272 lStatus = BAD_VALUE;
7273 goto Exit;
7274 }
7275
Eric Laurent84e9a102010-09-23 16:10:16 -07007276 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007277 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007278 lStatus = PERMISSION_DENIED;
7279 goto Exit;
7280 }
7281
Dima Zavinfce7a472011-04-19 22:30:36 -07007282 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007284 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007285 lStatus = PERMISSION_DENIED;
7286 goto Exit;
7287 }
7288
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007289 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007290 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007291 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007292 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007293 lStatus = BAD_VALUE;
7294 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007295 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007296 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007297 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007299 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007300 }
7301 }
7302
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303 {
7304 Mutex::Autolock _l(mLock);
7305
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306
7307 if (!EffectIsNullUuid(&pDesc->uuid)) {
7308 // if uuid is specified, request effect descriptor
7309 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7310 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007311 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312 goto Exit;
7313 }
7314 } else {
7315 // if uuid is not specified, look for an available implementation
7316 // of the required type in effect factory
7317 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007318 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 lStatus = BAD_VALUE;
7320 goto Exit;
7321 }
7322 uint32_t numEffects = 0;
7323 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007324 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325 bool found = false;
7326
7327 lStatus = EffectQueryNumberEffects(&numEffects);
7328 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007329 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 goto Exit;
7331 }
7332 for (uint32_t i = 0; i < numEffects; i++) {
7333 lStatus = EffectQueryEffect(i, &desc);
7334 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007335 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 continue;
7337 }
7338 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7339 // If matching type found save effect descriptor. If the session is
7340 // 0 and the effect is not auxiliary, continue enumeration in case
7341 // an auxiliary version of this effect type is available
7342 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007343 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007344 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7346 break;
7347 }
7348 }
7349 }
7350 if (!found) {
7351 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007352 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 goto Exit;
7354 }
7355 // For same effect type, chose auxiliary version over insert version if
7356 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007357 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007359 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 }
7361 }
7362
7363 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007364 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7366 lStatus = INVALID_OPERATION;
7367 goto Exit;
7368 }
7369
Eric Laurent59255e42011-07-27 19:49:51 -07007370 // check recording permission for visualizer
7371 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7372 !recordingAllowed()) {
7373 lStatus = PERMISSION_DENIED;
7374 goto Exit;
7375 }
7376
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007378 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379
7380 // If output is not specified try to find a matching audio session ID in one of the
7381 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007382 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7383 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007384 // Note: io is never 0 when creating an effect on an input
7385 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007386 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007387 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7388 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007389 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007390 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007393 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007394 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7395 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7396 io = mRecordThreads.keyAt(i);
7397 break;
7398 }
7399 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007401 // If no output thread contains the requested session ID, default to
7402 // first output. The effect chain will be moved to the correct output
7403 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007404 if (io == 0 && mPlaybackThreads.size()) {
7405 io = mPlaybackThreads.keyAt(0);
7406 }
Steve Block3856b092011-10-20 11:56:00 +01007407 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007408 }
7409 ThreadBase *thread = checkRecordThread_l(io);
7410 if (thread == NULL) {
7411 thread = checkPlaybackThread_l(io);
7412 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007413 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007414 lStatus = BAD_VALUE;
7415 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007418
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007419 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007421 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007422 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7423 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 if (handle != 0 && id != NULL) {
7425 *id = handle->id();
7426 }
7427 }
7428
7429Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007430 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 *status = lStatus;
7432 }
7433 return handle;
7434}
7435
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007436status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7437 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007438{
Steve Block3856b092011-10-20 11:56:00 +01007439 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007440 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007441 Mutex::Autolock _l(mLock);
7442 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007443 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007444 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 }
Eric Laurentde070132010-07-13 04:45:46 -07007446 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7447 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007449 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 }
Eric Laurentde070132010-07-13 04:45:46 -07007451 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7452 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007453 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007454 return BAD_VALUE;
7455 }
7456
7457 Mutex::Autolock _dl(dstThread->mLock);
7458 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007459 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007460
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 return NO_ERROR;
7462}
7463
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007464// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007465status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007466 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007467 AudioFlinger::PlaybackThread *dstThread,
7468 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007469{
Steve Block3856b092011-10-20 11:56:00 +01007470 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007471 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007472
Eric Laurent59255e42011-07-27 19:49:51 -07007473 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007474 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007475 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007476 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007477 return INVALID_OPERATION;
7478 }
7479
Eric Laurent39e94f82010-07-28 01:32:47 -07007480 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007481 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007482 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007483 // removed.
7484 srcThread->removeEffectChain_l(chain);
7485
7486 // transfer all effects one by one so that new effect chain is created on new thread with
7487 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007488 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007489 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007490 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007491 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7492 while (effect != 0) {
7493 srcThread->removeEffect_l(effect);
7494 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007495 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7496 if (effect->state() == EffectModule::ACTIVE ||
7497 effect->state() == EffectModule::STOPPING) {
7498 effect->start();
7499 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007500 // if the move request is not received from audio policy manager, the effect must be
7501 // re-registered with the new strategy and output
7502 if (dstChain == 0) {
7503 dstChain = effect->chain().promote();
7504 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007505 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007506 srcThread->addEffect_l(effect);
7507 return NO_INIT;
7508 }
7509 strategy = dstChain->strategy();
7510 }
7511 if (reRegister) {
7512 AudioSystem::unregisterEffect(effect->id());
7513 AudioSystem::registerEffect(&effect->desc(),
7514 dstOutput,
7515 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007516 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007517 effect->id());
7518 }
Eric Laurentde070132010-07-13 04:45:46 -07007519 effect = chain->getEffectFromId_l(0);
7520 }
7521
7522 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523}
7524
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007525
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007527sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528 const sp<AudioFlinger::Client>& client,
7529 const sp<IEffectClient>& effectClient,
7530 int32_t priority,
7531 int sessionId,
7532 effect_descriptor_t *desc,
7533 int *enabled,
7534 status_t *status
7535 )
7536{
7537 sp<EffectModule> effect;
7538 sp<EffectHandle> handle;
7539 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007541 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007542 bool effectCreated = false;
7543 bool effectRegistered = false;
7544
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007545 lStatus = initCheck();
7546 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007547 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 goto Exit;
7549 }
7550
7551 // Do not allow effects with session ID 0 on direct output or duplicating threads
7552 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007553 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007554 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007555 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007556 lStatus = BAD_VALUE;
7557 goto Exit;
7558 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007559 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007560 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007561 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007562 desc->name, desc->flags, mType);
7563 lStatus = BAD_VALUE;
7564 goto Exit;
7565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566
Steve Block3856b092011-10-20 11:56:00 +01007567 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568
7569 { // scope for mLock
7570 Mutex::Autolock _l(mLock);
7571
7572 // check for existing effect chain with the requested audio session
7573 chain = getEffectChain_l(sessionId);
7574 if (chain == 0) {
7575 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007576 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577 chain = new EffectChain(this, sessionId);
7578 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007579 chain->setStrategy(getStrategyForSession_l(sessionId));
7580 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007582 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 }
7584
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007585 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586
7587 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007590 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 if (lStatus != NO_ERROR) {
7592 goto Exit;
7593 }
7594 effectRegistered = true;
7595 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007596 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 lStatus = effect->status();
7598 if (lStatus != NO_ERROR) {
7599 goto Exit;
7600 }
Eric Laurentcab11242010-07-15 12:50:15 -07007601 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 if (lStatus != NO_ERROR) {
7603 goto Exit;
7604 }
7605 effectCreated = true;
7606
7607 effect->setDevice(mDevice);
7608 effect->setMode(mAudioFlinger->getMode());
7609 }
7610 // create effect handle and connect it to effect module
7611 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007612 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007613 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614 *enabled = (int)effect->isEnabled();
7615 }
7616 }
7617
7618Exit:
7619 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007620 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007622 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 }
7624 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007625 AudioSystem::unregisterEffect(effect->id());
7626 }
7627 if (chainCreated) {
7628 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 }
7630 handle.clear();
7631 }
7632
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007633 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 *status = lStatus;
7635 }
7636 return handle;
7637}
7638
Eric Laurent717e1282012-06-29 16:36:52 -07007639sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7640{
7641 Mutex::Autolock _l(mLock);
7642 return getEffect_l(sessionId, effectId);
7643}
7644
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007645sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7646{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007647 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007648 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007649}
7650
Eric Laurentde070132010-07-13 04:45:46 -07007651// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7652// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007653status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007654{
7655 // check for existing effect chain with the requested audio session
7656 int sessionId = effect->sessionId();
7657 sp<EffectChain> chain = getEffectChain_l(sessionId);
7658 bool chainCreated = false;
7659
7660 if (chain == 0) {
7661 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007662 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007663 chain = new EffectChain(this, sessionId);
7664 addEffectChain_l(chain);
7665 chain->setStrategy(getStrategyForSession_l(sessionId));
7666 chainCreated = true;
7667 }
Steve Block3856b092011-10-20 11:56:00 +01007668 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007669
7670 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007671 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007672 this, effect->desc().name, chain.get());
7673 return BAD_VALUE;
7674 }
7675
7676 status_t status = chain->addEffect_l(effect);
7677 if (status != NO_ERROR) {
7678 if (chainCreated) {
7679 removeEffectChain_l(chain);
7680 }
7681 return status;
7682 }
7683
7684 effect->setDevice(mDevice);
7685 effect->setMode(mAudioFlinger->getMode());
7686 return NO_ERROR;
7687}
7688
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007689void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007690
Steve Block3856b092011-10-20 11:56:00 +01007691 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007693 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7694 detachAuxEffect_l(effect->id());
7695 }
7696
7697 sp<EffectChain> chain = effect->chain().promote();
7698 if (chain != 0) {
7699 // remove effect chain if removing last effect
7700 if (chain->removeEffect_l(effect) == 0) {
7701 removeEffectChain_l(chain);
7702 }
7703 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007704 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007705 }
7706}
7707
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007708void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007709 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007710{
7711 effectChains = mEffectChains;
7712 for (size_t i = 0; i < mEffectChains.size(); i++) {
7713 mEffectChains[i]->lock();
7714 }
7715}
7716
7717void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007718 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719{
7720 for (size_t i = 0; i < effectChains.size(); i++) {
7721 effectChains[i]->unlock();
7722 }
7723}
7724
7725sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7726{
7727 Mutex::Autolock _l(mLock);
7728 return getEffectChain_l(sessionId);
7729}
7730
7731sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7732{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007733 size_t size = mEffectChains.size();
7734 for (size_t i = 0; i < size; i++) {
7735 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007736 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007737 }
7738 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007739 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007740}
7741
Glenn Kastenf78aee72012-01-04 11:00:47 -08007742void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007743{
7744 Mutex::Autolock _l(mLock);
7745 size_t size = mEffectChains.size();
7746 for (size_t i = 0; i < size; i++) {
7747 mEffectChains[i]->setMode_l(mode);
7748 }
7749}
7750
7751void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007752 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007753 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007754
Mathias Agopian65ab4712010-07-14 17:59:35 -07007755 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007756 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757 // delete the effect module if removing last handle on it
7758 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007759 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007760 removeEffect_l(effect);
7761 AudioSystem::unregisterEffect(effect->id());
7762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 }
7764}
7765
7766status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7767{
7768 int session = chain->sessionId();
7769 int16_t *buffer = mMixBuffer;
7770 bool ownsBuffer = false;
7771
Steve Block3856b092011-10-20 11:56:00 +01007772 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773 if (session > 0) {
7774 // Only one effect chain can be present in direct output thread and it uses
7775 // the mix buffer as input
7776 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007777 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 buffer = new int16_t[numSamples];
7779 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007780 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781 ownsBuffer = true;
7782 }
7783
7784 // Attach all tracks with same session ID to this chain.
7785 for (size_t i = 0; i < mTracks.size(); ++i) {
7786 sp<Track> track = mTracks[i];
7787 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007788 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007790 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 }
7792 }
7793
7794 // indicate all active tracks in the chain
7795 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7796 sp<Track> track = mActiveTracks[i].promote();
7797 if (track == 0) continue;
7798 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007799 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007800 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 }
7802 }
7803 }
7804
7805 chain->setInBuffer(buffer, ownsBuffer);
7806 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007807 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007808 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007809 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7810 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007812 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7813 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007814 // Effect chain for other sessions are inserted at beginning of effect
7815 // chains list to be processed before output mix effects. Relative order between other
7816 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007817 size_t size = mEffectChains.size();
7818 size_t i = 0;
7819 for (i = 0; i < size; i++) {
7820 if (mEffectChains[i]->sessionId() < session) break;
7821 }
7822 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007823 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824
7825 return NO_ERROR;
7826}
7827
7828size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7829{
7830 int session = chain->sessionId();
7831
Steve Block3856b092011-10-20 11:56:00 +01007832 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833
7834 for (size_t i = 0; i < mEffectChains.size(); i++) {
7835 if (chain == mEffectChains[i]) {
7836 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007837 // detach all active tracks from the chain
7838 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7839 sp<Track> track = mActiveTracks[i].promote();
7840 if (track == 0) continue;
7841 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007842 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007843 chain.get(), session);
7844 chain->decActiveTrackCnt();
7845 }
7846 }
7847
Mathias Agopian65ab4712010-07-14 17:59:35 -07007848 // detach all tracks with same session ID from this chain
7849 for (size_t i = 0; i < mTracks.size(); ++i) {
7850 sp<Track> track = mTracks[i];
7851 if (session == track->sessionId()) {
7852 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007853 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007854 }
7855 }
Eric Laurentde070132010-07-13 04:45:46 -07007856 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857 }
7858 }
7859 return mEffectChains.size();
7860}
7861
Eric Laurentde070132010-07-13 04:45:46 -07007862status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7863 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864{
7865 Mutex::Autolock _l(mLock);
7866 return attachAuxEffect_l(track, EffectId);
7867}
7868
Eric Laurentde070132010-07-13 04:45:46 -07007869status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7870 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871{
7872 status_t status = NO_ERROR;
7873
7874 if (EffectId == 0) {
7875 track->setAuxBuffer(0, NULL);
7876 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007877 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7878 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007879 if (effect != 0) {
7880 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7881 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7882 } else {
7883 status = INVALID_OPERATION;
7884 }
7885 } else {
7886 status = BAD_VALUE;
7887 }
7888 }
7889 return status;
7890}
7891
7892void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7893{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007894 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895 sp<Track> track = mTracks[i];
7896 if (track->auxEffectId() == effectId) {
7897 attachAuxEffect_l(track, 0);
7898 }
7899 }
7900}
7901
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007902status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7903{
7904 // only one chain per input thread
7905 if (mEffectChains.size() != 0) {
7906 return INVALID_OPERATION;
7907 }
Steve Block3856b092011-10-20 11:56:00 +01007908 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007909
7910 chain->setInBuffer(NULL);
7911 chain->setOutBuffer(NULL);
7912
Eric Laurent59255e42011-07-27 19:49:51 -07007913 checkSuspendOnAddEffectChain_l(chain);
7914
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007915 mEffectChains.add(chain);
7916
7917 return NO_ERROR;
7918}
7919
7920size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7921{
Steve Block3856b092011-10-20 11:56:00 +01007922 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007923 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007924 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7925 chain.get(), mEffectChains.size(), this);
7926 if (mEffectChains.size() == 1) {
7927 mEffectChains.removeAt(0);
7928 }
7929 return 0;
7930}
7931
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932// ----------------------------------------------------------------------------
7933// EffectModule implementation
7934// ----------------------------------------------------------------------------
7935
7936#undef LOG_TAG
7937#define LOG_TAG "AudioFlinger::EffectModule"
7938
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007939AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 const wp<AudioFlinger::EffectChain>& chain,
7941 effect_descriptor_t *desc,
7942 int id,
7943 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007944 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7945 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07007946 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07007947 // mConfig is set by configure() and not used before then
7948 mEffectInterface(NULL),
7949 mStatus(NO_INIT), mState(IDLE),
7950 // mMaxDisableWaitCnt is set by configure() and not used before then
7951 // mDisableWaitCnt is set by process() and updateState() and not used before then
7952 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007953{
Steve Block3856b092011-10-20 11:56:00 +01007954 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956
7957 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007958 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959
7960 if (mStatus != NO_ERROR) {
7961 return;
7962 }
7963 lStatus = init();
7964 if (lStatus < 0) {
7965 mStatus = lStatus;
7966 goto Error;
7967 }
7968
Steve Block3856b092011-10-20 11:56:00 +01007969 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 return;
7971Error:
7972 EffectRelease(mEffectInterface);
7973 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007974 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975}
7976
7977AudioFlinger::EffectModule::~EffectModule()
7978{
Steve Block3856b092011-10-20 11:56:00 +01007979 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007981 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7982 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7983 sp<ThreadBase> thread = mThread.promote();
7984 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007985 audio_stream_t *stream = thread->stream();
7986 if (stream != NULL) {
7987 stream->remove_audio_effect(stream, mEffectInterface);
7988 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007989 }
7990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 // release effect engine
7992 EffectRelease(mEffectInterface);
7993 }
7994}
7995
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007996status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997{
7998 status_t status;
7999
8000 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 int priority = handle->priority();
8002 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008003 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008004 size_t i;
8005 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008006 EffectHandle *h = mHandles[i];
8007 if (h == NULL || h->destroyed_l()) continue;
8008 // first non destroyed handle is considered in control
8009 if (controlHandle == NULL)
8010 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011 if (h->priority() <= priority) break;
8012 }
8013 // if inserted in first place, move effect control from previous owner to this handle
8014 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008015 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008016 if (controlHandle != NULL) {
8017 enabled = controlHandle->enabled();
8018 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019 }
Eric Laurent59255e42011-07-27 19:49:51 -07008020 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 status = NO_ERROR;
8022 } else {
8023 status = ALREADY_EXISTS;
8024 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008025 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 mHandles.insertAt(handle, i);
8027 return status;
8028}
8029
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008030size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008031{
8032 Mutex::Autolock _l(mLock);
8033 size_t size = mHandles.size();
8034 size_t i;
8035 for (i = 0; i < size; i++) {
8036 if (mHandles[i] == handle) break;
8037 }
8038 if (i == size) {
8039 return size;
8040 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008041 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008042
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008045 if (i == 0) {
8046 EffectHandle *h = controlHandle_l();
8047 if (h != NULL) {
8048 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049 }
8050 }
8051
Eric Laurentec437d82011-07-26 20:54:46 -07008052 // Prevent calls to process() and other functions on effect interface from now on.
8053 // The effect engine will be released by the destructor when the last strong reference on
8054 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008055 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008056 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008057 }
8058
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 return size;
8060}
8061
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008062// must be called with EffectModule::mLock held
8063AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008064{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008065 // the first valid handle in the list has control over the module
8066 for (size_t i = 0; i < mHandles.size(); i++) {
8067 EffectHandle *h = mHandles[i];
8068 if (h != NULL && !h->destroyed_l()) {
8069 return h;
8070 }
8071 }
8072
8073 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008074}
8075
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008076size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008078 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008079 // keep a strong reference on this EffectModule to avoid calling the
8080 // destructor before we exit
8081 sp<EffectModule> keep(this);
8082 {
8083 sp<ThreadBase> thread = mThread.promote();
8084 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008085 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086 }
8087 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008088 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089}
8090
8091void AudioFlinger::EffectModule::updateState() {
8092 Mutex::Autolock _l(mLock);
8093
8094 switch (mState) {
8095 case RESTART:
8096 reset_l();
8097 // FALL THROUGH
8098
8099 case STARTING:
8100 // clear auxiliary effect input buffer for next accumulation
8101 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8102 memset(mConfig.inputCfg.buffer.raw,
8103 0,
8104 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8105 }
8106 start_l();
8107 mState = ACTIVE;
8108 break;
8109 case STOPPING:
8110 stop_l();
8111 mDisableWaitCnt = mMaxDisableWaitCnt;
8112 mState = STOPPED;
8113 break;
8114 case STOPPED:
8115 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8116 // turn off sequence.
8117 if (--mDisableWaitCnt == 0) {
8118 reset_l();
8119 mState = IDLE;
8120 }
8121 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008122 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123 break;
8124 }
8125}
8126
8127void AudioFlinger::EffectModule::process()
8128{
8129 Mutex::Autolock _l(mLock);
8130
Eric Laurentec437d82011-07-26 20:54:46 -07008131 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 mConfig.inputCfg.buffer.raw == NULL ||
8133 mConfig.outputCfg.buffer.raw == NULL) {
8134 return;
8135 }
8136
Eric Laurent8f45bd72010-08-31 13:50:07 -07008137 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8139 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008140 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008142 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143 }
8144
8145 // do the actual processing in the effect engine
8146 int ret = (*mEffectInterface)->process(mEffectInterface,
8147 &mConfig.inputCfg.buffer,
8148 &mConfig.outputCfg.buffer);
8149
8150 // force transition to IDLE state when engine is ready
8151 if (mState == STOPPED && ret == -ENODATA) {
8152 mDisableWaitCnt = 1;
8153 }
8154
8155 // clear auxiliary effect input buffer for next accumulation
8156 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008157 memset(mConfig.inputCfg.buffer.raw, 0,
8158 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 }
8160 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008161 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8162 // If an insert effect is idle and input buffer is different from output buffer,
8163 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008165 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008166 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8167 int16_t *in = mConfig.inputCfg.buffer.s16;
8168 int16_t *out = mConfig.outputCfg.buffer.s16;
8169 for (size_t i = 0; i < frameCnt; i++) {
8170 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 }
8173 }
8174}
8175
8176void AudioFlinger::EffectModule::reset_l()
8177{
8178 if (mEffectInterface == NULL) {
8179 return;
8180 }
8181 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8182}
8183
8184status_t AudioFlinger::EffectModule::configure()
8185{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 if (mEffectInterface == NULL) {
8187 return NO_INIT;
8188 }
8189
8190 sp<ThreadBase> thread = mThread.promote();
8191 if (thread == 0) {
8192 return DEAD_OBJECT;
8193 }
8194
8195 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008196 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008197
8198 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008199 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008201 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202 }
Glenn Kasten254af182012-07-03 14:59:05 -07008203 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008204 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8205 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 mConfig.inputCfg.samplingRate = thread->sampleRate();
8207 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8208 mConfig.inputCfg.bufferProvider.cookie = NULL;
8209 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8210 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8211 mConfig.outputCfg.bufferProvider.cookie = NULL;
8212 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8213 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8214 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8215 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008216 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008217 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 // - in other sessions:
8219 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8220 // other effect: overwrites output buffer: input buffer == output buffer
8221 // Auxiliary effect:
8222 // accumulates in output buffer: input buffer != output buffer
8223 // Therefore: accumulate <=> input buffer != output buffer
8224 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8225 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8226 } else {
8227 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8228 }
8229 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8230 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8231 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8232 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8233
Steve Block3856b092011-10-20 11:56:00 +01008234 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008235 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8236
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008238 uint32_t size = sizeof(int);
8239 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008240 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008241 sizeof(effect_config_t),
8242 &mConfig,
8243 &size,
8244 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 if (status == 0) {
8246 status = cmdStatus;
8247 }
8248
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008249 if (status == 0 &&
8250 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8251 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8252 effect_param_t *p = (effect_param_t *)buf32;
8253
8254 p->psize = sizeof(uint32_t);
8255 p->vsize = sizeof(uint32_t);
8256 size = sizeof(int);
8257 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8258
8259 uint32_t latency = 0;
8260 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8261 if (pbt != NULL) {
8262 latency = pbt->latency_l();
8263 }
8264
8265 *((int32_t *)p->data + 1)= latency;
8266 (*mEffectInterface)->command(mEffectInterface,
8267 EFFECT_CMD_SET_PARAM,
8268 sizeof(effect_param_t) + 8,
8269 &buf32,
8270 &size,
8271 &cmdStatus);
8272 }
8273
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8275 (1000 * mConfig.outputCfg.buffer.frameCount);
8276
8277 return status;
8278}
8279
8280status_t AudioFlinger::EffectModule::init()
8281{
8282 Mutex::Autolock _l(mLock);
8283 if (mEffectInterface == NULL) {
8284 return NO_INIT;
8285 }
8286 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008287 uint32_t size = sizeof(status_t);
8288 status_t status = (*mEffectInterface)->command(mEffectInterface,
8289 EFFECT_CMD_INIT,
8290 0,
8291 NULL,
8292 &size,
8293 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 if (status == 0) {
8295 status = cmdStatus;
8296 }
8297 return status;
8298}
8299
Eric Laurentec35a142011-10-05 17:42:25 -07008300status_t AudioFlinger::EffectModule::start()
8301{
8302 Mutex::Autolock _l(mLock);
8303 return start_l();
8304}
8305
Mathias Agopian65ab4712010-07-14 17:59:35 -07008306status_t AudioFlinger::EffectModule::start_l()
8307{
8308 if (mEffectInterface == NULL) {
8309 return NO_INIT;
8310 }
8311 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008312 uint32_t size = sizeof(status_t);
8313 status_t status = (*mEffectInterface)->command(mEffectInterface,
8314 EFFECT_CMD_ENABLE,
8315 0,
8316 NULL,
8317 &size,
8318 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319 if (status == 0) {
8320 status = cmdStatus;
8321 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008322 if (status == 0 &&
8323 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8324 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8325 sp<ThreadBase> thread = mThread.promote();
8326 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008327 audio_stream_t *stream = thread->stream();
8328 if (stream != NULL) {
8329 stream->add_audio_effect(stream, mEffectInterface);
8330 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008331 }
8332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008333 return status;
8334}
8335
Eric Laurentec437d82011-07-26 20:54:46 -07008336status_t AudioFlinger::EffectModule::stop()
8337{
8338 Mutex::Autolock _l(mLock);
8339 return stop_l();
8340}
8341
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342status_t AudioFlinger::EffectModule::stop_l()
8343{
8344 if (mEffectInterface == NULL) {
8345 return NO_INIT;
8346 }
8347 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008348 uint32_t size = sizeof(status_t);
8349 status_t status = (*mEffectInterface)->command(mEffectInterface,
8350 EFFECT_CMD_DISABLE,
8351 0,
8352 NULL,
8353 &size,
8354 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355 if (status == 0) {
8356 status = cmdStatus;
8357 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008358 if (status == 0 &&
8359 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8360 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8361 sp<ThreadBase> thread = mThread.promote();
8362 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008363 audio_stream_t *stream = thread->stream();
8364 if (stream != NULL) {
8365 stream->remove_audio_effect(stream, mEffectInterface);
8366 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008367 }
8368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008369 return status;
8370}
8371
Eric Laurent25f43952010-07-28 05:40:18 -07008372status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8373 uint32_t cmdSize,
8374 void *pCmdData,
8375 uint32_t *replySize,
8376 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377{
8378 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008379// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380
Eric Laurentec437d82011-07-26 20:54:46 -07008381 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 return NO_INIT;
8383 }
Eric Laurent25f43952010-07-28 05:40:18 -07008384 status_t status = (*mEffectInterface)->command(mEffectInterface,
8385 cmdCode,
8386 cmdSize,
8387 pCmdData,
8388 replySize,
8389 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008391 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008393 EffectHandle *h = mHandles[i];
8394 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8396 }
8397 }
8398 }
8399 return status;
8400}
8401
8402status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8403{
8404 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008405 return setEnabled_l(enabled);
8406}
8407
8408// must be called with EffectModule::mLock held
8409status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8410{
8411
Steve Block3856b092011-10-20 11:56:00 +01008412 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413
8414 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008415 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8416 if (enabled && status != NO_ERROR) {
8417 return status;
8418 }
8419
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420 switch (mState) {
8421 // going from disabled to enabled
8422 case IDLE:
8423 mState = STARTING;
8424 break;
8425 case STOPPED:
8426 mState = RESTART;
8427 break;
8428 case STOPPING:
8429 mState = ACTIVE;
8430 break;
8431
8432 // going from enabled to disabled
8433 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008434 mState = STOPPED;
8435 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 case STARTING:
8437 mState = IDLE;
8438 break;
8439 case ACTIVE:
8440 mState = STOPPING;
8441 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008442 case DESTROYED:
8443 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 }
8445 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008446 EffectHandle *h = mHandles[i];
8447 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008448 h->setEnabled(enabled);
8449 }
8450 }
8451 }
8452 return NO_ERROR;
8453}
8454
Glenn Kastenc59c0042012-02-02 14:06:11 -08008455bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456{
8457 switch (mState) {
8458 case RESTART:
8459 case STARTING:
8460 case ACTIVE:
8461 return true;
8462 case IDLE:
8463 case STOPPING:
8464 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008465 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466 default:
8467 return false;
8468 }
8469}
8470
Glenn Kastenc59c0042012-02-02 14:06:11 -08008471bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008472{
8473 switch (mState) {
8474 case RESTART:
8475 case ACTIVE:
8476 case STOPPING:
8477 case STOPPED:
8478 return true;
8479 case IDLE:
8480 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008481 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008482 default:
8483 return false;
8484 }
8485}
8486
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8488{
8489 Mutex::Autolock _l(mLock);
8490 status_t status = NO_ERROR;
8491
8492 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8493 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008494 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008495 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8496 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497 status_t cmdStatus;
8498 uint32_t volume[2];
8499 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008500 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501 volume[0] = *left;
8502 volume[1] = *right;
8503 if (controller) {
8504 pVolume = volume;
8505 }
Eric Laurent25f43952010-07-28 05:40:18 -07008506 status = (*mEffectInterface)->command(mEffectInterface,
8507 EFFECT_CMD_SET_VOLUME,
8508 size,
8509 volume,
8510 &size,
8511 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8513 *left = volume[0];
8514 *right = volume[1];
8515 }
8516 }
8517 return status;
8518}
8519
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008520status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521{
8522 Mutex::Autolock _l(mLock);
8523 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008524 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8525 // audio pre processing modules on RecordThread can receive both output and
8526 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008527 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008528 if (dev) {
8529 status_t cmdStatus;
8530 uint32_t size = sizeof(status_t);
8531
8532 status = (*mEffectInterface)->command(mEffectInterface,
8533 EFFECT_CMD_SET_DEVICE,
8534 sizeof(uint32_t),
8535 &dev,
8536 &size,
8537 &cmdStatus);
8538 if (status == NO_ERROR) {
8539 status = cmdStatus;
8540 }
8541 }
8542 dev = device & AUDIO_DEVICE_IN_ALL;
8543 if (dev) {
8544 status_t cmdStatus;
8545 uint32_t size = sizeof(status_t);
8546
8547 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8548 EFFECT_CMD_SET_INPUT_DEVICE,
8549 sizeof(uint32_t),
8550 &dev,
8551 &size,
8552 &cmdStatus);
8553 if (status2 == NO_ERROR) {
8554 status2 = cmdStatus;
8555 }
8556 if (status == NO_ERROR) {
8557 status = status2;
8558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008559 }
8560 }
8561 return status;
8562}
8563
Glenn Kastenf78aee72012-01-04 11:00:47 -08008564status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565{
8566 Mutex::Autolock _l(mLock);
8567 status_t status = NO_ERROR;
8568 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008570 uint32_t size = sizeof(status_t);
8571 status = (*mEffectInterface)->command(mEffectInterface,
8572 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008573 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008574 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008575 &size,
8576 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577 if (status == NO_ERROR) {
8578 status = cmdStatus;
8579 }
8580 }
8581 return status;
8582}
8583
Eric Laurent59255e42011-07-27 19:49:51 -07008584void AudioFlinger::EffectModule::setSuspended(bool suspended)
8585{
8586 Mutex::Autolock _l(mLock);
8587 mSuspended = suspended;
8588}
Glenn Kastena3a85482012-01-04 11:01:11 -08008589
8590bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008591{
8592 Mutex::Autolock _l(mLock);
8593 return mSuspended;
8594}
8595
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008596bool AudioFlinger::EffectModule::purgeHandles()
8597{
8598 bool enabled = false;
8599 Mutex::Autolock _l(mLock);
8600 for (size_t i = 0; i < mHandles.size(); i++) {
8601 EffectHandle *handle = mHandles[i];
8602 if (handle != NULL && !handle->destroyed_l()) {
8603 handle->effect().clear();
8604 if (handle->hasControl()) {
8605 enabled = handle->enabled();
8606 }
8607 }
8608 }
8609 return enabled;
8610}
8611
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008612void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008613{
8614 const size_t SIZE = 256;
8615 char buffer[SIZE];
8616 String8 result;
8617
8618 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8619 result.append(buffer);
8620
8621 bool locked = tryLock(mLock);
8622 // failed to lock - AudioFlinger is probably deadlocked
8623 if (!locked) {
8624 result.append("\t\tCould not lock Fx mutex:\n");
8625 }
8626
8627 result.append("\t\tSession Status State Engine:\n");
8628 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8629 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8630 result.append(buffer);
8631
8632 result.append("\t\tDescriptor:\n");
8633 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8634 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8635 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8636 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8637 result.append(buffer);
8638 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8639 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8640 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8641 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8642 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008643 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644 mDescriptor.apiVersion,
8645 mDescriptor.flags);
8646 result.append(buffer);
8647 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8648 mDescriptor.name);
8649 result.append(buffer);
8650 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8651 mDescriptor.implementor);
8652 result.append(buffer);
8653
8654 result.append("\t\t- Input configuration:\n");
8655 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8656 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8657 (uint32_t)mConfig.inputCfg.buffer.raw,
8658 mConfig.inputCfg.buffer.frameCount,
8659 mConfig.inputCfg.samplingRate,
8660 mConfig.inputCfg.channels,
8661 mConfig.inputCfg.format);
8662 result.append(buffer);
8663
8664 result.append("\t\t- Output configuration:\n");
8665 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8666 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8667 (uint32_t)mConfig.outputCfg.buffer.raw,
8668 mConfig.outputCfg.buffer.frameCount,
8669 mConfig.outputCfg.samplingRate,
8670 mConfig.outputCfg.channels,
8671 mConfig.outputCfg.format);
8672 result.append(buffer);
8673
8674 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8675 result.append(buffer);
8676 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8677 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008678 EffectHandle *handle = mHandles[i];
8679 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680 handle->dump(buffer, SIZE);
8681 result.append(buffer);
8682 }
8683 }
8684
8685 result.append("\n");
8686
8687 write(fd, result.string(), result.length());
8688
8689 if (locked) {
8690 mLock.unlock();
8691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008692}
8693
8694// ----------------------------------------------------------------------------
8695// EffectHandle implementation
8696// ----------------------------------------------------------------------------
8697
8698#undef LOG_TAG
8699#define LOG_TAG "AudioFlinger::EffectHandle"
8700
8701AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8702 const sp<AudioFlinger::Client>& client,
8703 const sp<IEffectClient>& effectClient,
8704 int32_t priority)
8705 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008706 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008707 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708{
Steve Block3856b092011-10-20 11:56:00 +01008709 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008710
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008711 if (client == 0) {
8712 return;
8713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8715 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8716 if (mCblkMemory != 0) {
8717 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8718
Glenn Kastena0d68332012-01-27 16:47:15 -08008719 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720 new(mCblk) effect_param_cblk_t();
8721 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008724 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 return;
8726 }
8727}
8728
8729AudioFlinger::EffectHandle::~EffectHandle()
8730{
Steve Block3856b092011-10-20 11:56:00 +01008731 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008732
8733 if (mEffect == 0) {
8734 mDestroyed = true;
8735 return;
8736 }
8737 mEffect->lock();
8738 mDestroyed = true;
8739 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008740 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741}
8742
8743status_t AudioFlinger::EffectHandle::enable()
8744{
Steve Block3856b092011-10-20 11:56:00 +01008745 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 if (!mHasControl) return INVALID_OPERATION;
8747 if (mEffect == 0) return DEAD_OBJECT;
8748
Eric Laurentdb7c0792011-08-10 10:37:50 -07008749 if (mEnabled) {
8750 return NO_ERROR;
8751 }
8752
Eric Laurent59255e42011-07-27 19:49:51 -07008753 mEnabled = true;
8754
8755 sp<ThreadBase> thread = mEffect->thread().promote();
8756 if (thread != 0) {
8757 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8758 }
8759
8760 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8761 if (mEffect->suspended()) {
8762 return NO_ERROR;
8763 }
8764
Eric Laurentdb7c0792011-08-10 10:37:50 -07008765 status_t status = mEffect->setEnabled(true);
8766 if (status != NO_ERROR) {
8767 if (thread != 0) {
8768 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8769 }
8770 mEnabled = false;
8771 }
8772 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008773}
8774
8775status_t AudioFlinger::EffectHandle::disable()
8776{
Steve Block3856b092011-10-20 11:56:00 +01008777 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008778 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008779 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780
Eric Laurentdb7c0792011-08-10 10:37:50 -07008781 if (!mEnabled) {
8782 return NO_ERROR;
8783 }
Eric Laurent59255e42011-07-27 19:49:51 -07008784 mEnabled = false;
8785
8786 if (mEffect->suspended()) {
8787 return NO_ERROR;
8788 }
8789
8790 status_t status = mEffect->setEnabled(false);
8791
8792 sp<ThreadBase> thread = mEffect->thread().promote();
8793 if (thread != 0) {
8794 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8795 }
8796
8797 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798}
8799
8800void AudioFlinger::EffectHandle::disconnect()
8801{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008802 disconnect(true);
8803}
8804
Glenn Kasten58123c32012-02-03 10:32:24 -08008805void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008806{
Glenn Kasten58123c32012-02-03 10:32:24 -08008807 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808 if (mEffect == 0) {
8809 return;
8810 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008811 // restore suspended effects if the disconnected handle was enabled and the last one.
8812 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008813 sp<ThreadBase> thread = mEffect->thread().promote();
8814 if (thread != 0) {
8815 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8816 }
Eric Laurent59255e42011-07-27 19:49:51 -07008817 }
8818
Mathias Agopian65ab4712010-07-14 17:59:35 -07008819 // release sp on module => module destructor can be called now
8820 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008822 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008823 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008824 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8825 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008826 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008827 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008828 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8829 mClient.clear();
8830 }
8831}
8832
Eric Laurent25f43952010-07-28 05:40:18 -07008833status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8834 uint32_t cmdSize,
8835 void *pCmdData,
8836 uint32_t *replySize,
8837 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838{
Steve Block3856b092011-10-20 11:56:00 +01008839// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008840// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008841
8842 // only get parameter command is permitted for applications not controlling the effect
8843 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8844 return INVALID_OPERATION;
8845 }
8846 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008847 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008848
8849 // handle commands that are not forwarded transparently to effect engine
8850 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8851 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8852 // no risk to block the whole media server process or mixer threads is we are stuck here
8853 Mutex::Autolock _l(mCblk->lock);
8854 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8855 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8856 mCblk->serverIndex = 0;
8857 mCblk->clientIndex = 0;
8858 return BAD_VALUE;
8859 }
8860 status_t status = NO_ERROR;
8861 while (mCblk->serverIndex < mCblk->clientIndex) {
8862 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008863 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008864 int *p = (int *)(mBuffer + mCblk->serverIndex);
8865 int size = *p++;
8866 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008867 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868 break;
8869 }
8870 effect_param_t *param = (effect_param_t *)p;
8871 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008872 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873 mCblk->serverIndex += size;
8874 continue;
8875 }
Eric Laurent25f43952010-07-28 05:40:18 -07008876 uint32_t psize = sizeof(effect_param_t) +
8877 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8878 param->vsize;
8879 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8880 psize,
8881 p,
8882 &rsize,
8883 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008884 // stop at first error encountered
8885 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008886 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008887 *(int *)pReplyData = reply;
8888 break;
8889 } else if (reply != NO_ERROR) {
8890 *(int *)pReplyData = reply;
8891 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 }
8893 mCblk->serverIndex += size;
8894 }
8895 mCblk->serverIndex = 0;
8896 mCblk->clientIndex = 0;
8897 return status;
8898 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008899 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008900 return enable();
8901 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008902 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 return disable();
8904 }
8905
8906 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8907}
8908
Eric Laurent59255e42011-07-27 19:49:51 -07008909void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008910{
Steve Block3856b092011-10-20 11:56:00 +01008911 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912
8913 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008914 mEnabled = enabled;
8915
Mathias Agopian65ab4712010-07-14 17:59:35 -07008916 if (signal && mEffectClient != 0) {
8917 mEffectClient->controlStatusChanged(hasControl);
8918 }
8919}
8920
Eric Laurent25f43952010-07-28 05:40:18 -07008921void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8922 uint32_t cmdSize,
8923 void *pCmdData,
8924 uint32_t replySize,
8925 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926{
8927 if (mEffectClient != 0) {
8928 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8929 }
8930}
8931
8932
8933
8934void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8935{
8936 if (mEffectClient != 0) {
8937 mEffectClient->enableStatusChanged(enabled);
8938 }
8939}
8940
8941status_t AudioFlinger::EffectHandle::onTransact(
8942 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8943{
8944 return BnEffect::onTransact(code, data, reply, flags);
8945}
8946
8947
8948void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8949{
Glenn Kastena0d68332012-01-27 16:47:15 -08008950 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951
8952 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008953 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008954 mPriority,
8955 mHasControl,
8956 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008957 mCblk ? mCblk->clientIndex : 0,
8958 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959 );
8960
8961 if (locked) {
8962 mCblk->lock.unlock();
8963 }
8964}
8965
8966#undef LOG_TAG
8967#define LOG_TAG "AudioFlinger::EffectChain"
8968
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008969AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008971 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008972 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8973 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974{
Dima Zavinfce7a472011-04-19 22:30:36 -07008975 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008976 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008977 return;
8978 }
8979 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8980 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008981}
8982
8983AudioFlinger::EffectChain::~EffectChain()
8984{
8985 if (mOwnInBuffer) {
8986 delete mInBuffer;
8987 }
8988
8989}
8990
Eric Laurent59255e42011-07-27 19:49:51 -07008991// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008992sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994 size_t size = mEffects.size();
8995
8996 for (size_t i = 0; i < size; i++) {
8997 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008998 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008999 }
9000 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009001 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002}
9003
Eric Laurent59255e42011-07-27 19:49:51 -07009004// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009005sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009007 size_t size = mEffects.size();
9008
9009 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009010 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9011 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009012 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013 }
9014 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009015 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016}
9017
Eric Laurent59255e42011-07-27 19:49:51 -07009018// getEffectFromType_l() must be called with ThreadBase::mLock held
9019sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9020 const effect_uuid_t *type)
9021{
Eric Laurent59255e42011-07-27 19:49:51 -07009022 size_t size = mEffects.size();
9023
9024 for (size_t i = 0; i < size; i++) {
9025 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009026 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009027 }
9028 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009029 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009030}
9031
Eric Laurent91b14c42012-05-30 12:30:29 -07009032void AudioFlinger::EffectChain::clearInputBuffer()
9033{
9034 Mutex::Autolock _l(mLock);
9035 sp<ThreadBase> thread = mThread.promote();
9036 if (thread == 0) {
9037 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9038 return;
9039 }
9040 clearInputBuffer_l(thread);
9041}
9042
9043// Must be called with EffectChain::mLock locked
9044void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9045{
9046 size_t numSamples = thread->frameCount() * thread->channelCount();
9047 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9048
9049}
9050
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051// Must be called with EffectChain::mLock locked
9052void AudioFlinger::EffectChain::process_l()
9053{
Eric Laurentdac69112010-09-28 14:09:57 -07009054 sp<ThreadBase> thread = mThread.promote();
9055 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009056 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009057 return;
9058 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009059 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9060 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009061 // always process effects unless no more tracks are on the session and the effect tail
9062 // has been rendered
9063 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009064 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009065 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009066
Eric Laurent544fe9b2011-11-11 15:42:52 -08009067 if (!tracksOnSession && mTailBufferCount == 0) {
9068 doProcess = false;
9069 }
9070
9071 if (activeTrackCnt() == 0) {
9072 // if no track is active and the effect tail has not been rendered,
9073 // the input buffer must be cleared here as the mixer process will not do it
9074 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009075 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009076 if (mTailBufferCount > 0) {
9077 mTailBufferCount--;
9078 }
9079 }
9080 }
Eric Laurentdac69112010-09-28 14:09:57 -07009081 }
9082
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009084 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009085 for (size_t i = 0; i < size; i++) {
9086 mEffects[i]->process();
9087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009088 }
9089 for (size_t i = 0; i < size; i++) {
9090 mEffects[i]->updateState();
9091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009092}
9093
Eric Laurentcab11242010-07-15 12:50:15 -07009094// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009095status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009096{
9097 effect_descriptor_t desc = effect->desc();
9098 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9099
9100 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009101 effect->setChain(this);
9102 sp<ThreadBase> thread = mThread.promote();
9103 if (thread == 0) {
9104 return NO_INIT;
9105 }
9106 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009107
9108 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9109 // Auxiliary effects are inserted at the beginning of mEffects vector as
9110 // they are processed first and accumulated in chain input buffer
9111 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009112
Mathias Agopian65ab4712010-07-14 17:59:35 -07009113 // the input buffer for auxiliary effect contains mono samples in
9114 // 32 bit format. This is to avoid saturation in AudoMixer
9115 // accumulation stage. Saturation is done in EffectModule::process() before
9116 // calling the process in effect engine
9117 size_t numSamples = thread->frameCount();
9118 int32_t *buffer = new int32_t[numSamples];
9119 memset(buffer, 0, numSamples * sizeof(int32_t));
9120 effect->setInBuffer((int16_t *)buffer);
9121 // auxiliary effects output samples to chain input buffer for further processing
9122 // by insert effects
9123 effect->setOutBuffer(mInBuffer);
9124 } else {
9125 // Insert effects are inserted at the end of mEffects vector as they are processed
9126 // after track and auxiliary effects.
9127 // Insert effect order as a function of indicated preference:
9128 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9129 // another effect is present
9130 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9131 // last effect claiming first position
9132 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9133 // first effect claiming last position
9134 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9135 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9136 // already present
9137
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009138 size_t size = mEffects.size();
9139 size_t idx_insert = size;
9140 ssize_t idx_insert_first = -1;
9141 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009143 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009144 effect_descriptor_t d = mEffects[i]->desc();
9145 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9146 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9147 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9148 // check invalid effect chaining combinations
9149 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9150 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009151 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152 return INVALID_OPERATION;
9153 }
9154 // remember position of first insert effect and by default
9155 // select this as insert position for new effect
9156 if (idx_insert == size) {
9157 idx_insert = i;
9158 }
9159 // remember position of last insert effect claiming
9160 // first position
9161 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9162 idx_insert_first = i;
9163 }
9164 // remember position of first insert effect claiming
9165 // last position
9166 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9167 idx_insert_last == -1) {
9168 idx_insert_last = i;
9169 }
9170 }
9171 }
9172
9173 // modify idx_insert from first position if needed
9174 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9175 if (idx_insert_last != -1) {
9176 idx_insert = idx_insert_last;
9177 } else {
9178 idx_insert = size;
9179 }
9180 } else {
9181 if (idx_insert_first != -1) {
9182 idx_insert = idx_insert_first + 1;
9183 }
9184 }
9185
9186 // always read samples from chain input buffer
9187 effect->setInBuffer(mInBuffer);
9188
9189 // if last effect in the chain, output samples to chain
9190 // output buffer, otherwise to chain input buffer
9191 if (idx_insert == size) {
9192 if (idx_insert != 0) {
9193 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9194 mEffects[idx_insert-1]->configure();
9195 }
9196 effect->setOutBuffer(mOutBuffer);
9197 } else {
9198 effect->setOutBuffer(mInBuffer);
9199 }
9200 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201
Steve Block3856b092011-10-20 11:56:00 +01009202 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009203 }
9204 effect->configure();
9205 return NO_ERROR;
9206}
9207
Eric Laurentcab11242010-07-15 12:50:15 -07009208// removeEffect_l() must be called with PlaybackThread::mLock held
9209size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210{
9211 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009212 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9214
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009215 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009216 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009217 // calling stop here will remove pre-processing effect from the audio HAL.
9218 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9219 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009220 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9221 mEffects[i]->state() == EffectModule::STOPPING) {
9222 mEffects[i]->stop();
9223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9225 delete[] effect->inBuffer();
9226 } else {
9227 if (i == size - 1 && i != 0) {
9228 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9229 mEffects[i - 1]->configure();
9230 }
9231 }
9232 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009233 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 break;
9235 }
9236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237
9238 return mEffects.size();
9239}
9240
Eric Laurentcab11242010-07-15 12:50:15 -07009241// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009242void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009243{
9244 size_t size = mEffects.size();
9245 for (size_t i = 0; i < size; i++) {
9246 mEffects[i]->setDevice(device);
9247 }
9248}
9249
Eric Laurentcab11242010-07-15 12:50:15 -07009250// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009251void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252{
9253 size_t size = mEffects.size();
9254 for (size_t i = 0; i < size; i++) {
9255 mEffects[i]->setMode(mode);
9256 }
9257}
9258
Eric Laurentcab11242010-07-15 12:50:15 -07009259// setVolume_l() must be called with PlaybackThread::mLock held
9260bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009261{
9262 uint32_t newLeft = *left;
9263 uint32_t newRight = *right;
9264 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009265 int ctrlIdx = -1;
9266 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009267
Eric Laurentcab11242010-07-15 12:50:15 -07009268 // first update volume controller
9269 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009270 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009271 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9272 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009273 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009274 break;
9275 }
9276 }
9277
9278 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009279 if (hasControl) {
9280 *left = mNewLeftVolume;
9281 *right = mNewRightVolume;
9282 }
9283 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009284 }
9285
9286 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009287 mLeftVolume = newLeft;
9288 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009289
9290 // second get volume update from volume controller
9291 if (ctrlIdx >= 0) {
9292 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009293 mNewLeftVolume = newLeft;
9294 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009295 }
9296 // then indicate volume to all other effects in chain.
9297 // Pass altered volume to effects before volume controller
9298 // and requested volume to effects after controller
9299 uint32_t lVol = newLeft;
9300 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009301
Mathias Agopian65ab4712010-07-14 17:59:35 -07009302 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009303 if ((int)i == ctrlIdx) continue;
9304 // this also works for ctrlIdx == -1 when there is no volume controller
9305 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009306 lVol = *left;
9307 rVol = *right;
9308 }
9309 mEffects[i]->setVolume(&lVol, &rVol, false);
9310 }
9311 *left = newLeft;
9312 *right = newRight;
9313
9314 return hasControl;
9315}
9316
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009317void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009318{
9319 const size_t SIZE = 256;
9320 char buffer[SIZE];
9321 String8 result;
9322
9323 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9324 result.append(buffer);
9325
9326 bool locked = tryLock(mLock);
9327 // failed to lock - AudioFlinger is probably deadlocked
9328 if (!locked) {
9329 result.append("\tCould not lock mutex:\n");
9330 }
9331
Eric Laurentcab11242010-07-15 12:50:15 -07009332 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9333 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009334 mEffects.size(),
9335 (uint32_t)mInBuffer,
9336 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009337 mActiveTrackCnt);
9338 result.append(buffer);
9339 write(fd, result.string(), result.size());
9340
9341 for (size_t i = 0; i < mEffects.size(); ++i) {
9342 sp<EffectModule> effect = mEffects[i];
9343 if (effect != 0) {
9344 effect->dump(fd, args);
9345 }
9346 }
9347
9348 if (locked) {
9349 mLock.unlock();
9350 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009351}
9352
Eric Laurent59255e42011-07-27 19:49:51 -07009353// must be called with ThreadBase::mLock held
9354void AudioFlinger::EffectChain::setEffectSuspended_l(
9355 const effect_uuid_t *type, bool suspend)
9356{
9357 sp<SuspendedEffectDesc> desc;
9358 // use effect type UUID timelow as key as there is no real risk of identical
9359 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009360 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009361 if (suspend) {
9362 if (index >= 0) {
9363 desc = mSuspendedEffects.valueAt(index);
9364 } else {
9365 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009366 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009367 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009368 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009369 }
9370 if (desc->mRefCount++ == 0) {
9371 sp<EffectModule> effect = getEffectIfEnabled(type);
9372 if (effect != 0) {
9373 desc->mEffect = effect;
9374 effect->setSuspended(true);
9375 effect->setEnabled(false);
9376 }
9377 }
9378 } else {
9379 if (index < 0) {
9380 return;
9381 }
9382 desc = mSuspendedEffects.valueAt(index);
9383 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009384 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009385 desc->mRefCount = 1;
9386 }
9387 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009388 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009389 if (desc->mEffect != 0) {
9390 sp<EffectModule> effect = desc->mEffect.promote();
9391 if (effect != 0) {
9392 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009393 effect->lock();
9394 EffectHandle *handle = effect->controlHandle_l();
9395 if (handle != NULL && !handle->destroyed_l()) {
9396 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009397 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009398 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009399 }
9400 desc->mEffect.clear();
9401 }
9402 mSuspendedEffects.removeItemsAt(index);
9403 }
9404 }
9405}
9406
9407// must be called with ThreadBase::mLock held
9408void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9409{
9410 sp<SuspendedEffectDesc> desc;
9411
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009412 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009413 if (suspend) {
9414 if (index >= 0) {
9415 desc = mSuspendedEffects.valueAt(index);
9416 } else {
9417 desc = new SuspendedEffectDesc();
9418 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009419 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009420 }
9421 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009422 Vector< sp<EffectModule> > effects;
9423 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009424 for (size_t i = 0; i < effects.size(); i++) {
9425 setEffectSuspended_l(&effects[i]->desc().type, true);
9426 }
9427 }
9428 } else {
9429 if (index < 0) {
9430 return;
9431 }
9432 desc = mSuspendedEffects.valueAt(index);
9433 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009434 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009435 desc->mRefCount = 1;
9436 }
9437 if (--desc->mRefCount == 0) {
9438 Vector<const effect_uuid_t *> types;
9439 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9440 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9441 continue;
9442 }
9443 types.add(&mSuspendedEffects.valueAt(i)->mType);
9444 }
9445 for (size_t i = 0; i < types.size(); i++) {
9446 setEffectSuspended_l(types[i], false);
9447 }
Steve Block3856b092011-10-20 11:56:00 +01009448 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009449 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9450 }
9451 }
9452}
9453
Eric Laurent6bffdb82011-09-23 08:40:41 -07009454
9455// The volume effect is used for automated tests only
9456#ifndef OPENSL_ES_H_
9457static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9458 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9459const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9460#endif //OPENSL_ES_H_
9461
Eric Laurentdb7c0792011-08-10 10:37:50 -07009462bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9463{
9464 // auxiliary effects and visualizer are never suspended on output mix
9465 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9466 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009467 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9468 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009469 return false;
9470 }
9471 return true;
9472}
9473
Glenn Kastend0539712012-01-30 12:56:03 -08009474void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009475{
Glenn Kastend0539712012-01-30 12:56:03 -08009476 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009477 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009478 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9479 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009480 }
Eric Laurent59255e42011-07-27 19:49:51 -07009481 }
Eric Laurent59255e42011-07-27 19:49:51 -07009482}
9483
9484sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9485 const effect_uuid_t *type)
9486{
Glenn Kasten090f0192012-01-30 13:00:02 -08009487 sp<EffectModule> effect = getEffectFromType_l(type);
9488 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009489}
9490
9491void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9492 bool enabled)
9493{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009494 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009495 if (enabled) {
9496 if (index < 0) {
9497 // if the effect is not suspend check if all effects are suspended
9498 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9499 if (index < 0) {
9500 return;
9501 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009502 if (!isEffectEligibleForSuspend(effect->desc())) {
9503 return;
9504 }
Eric Laurent59255e42011-07-27 19:49:51 -07009505 setEffectSuspended_l(&effect->desc().type, enabled);
9506 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009507 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009508 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009509 return;
9510 }
Eric Laurent59255e42011-07-27 19:49:51 -07009511 }
Steve Block3856b092011-10-20 11:56:00 +01009512 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009513 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009514 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9515 // if effect is requested to suspended but was not yet enabled, supend it now.
9516 if (desc->mEffect == 0) {
9517 desc->mEffect = effect;
9518 effect->setEnabled(false);
9519 effect->setSuspended(true);
9520 }
9521 } else {
9522 if (index < 0) {
9523 return;
9524 }
Steve Block3856b092011-10-20 11:56:00 +01009525 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009526 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009527 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9528 desc->mEffect.clear();
9529 effect->setSuspended(false);
9530 }
9531}
9532
Mathias Agopian65ab4712010-07-14 17:59:35 -07009533#undef LOG_TAG
9534#define LOG_TAG "AudioFlinger"
9535
9536// ----------------------------------------------------------------------------
9537
9538status_t AudioFlinger::onTransact(
9539 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9540{
9541 return BnAudioFlinger::onTransact(code, data, reply, flags);
9542}
9543
Mathias Agopian65ab4712010-07-14 17:59:35 -07009544}; // namespace android