blob: c7fbb09a19abdddfd5885ed158b9a53ae5d39889 [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
vivek mehta2192bc92012-12-04 11:46:08 -08004** Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
5**
6** Copyright (c) 2012, The Linux Foundation. All rights reserved.
7** Not a Contribution, Apache license notifications and license are retained
8** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07009**
10** Licensed under the Apache License, Version 2.0 (the "License");
11** you may not use this file except in compliance with the License.
12** You may obtain a copy of the License at
13**
14** http://www.apache.org/licenses/LICENSE-2.0
15**
16** Unless required by applicable law or agreed to in writing, software
17** distributed under the License is distributed on an "AS IS" BASIS,
18** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19** See the License for the specific language governing permissions and
20** limitations under the License.
21*/
22
23
24#define LOG_TAG "AudioFlinger"
25//#define LOG_NDEBUG 0
26
27#include <math.h>
28#include <signal.h>
29#include <sys/time.h>
30#include <sys/resource.h>
31
Gloria Wang9ee159b2011-02-24 14:51:45 -080032#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/IServiceManager.h>
34#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070035#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
38#include <utils/String16.h>
39#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070040#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041
Dima Zavinfce7a472011-04-19 22:30:36 -070042#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080044#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#undef ADD_BATTERY_DATA
47
48#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080049#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080050#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070051#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include <private/media/AudioTrackShared.h>
54#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070057#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59#include "AudioMixer.h"
60#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080061#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070064#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070065#include <audio_effects/effect_ns.h>
66#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
Glenn Kasten3b21c502011-12-15 09:52:39 -080068#include <audio_utils/primitives.h>
69
Eric Laurentfeb0db62011-07-22 09:04:31 -070070#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080071
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070077
John Grossman4ff14ba2012-02-08 16:37:41 -080078#include <common_time/cc_helper.h>
79#include <common_time/local_clock.h>
80
Glenn Kasten58912562012-04-03 10:45:00 -070081#include "FastMixer.h"
82
83// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070084#include <media/nbaio/AudioStreamOutSink.h>
85#include <media/nbaio/MonoPipe.h>
86#include <media/nbaio/MonoPipeReader.h>
87#include <media/nbaio/Pipe.h>
88#include <media/nbaio/PipeReader.h>
89#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070090
Glenn Kasten1dc28b72012-04-24 10:01:03 -070091#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070092
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
John Grossman1c345192012-03-27 14:00:17 -070095// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
Eric Laurentde070132010-07-13 04:45:46 -0700107
vivek mehta2192bc92012-12-04 11:46:08 -0800108#ifdef QCOM_HARDWARE
109#define DIRECT_TRACK_EOS 1
110static const char lockName[] = "DirectTrack";
111#endif
112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113namespace android {
114
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800115static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
116static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800119static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121// retry counts for buffer fill timeout
122// 50 * ~20msecs = 1 second
123static const int8_t kMaxTrackRetries = 50;
124static const int8_t kMaxTrackStartupRetries = 50;
125// allow less retry attempts on direct output thread.
126// direct outputs can be a scarce resource in audio hardware and should
127// be released as quickly as possible.
128static const int8_t kMaxTrackRetriesDirect = 2;
129
130static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800131static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700132
Glenn Kasten7dede872011-12-13 11:04:14 -0800133// don't warn about blocked writes or record buffer overflows more often than this
134static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700136// RecordThread loop sleep time upon application overrun or audio HAL read error
137static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138
Glenn Kasten7dede872011-12-13 11:04:14 -0800139// maximum time to wait for setParameters to complete
140static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700141
Eric Laurent7cafbb32011-11-22 18:50:29 -0800142// minimum sleep time for the mixer thread loop when tracks are active but in underrun
143static const uint32_t kMinThreadSleepTimeUs = 5000;
144// maximum divider applied to the active sleep time in the mixer thread loop
145static const uint32_t kMaxThreadSleepTimeShift = 2;
146
Glenn Kasten58912562012-04-03 10:45:00 -0700147// minimum normal mix buffer size, expressed in milliseconds rather than frames
148static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700149// maximum normal mix buffer size
150static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700151
John Grossman4ff14ba2012-02-08 16:37:41 -0800152nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800153
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700160 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700162 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700171static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
172 // AudioFlinger::setParameters() updates, other threads read w/o lock
173
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700174// Priorities for requestPriority
175static const int kPriorityAudioApp = 2;
176static const int kPriorityFastMixer = 3;
177
Glenn Kasten3ed29202012-08-07 15:24:44 -0700178// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
179// for the track. The client then sub-divides this into smaller buffers for its use.
180// Currently the client uses double-buffering by default, but doesn't tell us about that.
181// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700182// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
183// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700184// See the client's minBufCount and mNotificationFramesAct calculations for details.
185static const int kFastTrackMultiplier = 2;
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700189#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800190// To collect the amplifier usage
191static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800192 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
193 if (service == NULL) {
194 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800195 return;
196 }
197
198 service->addBatteryData(params);
199}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700200#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800201
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700203{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700204 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 int rc;
206
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700207 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
208 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
209 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
210 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700212 }
213 rc = audio_hw_device_open(mod, dev);
214 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
215 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
216 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700218 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000219#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700220 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
221 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
222 rc = BAD_VALUE;
223 goto out;
224 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100225#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 return 0;
227
228out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 *dev = NULL;
230 return rc;
231}
232
vivek mehta2192bc92012-12-04 11:46:08 -0800233static uint32_t getInputChannelCount(uint32_t channels) {
234#ifdef QCOM_HARDWARE
235 // only mono or stereo and 5.1 are supported for input sources
236 return popcount((channels) & (AUDIO_CHANNEL_IN_STEREO | AUDIO_CHANNEL_IN_MONO | AUDIO_CHANNEL_IN_5POINT1));
237#else
238 return popcount(channels);
239#endif
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241// ----------------------------------------------------------------------------
242
243AudioFlinger::AudioFlinger()
244 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800245 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700246 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800248 mMasterMute(false),
249 mNextUniqueId(1),
250 mMode(AUDIO_MODE_INVALID),
251 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700253}
254
255void AudioFlinger::onFirstRef()
256{
Dima Zavin799a70e2011-04-18 16:57:27 -0700257 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700258
Eric Laurent93575202011-01-18 18:39:02 -0800259 Mutex::Autolock _l(mLock);
260
Dima Zavin799a70e2011-04-18 16:57:27 -0700261 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800262#ifdef QCOM_HARDWARE
263 mLPASessionId = -2; // -2 is invalid session ID
264 mIsEffectConfigChanged = false;
265 mLPAEffectChain = NULL;
266#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800267 char val_str[PROPERTY_VALUE_MAX] = { 0 };
268 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
269 uint32_t int_val;
270 if (1 == sscanf(val_str, "%u", &int_val)) {
271 mStandbyTimeInNsecs = milliseconds(int_val);
272 ALOGI("Using %u mSec as standby time.", int_val);
273 } else {
274 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
275 ALOGI("Using default %u mSec as standby time.",
276 (uint32_t)(mStandbyTimeInNsecs / 1000000));
277 }
278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281}
282
283AudioFlinger::~AudioFlinger()
284{
285 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700286 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700287 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700288 }
289 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700290 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700291 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700292 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700293
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800294 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
295 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
297 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298 }
299}
300
Eric Laurenta4c5a552012-03-29 10:12:40 -0700301static const char * const audio_interfaces[] = {
302 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
303 AUDIO_HARDWARE_MODULE_ID_A2DP,
304 AUDIO_HARDWARE_MODULE_ID_USB,
305};
306#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
307
John Grossmanee578c02012-07-23 17:05:46 -0700308AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
309 audio_module_handle_t module,
310 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700311{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700312 // if module is 0, the request comes from an old policy manager and we should load
313 // well known modules
314 if (module == 0) {
315 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
316 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
317 loadHwModule_l(audio_interfaces[i]);
318 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700319 // then try to find a module supporting the requested device.
320 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
321 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
322 audio_hw_device_t *dev = audioHwDevice->hwDevice();
323 if ((dev->get_supported_devices != NULL) &&
324 (dev->get_supported_devices(dev) & devices) == devices)
325 return audioHwDevice;
326 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700327 } else {
328 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700329 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
330 if (audioHwDevice != NULL) {
331 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700332 }
333 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700334
Dima Zavin799a70e2011-04-18 16:57:27 -0700335 return NULL;
336}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700338void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
343
344 result.append("Clients:\n");
345 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800346 sp<Client> client = mClients.valueAt(i).promote();
347 if (client != 0) {
348 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
349 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 }
351 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700352
353 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800354 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700355 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
356 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800357 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700358 result.append(buffer);
359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361}
362
363
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700364void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365{
366 const size_t SIZE = 256;
367 char buffer[SIZE];
368 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800369 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370
John Grossman4ff14ba2012-02-08 16:37:41 -0800371 snprintf(buffer, SIZE, "Hardware status: %d\n"
372 "Standby Time mSec: %u\n",
373 hardwareStatus,
374 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 result.append(buffer);
376 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377}
378
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700379void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380{
381 const size_t SIZE = 256;
382 char buffer[SIZE];
383 String8 result;
384 snprintf(buffer, SIZE, "Permission Denial: "
385 "can't dump AudioFlinger from pid=%d, uid=%d\n",
386 IPCThreadState::self()->getCallingPid(),
387 IPCThreadState::self()->getCallingUid());
388 result.append(buffer);
389 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390}
391
392static bool tryLock(Mutex& mutex)
393{
394 bool locked = false;
395 for (int i = 0; i < kDumpLockRetries; ++i) {
396 if (mutex.tryLock() == NO_ERROR) {
397 locked = true;
398 break;
399 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800400 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 }
402 return locked;
403}
404
405status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
406{
Glenn Kasten44deb052012-02-05 18:09:08 -0800407 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 dumpPermissionDenial(fd, args);
409 } else {
410 // get state of hardware lock
411 bool hardwareLocked = tryLock(mHardwareLock);
412 if (!hardwareLocked) {
413 String8 result(kHardwareLockedString);
414 write(fd, result.string(), result.size());
415 } else {
416 mHardwareLock.unlock();
417 }
418
419 bool locked = tryLock(mLock);
420
421 // failed to lock - AudioFlinger is probably deadlocked
422 if (!locked) {
423 String8 result(kDeadlockedString);
424 write(fd, result.string(), result.size());
425 }
426
427 dumpClients(fd, args);
428 dumpInternals(fd, args);
429
430 // dump playback threads
431 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
432 mPlaybackThreads.valueAt(i)->dump(fd, args);
433 }
434
435 // dump record threads
436 for (size_t i = 0; i < mRecordThreads.size(); i++) {
437 mRecordThreads.valueAt(i)->dump(fd, args);
438 }
439
Dima Zavin799a70e2011-04-18 16:57:27 -0700440 // dump all hardware devs
441 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700442 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700443 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 }
445 if (locked) mLock.unlock();
446 }
447 return NO_ERROR;
448}
449
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800450sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
451{
452 // If pid is already in the mClients wp<> map, then use that entry
453 // (for which promote() is always != 0), otherwise create a new entry and Client.
454 sp<Client> client = mClients.valueFor(pid).promote();
455 if (client == 0) {
456 client = new Client(this, pid);
457 mClients.add(pid, client);
458 }
459
460 return client;
461}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462
463// IAudioFlinger interface
464
465
466sp<IAudioTrack> AudioFlinger::createTrack(
467 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800468 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800470 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700471 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800473 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800475 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800476 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477 int *sessionId,
478 status_t *status)
479{
480 sp<PlaybackThread::Track> track;
481 sp<TrackHandle> trackHandle;
482 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 status_t lStatus;
484 int lSessionId;
485
Glenn Kasten263709e2012-01-06 08:40:01 -0800486 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
487 // but if someone uses binder directly they could bypass that and cause us to crash
488 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000489 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 lStatus = BAD_VALUE;
491 goto Exit;
492 }
493
494 {
495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700497 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000499 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 lStatus = BAD_VALUE;
501 goto Exit;
502 }
503
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800504 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505
Steve Block3856b092011-10-20 11:56:00 +0100506 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700507 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700508 // check if an effect chain with the same session ID is present on another
509 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700511 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
512 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700513 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700514 if (sessions & PlaybackThread::EFFECT_SESSION) {
515 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700516 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700517 }
Eric Laurentde070132010-07-13 04:45:46 -0700518 }
519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 lSessionId = *sessionId;
521 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700522 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700523 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 if (sessionId != NULL) {
525 *sessionId = lSessionId;
526 }
527 }
Steve Block3856b092011-10-20 11:56:00 +0100528 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529
530 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800531 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700532
533 // move effect chain to this output thread if an effect on same session was waiting
534 // for a track to be created
535 if (lStatus == NO_ERROR && effectThread != NULL) {
536 Mutex::Autolock _dl(thread->mLock);
537 Mutex::Autolock _sl(effectThread->mLock);
538 moveEffectChain_l(lSessionId, effectThread, thread, true);
539 }
Eric Laurenta011e352012-03-29 15:51:43 -0700540
541 // Look for sync events awaiting for a session to be used.
542 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
543 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
544 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700545 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700546 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700547 } else {
548 mPendingSyncEvents[i]->cancel();
549 }
Eric Laurenta011e352012-03-29 15:51:43 -0700550 mPendingSyncEvents.removeAt(i);
551 i--;
552 }
553 }
554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 }
556 if (lStatus == NO_ERROR) {
557 trackHandle = new TrackHandle(track);
558 } else {
559 // remove local strong reference to Client before deleting the Track so that the Client
560 // destructor is called by the TrackBase destructor with mLock held
561 client.clear();
562 track.clear();
563 }
564
565Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700566 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 *status = lStatus;
568 }
569 return trackHandle;
570}
571
vivek mehta2192bc92012-12-04 11:46:08 -0800572#ifdef QCOM_HARDWARE
573sp<IDirectTrack> AudioFlinger::createDirectTrack(
574 pid_t pid,
575 uint32_t sampleRate,
576 audio_channel_mask_t channelMask,
577 audio_io_handle_t output,
578 int *sessionId,
579 IDirectTrackClient *client,
580 audio_stream_type_t streamType,
581 status_t *status)
582{
583 *status = NO_ERROR;
584 status_t lStatus = NO_ERROR;
585 sp<IDirectTrack> track = NULL;
586 DirectAudioTrack* directTrack = NULL;
587 Mutex::Autolock _l(mLock);
588
589 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
590 *sessionId, sampleRate, channelMask);
591 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
592 if(desc == NULL) {
593 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
594 lStatus = BAD_VALUE;
595 goto Exit;
596 }
597 desc->mStreamType = streamType;
598 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
599 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
600 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
601 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
602 // Check if the session ID is already associated with a track
603 uint32_t sessions = t->hasAudioSession(*sessionId);
604
605 // check if an effect with same session ID is waiting for a ssession to be created
606 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
607 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
608 // Clear reference to previous effect chain if any
609 t->mLock.lock();
610 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
611 mLPAEffectChain = t->getEffectChain_l(*sessionId);
612 t->mLock.unlock();
613 }
614 }
615 mLPASessionId = *sessionId;
616 if (mLPAEffectChain != NULL) {
617 mLPAEffectChain->setLPAFlag(true);
618 // For LPA, the volume will be applied in DSP. No need for volume
619 // control in the Effect chain, so setting it to unity.
620 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
621 mLPAEffectChain->setVolume_l(&volume,&volume);
622 } else {
623 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
624 }
625 mLPASampleRate = sampleRate;
626 mLPANumChannels = popcount(channelMask);
627 } else {
628 if(sessionId != NULL) {
629 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
630 }
631 }
632 }
633 mLock.unlock();
634 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
635 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
636 mLock.lock();
637 if (directTrack != 0) {
638 track = dynamic_cast<IDirectTrack *>(directTrack);
639 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
640 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
641 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
642 } else {
643 lStatus = BAD_VALUE;
644 }
645Exit:
646 if(lStatus) {
647 if (track != NULL) {
648 track.clear();
649 }
650 *status = lStatus;
651 }
652 return track;
653}
654
655void AudioFlinger::deleteEffectSession()
656{
657 Mutex::Autolock _l(mLock);
658 ALOGV("deleteSession");
659 // -2 is invalid session ID
660 mLPASessionId = -2;
661 if (mLPAEffectChain != NULL) {
662 mLPAEffectChain->setLPAFlag(false);
663 size_t i, numEffects = mLPAEffectChain->getNumEffects();
664 for(i = 0; i < numEffects; i++) {
665 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
666 effect->setInBuffer(mLPAEffectChain->inBuffer());
667 if (i == numEffects-1) {
668 effect->setOutBuffer(mLPAEffectChain->outBuffer());
669 } else {
670 effect->setOutBuffer(mLPAEffectChain->inBuffer());
671 }
672 effect->configure();
673 }
674 mLPAEffectChain.clear();
675 mLPAEffectChain = NULL;
676 }
677}
678
679// ToDo: Should we go ahead with this frameCount?
680#define DEAFULT_FRAME_COUNT 1200
681void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
682{
683 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
684 // This might be the first buffer to apply effects after effect config change
685 // should not skip effects processing
686 mIsEffectConfigChanged = false;
687
688 volatile size_t numEffects = 0;
689 if(mLPAEffectChain != NULL) {
690 numEffects = mLPAEffectChain->getNumEffects();
691 }
692
693 if( numEffects > 0) {
694 size_t i = 0;
695 int16_t *pIn = inBuffer;
696 int16_t *pOut = outBuffer;
697
698 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
699
700 while(frameCount > 0) {
701 if(mLPAEffectChain == NULL) {
702 ALOGV("LPA Effect Chain is removed - No effects processing !!");
703 numEffects = 0;
704 break;
705 }
706 mLPAEffectChain->lock();
707
708 numEffects = mLPAEffectChain->getNumEffects();
709 if(!numEffects) {
710 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
711 mLPAEffectChain->unlock();
712 break;
713 }
714
715 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
716 bool isEffectEnabled = false;
717 for(i = 0; i < numEffects; i++) {
718 // If effect configuration is changed while applying effects do not process further
719 if(mIsEffectConfigChanged) {
720 mLPAEffectChain->unlock();
721 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
722 return;
723 }
724 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
725 if(effect == NULL) {
726 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
727 mLPAEffectChain->unlock();
728 return;
729 }
730 if(i == 0) {
731 // For the first set input and output buffers different
732 isEffectEnabled = effect->isProcessEnabled();
733 effect->setInBuffer(pIn);
734 effect->setOutBuffer(pOut);
735 } else {
736 // For the remaining use previous effect's output buffer as input buffer
737 effect->setInBuffer(pOut);
738 effect->setOutBuffer(pOut);
739 }
740 // true indicates that it is being applied on LPA output
741 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
742 }
743
744 if(isEffectEnabled) {
745 // Clear the output buffer
746 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
747 } else {
748 // Copy input buffer content to the output buffer
749 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
750 }
751
752 mLPAEffectChain->process_l();
753
754 mLPAEffectChain->unlock();
755
756 // Update input and output buffer pointers
757 pIn += (outFrameCount * mLPANumChannels);
758 pOut += (outFrameCount * mLPANumChannels);
759 frameCount -= outFrameCount;
760 }
761 }
762
763 if (!numEffects) {
764 ALOGV("applyEffectsOn: There are no effects to be applied");
765 if(inBuffer != outBuffer) {
766 // No effect applied so just copy input buffer to output buffer
767 memcpy(outBuffer, inBuffer, size);
768 }
769 }
770}
771#endif
772
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800773uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774{
775 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800776#ifdef QCOM_HARDWARE
777 if (!mDirectAudioTracks.isEmpty()) {
778 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
779 if(desc != NULL) {
780 return desc->stream->common.get_sample_rate(&desc->stream->common);
781 }
782 }
783#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784 PlaybackThread *thread = checkPlaybackThread_l(output);
785 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000786 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 return 0;
788 }
789 return thread->sampleRate();
790}
791
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800792int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
794 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800795#ifdef QCOM_HARDWARE
796 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
797 if(desc != NULL) {
798 return desc->stream->common.get_channels(&desc->stream->common);
799 }
800#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 PlaybackThread *thread = checkPlaybackThread_l(output);
802 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000803 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 return 0;
805 }
806 return thread->channelCount();
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
811 Mutex::Autolock _l(mLock);
812 PlaybackThread *thread = checkPlaybackThread_l(output);
813 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000814 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800815 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 }
817 return thread->format();
818}
819
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800820size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
822 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800823#ifdef QCOM_HARDWARE
824 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
825 if(desc != NULL) {
826 return desc->stream->common.get_buffer_size(&desc->stream->common);
827 }
828#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 PlaybackThread *thread = checkPlaybackThread_l(output);
830 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000831 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 return 0;
833 }
Glenn Kasten58912562012-04-03 10:45:00 -0700834 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
835 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return thread->frameCount();
837}
838
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800839uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
841 Mutex::Autolock _l(mLock);
842 PlaybackThread *thread = checkPlaybackThread_l(output);
843 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000844 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
847 return thread->latency();
848}
849
850status_t AudioFlinger::setMasterVolume(float value)
851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return ret;
855 }
856
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 // check calling permissions
858 if (!settingsAllowed()) {
859 return PERMISSION_DENIED;
860 }
861
Eric Laurenta4c5a552012-03-29 10:12:40 -0700862 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700863 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700864
John Grossmanee578c02012-07-23 17:05:46 -0700865 // Set master volume in the HALs which support it.
866 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
867 AutoMutex lock(mHardwareLock);
868 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800869
John Grossmanee578c02012-07-23 17:05:46 -0700870 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
871 if (dev->canSetMasterVolume()) {
872 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800873 }
John Grossmanee578c02012-07-23 17:05:46 -0700874 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876
John Grossmanee578c02012-07-23 17:05:46 -0700877 // Now set the master volume in each playback thread. Playback threads
878 // assigned to HALs which do not have master volume support will apply
879 // master volume during the mix operation. Threads with HALs which do
880 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800881 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700882 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883
884 return NO_ERROR;
885}
886
Glenn Kastenf78aee72012-01-04 11:00:47 -0800887status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888{
Eric Laurenta1884f92011-08-23 08:25:03 -0700889 status_t ret = initCheck();
890 if (ret != NO_ERROR) {
891 return ret;
892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893
894 // check calling permissions
895 if (!settingsAllowed()) {
896 return PERMISSION_DENIED;
897 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800898 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000899 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 return BAD_VALUE;
901 }
902
903 { // scope for the lock
904 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700905 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700907 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 mHardwareStatus = AUDIO_HW_IDLE;
909 }
910
911 if (NO_ERROR == ret) {
912 Mutex::Autolock _l(mLock);
913 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800914 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700915 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 }
917
918 return ret;
919}
920
921status_t AudioFlinger::setMicMute(bool state)
922{
Eric Laurenta1884f92011-08-23 08:25:03 -0700923 status_t ret = initCheck();
924 if (ret != NO_ERROR) {
925 return ret;
926 }
927
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 // check calling permissions
929 if (!settingsAllowed()) {
930 return PERMISSION_DENIED;
931 }
932
933 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700934 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700936 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mHardwareStatus = AUDIO_HW_IDLE;
938 return ret;
939}
940
941bool AudioFlinger::getMicMute() const
942{
Eric Laurenta1884f92011-08-23 08:25:03 -0700943 status_t ret = initCheck();
944 if (ret != NO_ERROR) {
945 return false;
946 }
947
Dima Zavinfce7a472011-04-19 22:30:36 -0700948 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800949 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700950 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700952 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 mHardwareStatus = AUDIO_HW_IDLE;
954 return state;
955}
956
957status_t AudioFlinger::setMasterMute(bool muted)
958{
John Grossmand8f178d2012-07-20 14:51:35 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return ret;
962 }
963
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 // check calling permissions
965 if (!settingsAllowed()) {
966 return PERMISSION_DENIED;
967 }
968
John Grossmanee578c02012-07-23 17:05:46 -0700969 Mutex::Autolock _l(mLock);
970 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700971
John Grossmanee578c02012-07-23 17:05:46 -0700972 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100973#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700974 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
975 AutoMutex lock(mHardwareLock);
976 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700977
John Grossmanee578c02012-07-23 17:05:46 -0700978 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
979 if (dev->canSetMasterMute()) {
980 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700981 }
John Grossmanee578c02012-07-23 17:05:46 -0700982 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700983 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100984#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700985
John Grossmanee578c02012-07-23 17:05:46 -0700986 // Now set the master mute in each playback thread. Playback threads
987 // assigned to HALs which do not have master mute support will apply master
988 // mute during the mix operation. Threads with HALs which do support master
989 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800990 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700991 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992
993 return NO_ERROR;
994}
995
996float AudioFlinger::masterVolume() const
997{
Glenn Kasten98067102011-12-13 11:47:54 -0800998 Mutex::Autolock _l(mLock);
999 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000}
1001
1002bool AudioFlinger::masterMute() const
1003{
Glenn Kasten98067102011-12-13 11:47:54 -08001004 Mutex::Autolock _l(mLock);
1005 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006}
1007
John Grossman4ff14ba2012-02-08 16:37:41 -08001008float AudioFlinger::masterVolume_l() const
1009{
John Grossman4ff14ba2012-02-08 16:37:41 -08001010 return mMasterVolume;
1011}
1012
John Grossmand8f178d2012-07-20 14:51:35 -07001013bool AudioFlinger::masterMute_l() const
1014{
John Grossmanee578c02012-07-23 17:05:46 -07001015 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001016}
1017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001018status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1019 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020{
1021 // check calling permissions
1022 if (!settingsAllowed()) {
1023 return PERMISSION_DENIED;
1024 }
1025
Glenn Kasten263709e2012-01-06 08:40:01 -08001026 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001027 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 return BAD_VALUE;
1029 }
1030
1031 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001032#ifdef QCOM_HARDWARE
1033 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1034 AudioSessionDescriptor *desc = NULL;
1035 if (!mDirectAudioTracks.isEmpty()) {
1036 desc = mDirectAudioTracks.valueFor(output);
1037 if (desc != NULL) {
1038 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1039 if (desc->mStreamType == stream) {
1040 mStreamTypes[stream].volume = value;
1041 desc->stream->set_volume(desc->stream,
1042 desc->mVolumeLeft * mStreamTypes[stream].volume,
1043 desc->mVolumeRight* mStreamTypes[stream].volume);
1044 return NO_ERROR;
1045 }
1046 }
1047 }
1048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 PlaybackThread *thread = NULL;
1050 if (output) {
1051 thread = checkPlaybackThread_l(output);
1052 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001053#ifdef QCOM_HARDWARE
1054 if (desc != NULL) {
1055 return NO_ERROR;
1056 }
1057#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 return BAD_VALUE;
1059 }
vivek mehta2192bc92012-12-04 11:46:08 -08001060
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 }
1062
1063 mStreamTypes[stream].volume = value;
1064
1065 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001066 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001067 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 }
1069 } else {
1070 thread->setStreamVolume(stream, value);
1071 }
1072
1073 return NO_ERROR;
1074}
1075
Glenn Kastenfff6d712012-01-12 16:38:12 -08001076status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077{
1078 // check calling permissions
1079 if (!settingsAllowed()) {
1080 return PERMISSION_DENIED;
1081 }
1082
Glenn Kasten263709e2012-01-06 08:40:01 -08001083 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001084 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001085 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 return BAD_VALUE;
1087 }
1088
Eric Laurent93575202011-01-18 18:39:02 -08001089 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090 mStreamTypes[stream].mute = muted;
1091 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001092 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093
1094 return NO_ERROR;
1095}
1096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001097float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098{
Glenn Kasten263709e2012-01-06 08:40:01 -08001099 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 return 0.0f;
1101 }
1102
1103 AutoMutex lock(mLock);
1104 float volume;
1105 if (output) {
1106 PlaybackThread *thread = checkPlaybackThread_l(output);
1107 if (thread == NULL) {
1108 return 0.0f;
1109 }
1110 volume = thread->streamVolume(stream);
1111 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001112 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 }
1114
1115 return volume;
1116}
1117
Glenn Kastenfff6d712012-01-12 16:38:12 -08001118bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119{
Glenn Kasten263709e2012-01-06 08:40:01 -08001120 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 return true;
1122 }
1123
Glenn Kasten6637baa2012-01-09 09:40:36 -08001124 AutoMutex lock(mLock);
1125 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001128status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001130 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1132 // check calling permissions
1133 if (!settingsAllowed()) {
1134 return PERMISSION_DENIED;
1135 }
1136
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 // ioHandle == 0 means the parameters are global to the audio hardware interface
1138 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001139 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001140 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001141 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001142 AutoMutex lock(mHardwareLock);
1143 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1144 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1145 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1146 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1147 final_result = result ?: final_result;
1148 }
1149 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001150 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001151 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1152 AudioParameter param = AudioParameter(keyValuePairs);
1153 String8 value;
1154 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001155 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1156 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001157 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1158 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001159 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001160 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1161 // collect all of the thread's session IDs
1162 KeyedVector<int, bool> ids = thread->sessionIds();
1163 // suspend effects associated with those session IDs
1164 for (size_t j = 0; j < ids.size(); ++j) {
1165 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001166 thread->setEffectSuspended(FX_IID_AEC,
1167 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001168 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001169 thread->setEffectSuspended(FX_IID_NS,
1170 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001171 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001172 }
1173 }
Eric Laurentbee53372011-08-29 12:42:48 -07001174 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001175 }
1176 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001177 String8 screenState;
1178 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1179 bool isOff = screenState == "off";
1180 if (isOff != (gScreenState & 1)) {
1181 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1182 }
1183 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001184 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 }
1186
vivek mehta2192bc92012-12-04 11:46:08 -08001187#ifdef QCOM_HARDWARE
1188 AudioSessionDescriptor *desc = NULL;
1189 if (!mDirectAudioTracks.isEmpty()) {
1190 desc = mDirectAudioTracks.valueFor(ioHandle);
1191 if (desc != NULL) {
1192 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1193 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
1194 return NO_ERROR;
1195 }
1196 }
1197#endif
1198
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1200 // and the thread is exited once the lock is released
1201 sp<ThreadBase> thread;
1202 {
1203 Mutex::Autolock _l(mLock);
1204 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001205 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001207 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001208 // indicate output device change to all input threads for pre processing
1209 AudioParameter param = AudioParameter(keyValuePairs);
1210 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001211 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1212 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001213 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1214 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001215 for (size_t i = 0; i < recordThreads.size(); i++) {
1216 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001217 }
1218 }
vivek mehta2192bc92012-12-04 11:46:08 -08001219 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 }
vivek mehta2192bc92012-12-04 11:46:08 -08001221 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001223 if (thread != 0) {
1224 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 }
1226 return BAD_VALUE;
1227}
1228
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001229String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001231// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1233
Eric Laurenta4c5a552012-03-29 10:12:40 -07001234 Mutex::Autolock _l(mLock);
1235
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001237 String8 out_s8;
1238
Dima Zavin799a70e2011-04-18 16:57:27 -07001239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001240 char *s;
1241 {
1242 AutoMutex lock(mHardwareLock);
1243 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001244 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001245 s = dev->get_parameters(dev, keys.string());
1246 mHardwareStatus = AUDIO_HW_IDLE;
1247 }
John Grossmanef7740b2012-02-09 11:28:36 -08001248 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001249 free(s);
1250 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001251 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 }
1253
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1255 if (playbackThread != NULL) {
1256 return playbackThread->getParameters(keys);
1257 }
1258 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1259 if (recordThread != NULL) {
1260 return recordThread->getParameters(keys);
1261 }
1262 return String8("");
1263}
1264
Glenn Kastendd8104c2012-07-02 12:42:44 -07001265size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1266 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267{
Eric Laurenta1884f92011-08-23 08:25:03 -07001268 status_t ret = initCheck();
1269 if (ret != NO_ERROR) {
1270 return 0;
1271 }
1272
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001273 AutoMutex lock(mHardwareLock);
1274 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001275 struct audio_config config = {
1276 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001277 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001278 format: format,
1279 };
John Grossmanee578c02012-07-23 17:05:46 -07001280 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001281#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001282 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001283#else
1284 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1285#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001286 mHardwareStatus = AUDIO_HW_IDLE;
1287 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288}
1289
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001290unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 Mutex::Autolock _l(mLock);
1293
1294 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1295 if (recordThread != NULL) {
1296 return recordThread->getInputFramesLost();
1297 }
1298 return 0;
1299}
1300
1301status_t AudioFlinger::setVoiceVolume(float value)
1302{
Eric Laurenta1884f92011-08-23 08:25:03 -07001303 status_t ret = initCheck();
1304 if (ret != NO_ERROR) {
1305 return ret;
1306 }
1307
Mathias Agopian65ab4712010-07-14 17:59:35 -07001308 // check calling permissions
1309 if (!settingsAllowed()) {
1310 return PERMISSION_DENIED;
1311 }
1312
1313 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001314 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001315 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001316 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 mHardwareStatus = AUDIO_HW_IDLE;
1318
1319 return ret;
1320}
1321
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001322status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1323 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001324{
1325 status_t status;
1326
1327 Mutex::Autolock _l(mLock);
1328
1329 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1330 if (playbackThread != NULL) {
1331 return playbackThread->getRenderPosition(halFrames, dspFrames);
1332 }
1333
1334 return BAD_VALUE;
1335}
1336
1337void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1338{
1339
1340 Mutex::Autolock _l(mLock);
1341
vivek mehta2192bc92012-12-04 11:46:08 -08001342 sp<IBinder> binder = client->asBinder();
1343 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344 sp<NotificationClient> notificationClient = new NotificationClient(this,
1345 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001346 binder);
1347 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348
vivek mehta2192bc92012-12-04 11:46:08 -08001349 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350
1351 sp<IBinder> binder = client->asBinder();
1352 binder->linkToDeath(notificationClient);
1353
1354 // the config change is always sent from playback or record threads to avoid deadlock
1355 // with AudioSystem::gLock
1356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001357 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 }
1359
1360 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001361 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001362 }
1363 }
1364}
1365
vivek mehta2192bc92012-12-04 11:46:08 -08001366#ifdef QCOM_HARDWARE
1367status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1368{
1369 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1370 Mutex::Autolock _l(mLock);
1371
1372 sp<IBinder> binder = client->asBinder();
1373 int index = mNotificationClients.indexOfKey(binder);
1374 if (index >= 0) {
1375 mNotificationClients.removeItemsAt(index);
1376 return true;
1377 }
1378
1379 return false;
1380}
1381#endif
1382
1383void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384{
1385 Mutex::Autolock _l(mLock);
1386
vivek mehta2192bc92012-12-04 11:46:08 -08001387 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001388
vivek mehta2192bc92012-12-04 11:46:08 -08001389 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001390 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001391 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001392 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001393 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001394 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001395 ALOGV(" pid %d @ %d", ref->mPid, i);
1396 if (ref->mPid == pid) {
1397 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001398 mAudioSessionRefs.removeAt(i);
1399 delete ref;
1400 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001401 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001402 } else {
1403 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001404 }
1405 }
1406 if (removed) {
1407 purgeStaleEffects_l();
1408 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409}
1410
1411// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001412void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413{
vivek mehta2192bc92012-12-04 11:46:08 -08001414#ifdef QCOM_HARDWARE
1415 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1416 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1417 mIsEffectConfigChanged = true;
1418 }
1419#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 size_t size = mNotificationClients.size();
1421 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001422 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1423 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424 }
1425}
1426
1427// removeClient_l() must be called with AudioFlinger::mLock held
1428void AudioFlinger::removeClient_l(pid_t pid)
1429{
Steve Block3856b092011-10-20 11:56:00 +01001430 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 mClients.removeItem(pid);
1432}
1433
Eric Laurent717e1282012-06-29 16:36:52 -07001434// getEffectThread_l() must be called with AudioFlinger::mLock held
1435sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1436{
1437 sp<PlaybackThread> thread;
1438
1439 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1440 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1441 ALOG_ASSERT(thread == 0);
1442 thread = mPlaybackThreads.valueAt(i);
1443 }
1444 }
1445
1446 return thread;
1447}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
1449// ----------------------------------------------------------------------------
1450
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001451AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001452 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001453 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001454 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001455 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001456 // mChannelMask
1457 mChannelCount(0),
1458 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1459 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001460 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1461 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001462 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001463 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464{
1465}
1466
1467AudioFlinger::ThreadBase::~ThreadBase()
1468{
1469 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001470 // do not lock the mutex in destructor
1471 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001472 if (mPowerManager != 0) {
1473 sp<IBinder> binder = mPowerManager->asBinder();
1474 binder->unlinkToDeath(mDeathRecipient);
1475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478void AudioFlinger::ThreadBase::exit()
1479{
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001481 // do any cleanup required for exit to succeed
1482 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001484 // This lock prevents the following race in thread (uniprocessor for illustration):
1485 // if (!exitPending()) {
1486 // // context switch from here to exit()
1487 // // exit() calls requestExit(), what exitPending() observes
1488 // // exit() calls signal(), which is dropped since no waiters
1489 // // context switch back from exit() to here
1490 // mWaitWorkCV.wait(...);
1491 // // now thread is hung
1492 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001493 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001495 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001497 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1498 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 requestExitAndWait();
1500}
1501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1503{
1504 status_t status;
1505
Steve Block3856b092011-10-20 11:56:00 +01001506 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 Mutex::Autolock _l(mLock);
1508
1509 mNewParameters.add(keyValuePairs);
1510 mWaitWorkCV.signal();
1511 // wait condition with timeout in case the thread loop has exited
1512 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001513 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 status = mParamStatus;
1515 mWaitWorkCV.signal();
1516 } else {
1517 status = TIMED_OUT;
1518 }
1519 return status;
1520}
1521
vivek mehta2192bc92012-12-04 11:46:08 -08001522#ifdef QCOM_HARDWARE
1523void AudioFlinger::ThreadBase::effectConfigChanged() {
1524 mAudioFlinger->mLock.lock();
1525 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1526 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1527 mAudioFlinger->mLock.unlock();
1528}
1529#endif
1530
Eric Laurent896adcd2012-09-13 11:18:23 -07001531void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532{
1533 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001534 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535}
1536
Eric Laurent896adcd2012-09-13 11:18:23 -07001537// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1538void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539{
Eric Laurent896adcd2012-09-13 11:18:23 -07001540 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1541 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1542 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1543 mWaitWorkCV.signal();
1544}
1545
1546// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1547void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1548{
1549 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1550 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1551 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1552 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 mWaitWorkCV.signal();
1554}
1555
1556void AudioFlinger::ThreadBase::processConfigEvents()
1557{
1558 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001559 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001560 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001561 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 mConfigEvents.removeAt(0);
1563 // release mLock before locking AudioFlinger mLock: lock order is always
1564 // AudioFlinger then ThreadBase to avoid cross deadlock
1565 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001566 switch(event->type()) {
1567 case CFG_EVENT_PRIO: {
1568 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1569 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1570 if (err != 0) {
1571 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1572 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1573 }
1574 } break;
1575 case CFG_EVENT_IO: {
1576 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1577 mAudioFlinger->mLock.lock();
1578 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1579 mAudioFlinger->mLock.unlock();
1580 } break;
1581 default:
1582 ALOGE("processConfigEvents() unknown event type %d", event->type());
1583 break;
1584 }
1585 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 mLock.lock();
1587 }
1588 mLock.unlock();
1589}
1590
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001591void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592{
1593 const size_t SIZE = 256;
1594 char buffer[SIZE];
1595 String8 result;
1596
1597 bool locked = tryLock(mLock);
1598 if (!locked) {
1599 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1600 write(fd, buffer, strlen(buffer));
1601 }
1602
Eric Laurent612bbb52012-03-14 15:03:26 -07001603 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1604 result.append(buffer);
1605 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1606 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1608 result.append(buffer);
1609 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1610 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001611 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1612 result.append(buffer);
1613 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 result.append(buffer);
1615 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1616 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001617 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1618 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1620 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001621 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 result.append(buffer);
1623
1624 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1625 result.append(buffer);
1626 result.append(" Index Command");
1627 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1628 snprintf(buffer, SIZE, "\n %02d ", i);
1629 result.append(buffer);
1630 result.append(mNewParameters[i]);
1631 }
1632
1633 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1634 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001636 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 result.append(buffer);
1638 }
1639 result.append("\n");
1640
1641 write(fd, result.string(), result.size());
1642
1643 if (locked) {
1644 mLock.unlock();
1645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646}
1647
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001648void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001649{
1650 const size_t SIZE = 256;
1651 char buffer[SIZE];
1652 String8 result;
1653
1654 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1655 write(fd, buffer, strlen(buffer));
1656
1657 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1658 sp<EffectChain> chain = mEffectChains[i];
1659 if (chain != 0) {
1660 chain->dump(fd, args);
1661 }
1662 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001663}
1664
Eric Laurentfeb0db62011-07-22 09:04:31 -07001665void AudioFlinger::ThreadBase::acquireWakeLock()
1666{
1667 Mutex::Autolock _l(mLock);
1668 acquireWakeLock_l();
1669}
1670
1671void AudioFlinger::ThreadBase::acquireWakeLock_l()
1672{
1673 if (mPowerManager == 0) {
1674 // use checkService() to avoid blocking if power service is not up yet
1675 sp<IBinder> binder =
1676 defaultServiceManager()->checkService(String16("power"));
1677 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001678 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001679 } else {
1680 mPowerManager = interface_cast<IPowerManager>(binder);
1681 binder->linkToDeath(mDeathRecipient);
1682 }
1683 }
1684 if (mPowerManager != 0) {
1685 sp<IBinder> binder = new BBinder();
1686 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1687 binder,
1688 String16(mName));
1689 if (status == NO_ERROR) {
1690 mWakeLockToken = binder;
1691 }
Steve Block3856b092011-10-20 11:56:00 +01001692 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001693 }
1694}
1695
1696void AudioFlinger::ThreadBase::releaseWakeLock()
1697{
1698 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001699 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001700}
1701
1702void AudioFlinger::ThreadBase::releaseWakeLock_l()
1703{
1704 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001705 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001706 if (mPowerManager != 0) {
1707 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1708 }
1709 mWakeLockToken.clear();
1710 }
1711}
1712
1713void AudioFlinger::ThreadBase::clearPowerManager()
1714{
1715 Mutex::Autolock _l(mLock);
1716 releaseWakeLock_l();
1717 mPowerManager.clear();
1718}
1719
1720void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1721{
1722 sp<ThreadBase> thread = mThread.promote();
1723 if (thread != 0) {
1724 thread->clearPowerManager();
1725 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001726 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001727}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001728
Eric Laurent59255e42011-07-27 19:49:51 -07001729void AudioFlinger::ThreadBase::setEffectSuspended(
1730 const effect_uuid_t *type, bool suspend, int sessionId)
1731{
1732 Mutex::Autolock _l(mLock);
1733 setEffectSuspended_l(type, suspend, sessionId);
1734}
1735
1736void AudioFlinger::ThreadBase::setEffectSuspended_l(
1737 const effect_uuid_t *type, bool suspend, int sessionId)
1738{
Glenn Kasten090f0192012-01-30 13:00:02 -08001739 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001740 if (chain != 0) {
1741 if (type != NULL) {
1742 chain->setEffectSuspended_l(type, suspend);
1743 } else {
1744 chain->setEffectSuspendedAll_l(suspend);
1745 }
1746 }
1747
1748 updateSuspendedSessions_l(type, suspend, sessionId);
1749}
1750
1751void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1752{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001753 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001754 if (index < 0) {
1755 return;
1756 }
1757
Glenn Kasten0a7af182012-07-09 16:09:19 -07001758 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1759 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001760
1761 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001762 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001763 for (int j = 0; j < desc->mRefCount; j++) {
1764 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1765 chain->setEffectSuspendedAll_l(true);
1766 } else {
Steve Block3856b092011-10-20 11:56:00 +01001767 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001768 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001769 chain->setEffectSuspended_l(&desc->mType, true);
1770 }
1771 }
1772 }
1773}
1774
Eric Laurent59255e42011-07-27 19:49:51 -07001775void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1776 bool suspend,
1777 int sessionId)
1778{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001779 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001780
1781 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1782
1783 if (suspend) {
1784 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001785 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001786 } else {
1787 mSuspendedSessions.add(sessionId, sessionEffects);
1788 }
1789 } else {
1790 if (index < 0) {
1791 return;
1792 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001793 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001794 }
1795
1796
1797 int key = EffectChain::kKeyForSuspendAll;
1798 if (type != NULL) {
1799 key = type->timeLow;
1800 }
1801 index = sessionEffects.indexOfKey(key);
1802
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001803 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001804 if (suspend) {
1805 if (index >= 0) {
1806 desc = sessionEffects.valueAt(index);
1807 } else {
1808 desc = new SuspendedSessionDesc();
1809 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001810 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001811 }
1812 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001813 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001814 }
1815 desc->mRefCount++;
1816 } else {
1817 if (index < 0) {
1818 return;
1819 }
1820 desc = sessionEffects.valueAt(index);
1821 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001822 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001823 sessionEffects.removeItemsAt(index);
1824 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001825 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001826 sessionId);
1827 mSuspendedSessions.removeItem(sessionId);
1828 }
1829 }
1830 }
1831 if (!sessionEffects.isEmpty()) {
1832 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1833 }
1834}
1835
1836void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1837 bool enabled,
1838 int sessionId)
1839{
1840 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001841 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1842}
Eric Laurent59255e42011-07-27 19:49:51 -07001843
Eric Laurenta85a74a2011-10-19 11:44:54 -07001844void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1845 bool enabled,
1846 int sessionId)
1847{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001848 if (mType != RECORD) {
1849 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1850 // another session. This gives the priority to well behaved effect control panels
1851 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001852 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1853 // global effects
1854 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001855 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1856 }
1857 }
Eric Laurent59255e42011-07-27 19:49:51 -07001858
1859 sp<EffectChain> chain = getEffectChain_l(sessionId);
1860 if (chain != 0) {
1861 chain->checkSuspendOnEffectEnabled(effect, enabled);
1862 }
1863}
1864
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865// ----------------------------------------------------------------------------
1866
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001867AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1868 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001869 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001870 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001871 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001872 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001873 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001874 // mStreamTypes[] initialized in constructor body
1875 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001876 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001877 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001878 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001879 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001880 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001881 // index 0 is reserved for normal mixer's submix
1882 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883{
Glenn Kasten480b4682012-02-28 12:30:08 -08001884 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001885
John Grossmanee578c02012-07-23 17:05:46 -07001886 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1887 // it would be safer to explicitly pass initial masterVolume/masterMute as
1888 // parameter.
1889 //
1890 // If the HAL we are using has support for master volume or master mute,
1891 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1892 // and the mute set to false).
1893 mMasterVolume = audioFlinger->masterVolume_l();
1894 mMasterMute = audioFlinger->masterMute_l();
1895 if (mOutput && mOutput->audioHwDev) {
1896 if (mOutput->audioHwDev->canSetMasterVolume()) {
1897 mMasterVolume = 1.0;
1898 }
1899
1900 if (mOutput->audioHwDev->canSetMasterMute()) {
1901 mMasterMute = false;
1902 }
1903 }
1904
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 readOutputParameters();
1906
Glenn Kasten263709e2012-01-06 08:40:01 -08001907 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001908 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1909 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1910 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001911 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1912 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001914 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1915 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916}
1917
1918AudioFlinger::PlaybackThread::~PlaybackThread()
1919{
1920 delete [] mMixBuffer;
1921}
1922
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001923void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924{
1925 dumpInternals(fd, args);
1926 dumpTracks(fd, args);
1927 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928}
1929
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001930void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931{
1932 const size_t SIZE = 256;
1933 char buffer[SIZE];
1934 String8 result;
1935
Glenn Kasten58912562012-04-03 10:45:00 -07001936 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1937 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1938 const stream_type_t *st = &mStreamTypes[i];
1939 if (i > 0) {
1940 result.appendFormat(", ");
1941 }
1942 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1943 if (st->mute) {
1944 result.append("M");
1945 }
1946 }
1947 result.append("\n");
1948 write(fd, result.string(), result.length());
1949 result.clear();
1950
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1952 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001953 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 for (size_t i = 0; i < mTracks.size(); ++i) {
1955 sp<Track> track = mTracks[i];
1956 if (track != 0) {
1957 track->dump(buffer, SIZE);
1958 result.append(buffer);
1959 }
1960 }
1961
1962 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1963 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001964 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001966 sp<Track> track = mActiveTracks[i].promote();
1967 if (track != 0) {
1968 track->dump(buffer, SIZE);
1969 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 }
1971 }
1972 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001973
1974 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1975 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1976 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1977 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978}
1979
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001980void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981{
1982 const size_t SIZE = 256;
1983 char buffer[SIZE];
1984 String8 result;
1985
1986 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1987 result.append(buffer);
1988 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1989 result.append(buffer);
1990 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1991 result.append(buffer);
1992 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1993 result.append(buffer);
1994 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1995 result.append(buffer);
1996 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1997 result.append(buffer);
1998 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1999 result.append(buffer);
2000 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002001 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002
2003 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004}
2005
2006// Thread virtuals
2007status_t AudioFlinger::PlaybackThread::readyToRun()
2008{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002009 status_t status = initCheck();
2010 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002011 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002012 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002013 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002015 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016}
2017
2018void AudioFlinger::PlaybackThread::onFirstRef()
2019{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002020 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021}
2022
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002023// ThreadBase virtuals
2024void AudioFlinger::PlaybackThread::preExit()
2025{
2026 ALOGV(" preExit()");
2027 // FIXME this is using hard-coded strings but in the future, this functionality will be
2028 // converted to use audio HAL extensions required to support tunneling
2029 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2030}
2031
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002033sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002035 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002037 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002038 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 int frameCount,
2040 const sp<IMemory>& sharedBuffer,
2041 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002042 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002043 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 status_t *status)
2045{
2046 sp<Track> track;
2047 status_t lStatus;
2048
Glenn Kasten73d22752012-03-19 13:38:30 -07002049 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2050
2051 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002052 if (flags & IAudioFlinger::TRACK_FAST) {
2053 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002054 // not timed
2055 (!isTimed) &&
2056 // either of these use cases:
2057 (
2058 // use case 1: shared buffer with any frame count
2059 (
2060 (sharedBuffer != 0)
2061 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002062 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002063 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002064 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002065 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002066 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002067 )
2068 ) &&
2069 // PCM data
2070 audio_is_linear_pcm(format) &&
2071 // mono or stereo
2072 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2073 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002074#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002075 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002076 (sampleRate == mSampleRate) &&
2077#endif
2078 // normal mixer has an associated fast mixer
2079 hasFastMixer() &&
2080 // there are sufficient fast track slots available
2081 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002082 // FIXME test that MixerThread for this fast track has a capable output HAL
2083 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002084 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002085 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2086 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002087 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002088 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002089 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002090 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002091 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002092 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002093 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002094 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2095 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2096 audio_is_linear_pcm(format),
2097 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002098 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002099 // For compatibility with AudioTrack calculation, buffer depth is forced
2100 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2101 // This is probably too conservative, but legacy application code may depend on it.
2102 // If you change this calculation, also review the start threshold which is related.
2103 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2104 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2105 if (minBufCount < 2) {
2106 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002107 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002108 int minFrameCount = mNormalFrameCount * minBufCount;
2109 if (frameCount < minFrameCount) {
2110 frameCount = minFrameCount;
2111 }
2112 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002113 }
2114
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002116 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2117 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002118 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002119 "for output %p with format %d",
2120 sampleRate, format, channelMask, mOutput, mFormat);
2121 lStatus = BAD_VALUE;
2122 goto Exit;
2123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 }
2125 } else {
2126 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2127 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002128 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 lStatus = BAD_VALUE;
2130 goto Exit;
2131 }
2132 }
2133
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002134 lStatus = initCheck();
2135 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002136 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 goto Exit;
2138 }
2139
2140 { // scope for mLock
2141 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002142
2143 // all tracks in same audio session must share the same routing strategy otherwise
2144 // conflicts will happen when tracks are moved from one output to another by audio policy
2145 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002146 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002147 for (size_t i = 0; i < mTracks.size(); ++i) {
2148 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002149 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002150 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002151 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002152 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002153 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002154 lStatus = BAD_VALUE;
2155 goto Exit;
2156 }
2157 }
2158 }
2159
John Grossman4ff14ba2012-02-08 16:37:41 -08002160 if (!isTimed) {
2161 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002162 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002163 } else {
2164 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2165 channelMask, frameCount, sharedBuffer, sessionId);
2166 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002167 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 lStatus = NO_MEMORY;
2169 goto Exit;
2170 }
2171 mTracks.add(track);
2172
2173 sp<EffectChain> chain = getEffectChain_l(sessionId);
2174 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002175 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002177 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002178 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002180
Eric Laurent896adcd2012-09-13 11:18:23 -07002181 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2182 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2183 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2184 // so ask activity manager to do this on our behalf
2185 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002186 }
2187 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002188
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 lStatus = NO_ERROR;
2190
2191Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002192 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 *status = lStatus;
2194 }
2195 return track;
2196}
2197
Eric Laurente737cda2012-05-22 18:55:44 -07002198uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2199{
2200 if (mFastMixer != NULL) {
2201 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2202 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2203 }
2204 return latency;
2205}
2206
2207uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2208{
2209 return latency;
2210}
2211
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212uint32_t AudioFlinger::PlaybackThread::latency() const
2213{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002214 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002215 return latency_l();
2216}
2217uint32_t AudioFlinger::PlaybackThread::latency_l() const
2218{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002219 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002220 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002221 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 return 0;
2223 }
2224}
2225
Glenn Kasten6637baa2012-01-09 09:40:36 -08002226void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002228 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002229 // Don't apply master volume in SW if our HAL can do it for us.
2230 if (mOutput && mOutput->audioHwDev &&
2231 mOutput->audioHwDev->canSetMasterVolume()) {
2232 mMasterVolume = 1.0;
2233 } else {
2234 mMasterVolume = value;
2235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236}
2237
Glenn Kasten6637baa2012-01-09 09:40:36 -08002238void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002240 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002241 // Don't apply master mute in SW if our HAL can do it for us.
2242 if (mOutput && mOutput->audioHwDev &&
2243 mOutput->audioHwDev->canSetMasterMute()) {
2244 mMasterMute = false;
2245 } else {
2246 mMasterMute = muted;
2247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248}
2249
Glenn Kasten6637baa2012-01-09 09:40:36 -08002250void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002252 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254}
2255
Glenn Kasten6637baa2012-01-09 09:40:36 -08002256void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002258 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260}
2261
Glenn Kastenfff6d712012-01-12 16:38:12 -08002262float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002264 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 return mStreamTypes[stream].volume;
2266}
2267
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268// addTrack_l() must be called with ThreadBase::mLock held
2269status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2270{
2271 status_t status = ALREADY_EXISTS;
2272
2273 // set retry count for buffer fill
2274 track->mRetryCount = kMaxTrackStartupRetries;
2275 if (mActiveTracks.indexOf(track) < 0) {
2276 // the track is newly added, make sure it fills up all its
2277 // buffers before playing. This is to ensure the client will
2278 // effectively get the latency it requested.
2279 track->mFillingUpStatus = Track::FS_FILLING;
2280 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002281 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 mActiveTracks.add(track);
2283 if (track->mainBuffer() != mMixBuffer) {
2284 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2285 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002286 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002287 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289 }
2290
2291 status = NO_ERROR;
2292 }
2293
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 mWaitWorkCV.broadcast();
2296
2297 return status;
2298}
2299
2300// destroyTrack_l() must be called with ThreadBase::mLock held
2301void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2302{
2303 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002304 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002306 removeTrack_l(track);
2307 }
2308}
2309
2310void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2311{
Eric Laurent29864602012-05-08 18:57:51 -07002312 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002313 mTracks.remove(track);
2314 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002315 // redundant as track is about to be destroyed, for dumpsys only
2316 track->mName = -1;
2317 if (track->isFastTrack()) {
2318 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002319 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002320 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2321 mFastTrackAvailMask |= 1 << index;
2322 // redundant as track is about to be destroyed, for dumpsys only
2323 track->mFastIndex = -1;
2324 }
Eric Laurentb469b942011-05-09 12:09:06 -07002325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2326 if (chain != 0) {
2327 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329}
2330
2331String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2332{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002333 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002334 char *s;
2335
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002336 Mutex::Autolock _l(mLock);
2337 if (initCheck() != NO_ERROR) {
2338 return out_s8;
2339 }
2340
Dima Zavin799a70e2011-04-18 16:57:27 -07002341 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002342 out_s8 = String8(s);
2343 free(s);
2344 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345}
2346
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002347// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2349 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002350 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351
Steve Block3856b092011-10-20 11:56:00 +01002352 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353
2354 switch (event) {
2355 case AudioSystem::OUTPUT_OPENED:
2356 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002357 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 desc.samplingRate = mSampleRate;
2359 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002360 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 desc.latency = latency();
2362 param2 = &desc;
2363 break;
2364
2365 case AudioSystem::STREAM_CONFIG_CHANGED:
2366 param2 = &param;
2367 case AudioSystem::OUTPUT_CLOSED:
2368 default:
2369 break;
2370 }
2371 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2372}
2373
2374void AudioFlinger::PlaybackThread::readOutputParameters()
2375{
Dima Zavin799a70e2011-04-18 16:57:27 -07002376 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002377 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2378 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002379 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002380 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002381 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002382 if (mFrameCount & 15) {
2383 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2384 mFrameCount);
2385 }
2386
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002387 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002388 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002389 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002390 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002391 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2392 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2393 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2394 maxNormalFrameCount = maxNormalFrameCount & ~15;
2395 if (maxNormalFrameCount < minNormalFrameCount) {
2396 maxNormalFrameCount = minNormalFrameCount;
2397 }
2398 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2399 if (multiplier <= 1.0) {
2400 multiplier = 1.0;
2401 } else if (multiplier <= 2.0) {
2402 if (2 * mFrameCount <= maxNormalFrameCount) {
2403 multiplier = 2.0;
2404 } else {
2405 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2406 }
2407 } else {
2408 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2409 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2410 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2411 // FIXME this rounding up should not be done if no HAL SRC
2412 uint32_t truncMult = (uint32_t) multiplier;
2413 if ((truncMult & 1)) {
2414 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2415 ++truncMult;
2416 }
2417 }
2418 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002419 }
Glenn Kasten58912562012-04-03 10:45:00 -07002420 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002421 mNormalFrameCount = multiplier * mFrameCount;
2422 // round up to nearest 16 frames to satisfy AudioMixer
2423 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002424 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425
Glenn Kastene9dd0172012-01-27 18:08:45 -08002426 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002427 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2428 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429
Eric Laurentde070132010-07-13 04:45:46 -07002430 // force reconfiguration of effect chains and engines to take new buffer size and audio
2431 // parameters into account
2432 // Note that mLock is not held when readOutputParameters() is called from the constructor
2433 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2434 // matter.
2435 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2436 Vector< sp<EffectChain> > effectChains = mEffectChains;
2437 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002438 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440}
2441
Eric Laurente737cda2012-05-22 18:55:44 -07002442
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2444{
Glenn Kastena0d68332012-01-27 16:47:15 -08002445 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 return BAD_VALUE;
2447 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002448 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002449 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 return INVALID_OPERATION;
2451 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002452 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453
Eric Laurent1afc26d2012-09-23 15:20:50 -07002454 if (isSuspended()) {
2455 // return an estimation of rendered frames when the output is suspended
2456 int32_t frames = mBytesWritten - latency_l();
2457 if (frames < 0) {
2458 frames = 0;
2459 }
2460 *dspFrames = (uint32_t)frames;
2461 return NO_ERROR;
2462 } else {
2463 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465}
2466
Glenn Kasten106e8a42012-08-02 13:37:12 -07002467uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468{
2469 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002470 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002472 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 }
2474
2475 for (size_t i = 0; i < mTracks.size(); ++i) {
2476 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002477 if (sessionId == track->sessionId() &&
2478 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002479 result |= TRACK_SESSION;
2480 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
2482 }
2483
Eric Laurent39e94f82010-07-28 01:32:47 -07002484 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485}
2486
Eric Laurentde070132010-07-13 04:45:46 -07002487uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2488{
Dima Zavinfce7a472011-04-19 22:30:36 -07002489 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002490 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002491 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2492 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002493 }
2494 for (size_t i = 0; i < mTracks.size(); i++) {
2495 sp<Track> track = mTracks[i];
2496 if (sessionId == track->sessionId() &&
2497 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002498 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002499 }
2500 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002501 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002502}
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504
Glenn Kastenaed850d2012-01-26 09:46:34 -08002505AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002506{
2507 Mutex::Autolock _l(mLock);
2508 return mOutput;
2509}
2510
2511AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2512{
2513 Mutex::Autolock _l(mLock);
2514 AudioStreamOut *output = mOutput;
2515 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002516 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2517 // must push a NULL and wait for ack
2518 mOutputSink.clear();
2519 mPipeSink.clear();
2520 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002521 return output;
2522}
2523
2524// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002525audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002526{
2527 if (mOutput == NULL) {
2528 return NULL;
2529 }
2530 return &mOutput->stream->common;
2531}
2532
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002533uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002534{
Eric Laurentab9071b2012-06-04 13:45:29 -07002535 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002536}
2537
Eric Laurenta011e352012-03-29 15:51:43 -07002538status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2539{
2540 if (!isValidSyncEvent(event)) {
2541 return BAD_VALUE;
2542 }
2543
2544 Mutex::Autolock _l(mLock);
2545
2546 for (size_t i = 0; i < mTracks.size(); ++i) {
2547 sp<Track> track = mTracks[i];
2548 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002549 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002550 return NO_ERROR;
2551 }
2552 }
2553
2554 return NAME_NOT_FOUND;
2555}
2556
Glenn Kasten106e8a42012-08-02 13:37:12 -07002557bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002558{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002559 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002560}
2561
Eric Laurent44a957f2012-05-15 15:26:05 -07002562void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2563{
2564 size_t count = tracksToRemove.size();
2565 if (CC_UNLIKELY(count)) {
2566 for (size_t i = 0 ; i < count ; i++) {
2567 const sp<Track>& track = tracksToRemove.itemAt(i);
2568 if ((track->sharedBuffer() != 0) &&
2569 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2570 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2571 }
2572 }
2573 }
2574
2575}
2576
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577// ----------------------------------------------------------------------------
2578
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002579AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002580 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002581 : PlaybackThread(audioFlinger, output, id, device, type),
2582 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002583 // mFastMixer below
2584 mFastMixerFutex(0)
2585 // mOutputSink below
2586 // mPipeSink below
2587 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002589 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002590 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002591 "mFrameCount=%d, mNormalFrameCount=%d",
2592 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2593 mNormalFrameCount);
2594 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2595
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002597 if (mChannelCount != FCC_2) {
2598 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 }
Glenn Kasten58912562012-04-03 10:45:00 -07002600
2601 // create an NBAIO sink for the HAL output stream, and negotiate
2602 mOutputSink = new AudioStreamOutSink(output->stream);
2603 size_t numCounterOffers = 0;
2604 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2605 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2606 ALOG_ASSERT(index == 0);
2607
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002608 // initialize fast mixer depending on configuration
2609 bool initFastMixer;
2610 switch (kUseFastMixer) {
2611 case FastMixer_Never:
2612 initFastMixer = false;
2613 break;
2614 case FastMixer_Always:
2615 initFastMixer = true;
2616 break;
2617 case FastMixer_Static:
2618 case FastMixer_Dynamic:
2619 initFastMixer = mFrameCount < mNormalFrameCount;
2620 break;
2621 }
2622 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002623
2624 // create a MonoPipe to connect our submix to FastMixer
2625 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002626 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2627 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2628 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2629 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002630 const NBAIO_Format offers[1] = {format};
2631 size_t numCounterOffers = 0;
2632 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2633 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002634 monoPipe->setAvgFrames((mScreenState & 1) ?
2635 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002636 mPipeSink = monoPipe;
2637
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002638#ifdef TEE_SINK_FRAMES
2639 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2640 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2641 numCounterOffers = 0;
2642 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2643 ALOG_ASSERT(index == 0);
2644 mTeeSink = teeSink;
2645 PipeReader *teeSource = new PipeReader(*teeSink);
2646 numCounterOffers = 0;
2647 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2648 ALOG_ASSERT(index == 0);
2649 mTeeSource = teeSource;
2650#endif
2651
Glenn Kasten58912562012-04-03 10:45:00 -07002652 // create fast mixer and configure it initially with just one fast track for our submix
2653 mFastMixer = new FastMixer();
2654 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002655#ifdef STATE_QUEUE_DUMP
2656 sq->setObserverDump(&mStateQueueObserverDump);
2657 sq->setMutatorDump(&mStateQueueMutatorDump);
2658#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002659 FastMixerState *state = sq->begin();
2660 FastTrack *fastTrack = &state->mFastTracks[0];
2661 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2662 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2663 fastTrack->mVolumeProvider = NULL;
2664 fastTrack->mGeneration++;
2665 state->mFastTracksGen++;
2666 state->mTrackMask = 1;
2667 // fast mixer will use the HAL output sink
2668 state->mOutputSink = mOutputSink.get();
2669 state->mOutputSinkGen++;
2670 state->mFrameCount = mFrameCount;
2671 state->mCommand = FastMixerState::COLD_IDLE;
2672 // already done in constructor initialization list
2673 //mFastMixerFutex = 0;
2674 state->mColdFutexAddr = &mFastMixerFutex;
2675 state->mColdGen++;
2676 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002677 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002678 sq->end();
2679 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2680
2681 // start the fast mixer
2682 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002683 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002684 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002685 if (err != 0) {
2686 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002687 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002688 }
Glenn Kasten58912562012-04-03 10:45:00 -07002689
Glenn Kastenc15d6652012-05-30 14:52:57 -07002690#ifdef AUDIO_WATCHDOG
2691 // create and start the watchdog
2692 mAudioWatchdog = new AudioWatchdog();
2693 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2694 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2695 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002696 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002697 if (err != 0) {
2698 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002699 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002700 }
2701#endif
2702
Glenn Kasten58912562012-04-03 10:45:00 -07002703 } else {
2704 mFastMixer = NULL;
2705 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002706
2707 switch (kUseFastMixer) {
2708 case FastMixer_Never:
2709 case FastMixer_Dynamic:
2710 mNormalSink = mOutputSink;
2711 break;
2712 case FastMixer_Always:
2713 mNormalSink = mPipeSink;
2714 break;
2715 case FastMixer_Static:
2716 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2717 break;
2718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719}
2720
2721AudioFlinger::MixerThread::~MixerThread()
2722{
Glenn Kasten58912562012-04-03 10:45:00 -07002723 if (mFastMixer != NULL) {
2724 FastMixerStateQueue *sq = mFastMixer->sq();
2725 FastMixerState *state = sq->begin();
2726 if (state->mCommand == FastMixerState::COLD_IDLE) {
2727 int32_t old = android_atomic_inc(&mFastMixerFutex);
2728 if (old == -1) {
2729 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2730 }
2731 }
2732 state->mCommand = FastMixerState::EXIT;
2733 sq->end();
2734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2735 mFastMixer->join();
2736 // Though the fast mixer thread has exited, it's state queue is still valid.
2737 // We'll use that extract the final state which contains one remaining fast track
2738 // corresponding to our sub-mix.
2739 state = sq->begin();
2740 ALOG_ASSERT(state->mTrackMask == 1);
2741 FastTrack *fastTrack = &state->mFastTracks[0];
2742 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2743 delete fastTrack->mBufferProvider;
2744 sq->end(false /*didModify*/);
2745 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002746#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002747 if (mAudioWatchdog != 0) {
2748 mAudioWatchdog->requestExit();
2749 mAudioWatchdog->requestExitAndWait();
2750 mAudioWatchdog.clear();
2751 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002752#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 delete mAudioMixer;
2755}
2756
Glenn Kasten83efdd02012-02-24 07:21:32 -08002757class CpuStats {
2758public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002759 CpuStats();
2760 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002761#ifdef DEBUG_CPU_USAGE
2762private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002763 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2764 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2765
2766 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2767
2768 int mCpuNum; // thread's current CPU number
2769 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002770#endif
2771};
2772
Glenn Kasten190a46f2012-03-06 11:27:10 -08002773CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002774#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002775 : mCpuNum(-1), mCpukHz(-1)
2776#endif
2777{
2778}
2779
2780void CpuStats::sample(const String8 &title) {
2781#ifdef DEBUG_CPU_USAGE
2782 // get current thread's delta CPU time in wall clock ns
2783 double wcNs;
2784 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2785
2786 // record sample for wall clock statistics
2787 if (valid) {
2788 mWcStats.sample(wcNs);
2789 }
2790
2791 // get the current CPU number
2792 int cpuNum = sched_getcpu();
2793
2794 // get the current CPU frequency in kHz
2795 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2796
2797 // check if either CPU number or frequency changed
2798 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2799 mCpuNum = cpuNum;
2800 mCpukHz = cpukHz;
2801 // ignore sample for purposes of cycles
2802 valid = false;
2803 }
2804
2805 // if no change in CPU number or frequency, then record sample for cycle statistics
2806 if (valid && mCpukHz > 0) {
2807 double cycles = wcNs * cpukHz * 0.000001;
2808 mHzStats.sample(cycles);
2809 }
2810
2811 unsigned n = mWcStats.n();
2812 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002813 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002814 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002815 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2816 double perLoop = elapsed / (double) n;
2817 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002818 double perLoop1k = perLoop * 0.001;
2819 double mean = mWcStats.mean();
2820 double stddev = mWcStats.stddev();
2821 double minimum = mWcStats.minimum();
2822 double maximum = mWcStats.maximum();
2823 double meanCycles = mHzStats.mean();
2824 double stddevCycles = mHzStats.stddev();
2825 double minCycles = mHzStats.minimum();
2826 double maxCycles = mHzStats.maximum();
2827 mCpuUsage.resetElapsed();
2828 mWcStats.reset();
2829 mHzStats.reset();
2830 ALOGD("CPU usage for %s over past %.1f secs\n"
2831 " (%u mixer loops at %.1f mean ms per loop):\n"
2832 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2833 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2834 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2835 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002836 elapsed * .000000001, n, perLoop * .000001,
2837 mean * .001,
2838 stddev * .001,
2839 minimum * .001,
2840 maximum * .001,
2841 mean / perLoop100,
2842 stddev / perLoop100,
2843 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002844 maximum / perLoop100,
2845 meanCycles / perLoop1k,
2846 stddevCycles / perLoop1k,
2847 minCycles / perLoop1k,
2848 maxCycles / perLoop1k);
2849
Glenn Kasten83efdd02012-02-24 07:21:32 -08002850 }
2851 }
2852#endif
2853};
2854
Glenn Kasten37d825e2012-02-24 07:21:48 -08002855void AudioFlinger::PlaybackThread::checkSilentMode_l()
2856{
2857 if (!mMasterMute) {
2858 char value[PROPERTY_VALUE_MAX];
2859 if (property_get("ro.audio.silent", value, "0") > 0) {
2860 char *endptr;
2861 unsigned long ul = strtoul(value, &endptr, 0);
2862 if (*endptr == '\0' && ul != 0) {
2863 ALOGD("Silence is golden");
2864 // The setprop command will not allow a property to be changed after
2865 // the first time it is set, so we don't have to worry about un-muting.
2866 setMasterMute_l(true);
2867 }
2868 }
2869 }
2870}
2871
Glenn Kasten000f0e32012-03-01 17:10:56 -08002872bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873{
2874 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002875
Glenn Kasten000f0e32012-03-01 17:10:56 -08002876 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002877
2878 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002880
Glenn Kasten000f0e32012-03-01 17:10:56 -08002881 // DUPLICATING
2882 // FIXME could this be made local to while loop?
2883 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002884
Glenn Kasten66fcab92012-02-24 14:59:21 -08002885 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002886 sleepTime = idleSleepTime;
2887
Glenn Kasten9f34a362012-03-20 16:46:41 -07002888 if (mType == MIXER) {
2889 sleepTimeShift = 0;
2890 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002891
Glenn Kasten83efdd02012-02-24 07:21:32 -08002892 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002893 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894
Eric Laurentfeb0db62011-07-22 09:04:31 -07002895 acquireWakeLock();
2896
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 while (!exitPending())
2898 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002899 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002900
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002901 Vector< sp<EffectChain> > effectChains;
2902
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 processConfigEvents();
2904
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 { // scope for mLock
2906
2907 Mutex::Autolock _l(mLock);
2908
2909 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002910 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 }
2912
Glenn Kastenfa26a852012-03-06 11:28:04 -08002913 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002914
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002916 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002917 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002919
2920 threadLoop_standby();
2921
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 }
2924
Glenn Kasten3e074702012-02-28 18:40:35 -08002925 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 // we're about to wait, flush the binder command buffer
2927 IPCThreadState::self()->flushCommands();
2928
Glenn Kastenfa26a852012-03-06 11:28:04 -08002929 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002930
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 if (exitPending()) break;
2932
Eric Laurentfeb0db62011-07-22 09:04:31 -07002933 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002935 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002937 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002938 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Eric Laurentda747442012-04-25 18:53:13 -07002940 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002941 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002942 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002943
Glenn Kasten37d825e2012-02-24 07:21:48 -08002944 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945
Glenn Kasten000f0e32012-03-01 17:10:56 -08002946 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002948 if (mType == MIXER) {
2949 sleepTimeShift = 0;
2950 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002951
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 continue;
2953 }
2954 }
2955
Glenn Kasten81028042012-04-30 18:15:12 -07002956 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002957 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958
2959 // prevent any changes in effect chain list and in each effect chain
2960 // during mixing and effect process as the audio buffers could be deleted
2961 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002962 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964
Glenn Kastenfec279f2012-03-08 07:47:15 -08002965 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002966 threadLoop_mix();
2967 } else {
2968 threadLoop_sleepTime();
2969 }
2970
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002971 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002972 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002973 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002974 }
2975
2976 // only process effects if we're going to write
2977 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002978 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08002979#ifdef QCOM_HARDWARE
2980 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
2981#endif
2982 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002983 }
2984 }
2985
2986 // enable changes in effect chain
2987 unlockEffectChains(effectChains);
2988
2989 // sleepTime == 0 means we must write to audio hardware
2990 if (sleepTime == 0) {
2991
2992 threadLoop_write();
2993
2994if (mType == MIXER) {
2995 // write blocked detection
2996 nsecs_t now = systemTime();
2997 nsecs_t delta = now - mLastWriteTime;
2998 if (!mStandby && delta > maxPeriod) {
2999 mNumDelayedWrites++;
3000 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003001#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003002 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003003#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003004 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3005 ns2ms(delta), mNumDelayedWrites, this);
3006 lastWarning = now;
3007 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003008 }
3009}
3010
3011 mStandby = false;
3012 } else {
3013 usleep(sleepTime);
3014 }
3015
Glenn Kasten58912562012-04-03 10:45:00 -07003016 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003017 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003018 // same lock. This will also mutate and push a new fast mixer state.
3019 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003020 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003021
Glenn Kastenfa26a852012-03-06 11:28:04 -08003022 // FIXME I don't understand the need for this here;
3023 // it was in the original code but maybe the
3024 // assignment in saveOutputTracks() makes this unnecessary?
3025 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003026
3027 // Effect chains will be actually deleted here if they were removed from
3028 // mEffectChains list during mixing or effects processing
3029 effectChains.clear();
3030
3031 // FIXME Note that the above .clear() is no longer necessary since effectChains
3032 // is now local to this block, but will keep it for now (at least until merge done).
3033 }
3034
Glenn Kasten9f34a362012-03-20 16:46:41 -07003035 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3036 if (mType == MIXER || mType == DIRECT) {
3037 // put output stream into standby mode
3038 if (!mStandby) {
3039 mOutput->stream->common.standby(&mOutput->stream->common);
3040 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003041 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003042
3043 releaseWakeLock();
3044
3045 ALOGV("Thread %p type %d exiting", this, mType);
3046 return false;
3047}
3048
Glenn Kasten58912562012-04-03 10:45:00 -07003049void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3050{
Glenn Kasten58912562012-04-03 10:45:00 -07003051 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3052}
3053
3054void AudioFlinger::MixerThread::threadLoop_write()
3055{
3056 // FIXME we should only do one push per cycle; confirm this is true
3057 // Start the fast mixer if it's not already running
3058 if (mFastMixer != NULL) {
3059 FastMixerStateQueue *sq = mFastMixer->sq();
3060 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003061 if (state->mCommand != FastMixerState::MIX_WRITE &&
3062 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003063 if (state->mCommand == FastMixerState::COLD_IDLE) {
3064 int32_t old = android_atomic_inc(&mFastMixerFutex);
3065 if (old == -1) {
3066 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3067 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003068#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003069 if (mAudioWatchdog != 0) {
3070 mAudioWatchdog->resume();
3071 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003072#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003073 }
3074 state->mCommand = FastMixerState::MIX_WRITE;
3075 sq->end();
3076 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003077 if (kUseFastMixer == FastMixer_Dynamic) {
3078 mNormalSink = mPipeSink;
3079 }
Glenn Kasten58912562012-04-03 10:45:00 -07003080 } else {
3081 sq->end(false /*didModify*/);
3082 }
3083 }
3084 PlaybackThread::threadLoop_write();
3085}
3086
Glenn Kasten000f0e32012-03-01 17:10:56 -08003087// shared by MIXER and DIRECT, overridden by DUPLICATING
3088void AudioFlinger::PlaybackThread::threadLoop_write()
3089{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003090 // FIXME rewrite to reduce number of system calls
3091 mLastWriteTime = systemTime();
3092 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003093 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003094
Eric Laurent67c0a582012-05-01 19:31:12 -07003095 // If an NBAIO sink is present, use it to write the normal mixer's submix
3096 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003097#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003098 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003099#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003100 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003101#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003102 // update the setpoint when gScreenState changes
3103 uint32_t screenState = gScreenState;
3104 if (screenState != mScreenState) {
3105 mScreenState = screenState;
3106 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3107 if (pipe != NULL) {
3108 pipe->setAvgFrames((mScreenState & 1) ?
3109 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3110 }
3111 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003112 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003113#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003114 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003115#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003116 if (framesWritten > 0) {
3117 bytesWritten = framesWritten << mBitShift;
3118 } else {
3119 bytesWritten = framesWritten;
3120 }
3121 // otherwise use the HAL / AudioStreamOut directly
3122 } else {
3123 // Direct output thread.
3124 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003125 }
3126
Eric Laurent67c0a582012-05-01 19:31:12 -07003127 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003128 mNumWrites++;
3129 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003130}
3131
Glenn Kasten58912562012-04-03 10:45:00 -07003132void AudioFlinger::MixerThread::threadLoop_standby()
3133{
3134 // Idle the fast mixer if it's currently running
3135 if (mFastMixer != NULL) {
3136 FastMixerStateQueue *sq = mFastMixer->sq();
3137 FastMixerState *state = sq->begin();
3138 if (!(state->mCommand & FastMixerState::IDLE)) {
3139 state->mCommand = FastMixerState::COLD_IDLE;
3140 state->mColdFutexAddr = &mFastMixerFutex;
3141 state->mColdGen++;
3142 mFastMixerFutex = 0;
3143 sq->end();
3144 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3145 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003146 if (kUseFastMixer == FastMixer_Dynamic) {
3147 mNormalSink = mOutputSink;
3148 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003149#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003150 if (mAudioWatchdog != 0) {
3151 mAudioWatchdog->pause();
3152 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003153#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003154 } else {
3155 sq->end(false /*didModify*/);
3156 }
3157 }
3158 PlaybackThread::threadLoop_standby();
3159}
3160
Glenn Kasten000f0e32012-03-01 17:10:56 -08003161// shared by MIXER and DIRECT, overridden by DUPLICATING
3162void AudioFlinger::PlaybackThread::threadLoop_standby()
3163{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003164 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003165 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003166}
3167
3168void AudioFlinger::MixerThread::threadLoop_mix()
3169{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003170 // obtain the presentation timestamp of the next output buffer
3171 int64_t pts;
3172 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003173
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003174#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003175 if (mNormalSink != 0) {
3176 status = mNormalSink->getNextWriteTimestamp(&pts);
3177 } else {
3178 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003179 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003180#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003181
Glenn Kasten952eeb22012-03-06 11:30:57 -08003182 if (status != NO_ERROR) {
3183 pts = AudioBufferProvider::kInvalidPTS;
3184 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003185
Glenn Kasten952eeb22012-03-06 11:30:57 -08003186 // mix buffers...
3187 mAudioMixer->process(pts);
3188 // increase sleep time progressively when application underrun condition clears.
3189 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3190 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3191 // such that we would underrun the audio HAL.
3192 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3193 sleepTimeShift--;
3194 }
3195 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003196 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003197 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003198}
3199
3200void AudioFlinger::MixerThread::threadLoop_sleepTime()
3201{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003202 // If no tracks are ready, sleep once for the duration of an output
3203 // buffer size, then write 0s to the output
3204 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003205 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003206 sleepTime = activeSleepTime >> sleepTimeShift;
3207 if (sleepTime < kMinThreadSleepTimeUs) {
3208 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003210 // reduce sleep time in case of consecutive application underruns to avoid
3211 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3212 // duration we would end up writing less data than needed by the audio HAL if
3213 // the condition persists.
3214 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3215 sleepTimeShift++;
3216 }
3217 } else {
3218 sleepTime = idleSleepTime;
3219 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003220 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003221 memset (mMixBuffer, 0, mixBufferSize);
3222 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003223 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003224 }
3225 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226}
3227
3228// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003229AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003230 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231{
3232
Glenn Kasten29c23c32012-01-26 13:37:52 -08003233 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003235 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 size_t mixedTracks = 0;
3237 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003238 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003239 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003240 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241
3242 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003243 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244
Eric Laurent571d49c2010-08-11 05:20:11 -07003245 if (masterMute) {
3246 masterVolume = 0;
3247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003249 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003251 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003252 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 masterVolume = (float)((v + (1 << 23)) >> 24);
3254 chain.clear();
3255 }
3256
Glenn Kasten288ed212012-04-25 17:52:27 -07003257 // prepare a new state to push
3258 FastMixerStateQueue *sq = NULL;
3259 FastMixerState *state = NULL;
3260 bool didModify = false;
3261 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3262 if (mFastMixer != NULL) {
3263 sq = mFastMixer->sq();
3264 state = sq->begin();
3265 }
3266
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003268 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 if (t == 0) continue;
3270
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003271 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003273
Glenn Kasten288ed212012-04-25 17:52:27 -07003274 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003275 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003276
3277 // It's theoretically possible (though unlikely) for a fast track to be created
3278 // and then removed within the same normal mix cycle. This is not a problem, as
3279 // the track never becomes active so it's fast mixer slot is never touched.
3280 // The converse, of removing an (active) track and then creating a new track
3281 // at the identical fast mixer slot within the same normal mix cycle,
3282 // is impossible because the slot isn't marked available until the end of each cycle.
3283 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003284 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3285 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003286 FastTrack *fastTrack = &state->mFastTracks[j];
3287
3288 // Determine whether the track is currently in underrun condition,
3289 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003290 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3291 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003292 uint32_t recentFull = (underruns.mBitFields.mFull -
3293 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3294 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3295 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3296 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3297 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3298 uint32_t recentUnderruns = recentPartial + recentEmpty;
3299 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003300 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003301 // or stopped which can occur when flush() is called while active
3302 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003303 track->mUnderrunCount += recentUnderruns;
3304 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003305
Glenn Kastend08f48c2012-05-01 18:14:02 -07003306 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003307 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003308 bool isActive = true;
3309 switch (track->mState) {
3310 case TrackBase::STOPPING_1:
3311 // track stays active in STOPPING_1 state until first underrun
3312 if (recentUnderruns > 0) {
3313 track->mState = TrackBase::STOPPING_2;
3314 }
3315 break;
3316 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003317 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003318 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003319 break;
3320 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003321 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003322 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003323 break;
3324 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003325 if (recentFull > 0 || recentPartial > 0) {
3326 // track has provided at least some frames recently: reset retry count
3327 track->mRetryCount = kMaxTrackRetries;
3328 }
3329 if (recentUnderruns == 0) {
3330 // no recent underruns: stay active
3331 break;
3332 }
3333 // there has recently been an underrun of some kind
3334 if (track->sharedBuffer() == 0) {
3335 // were any of the recent underruns "empty" (no frames available)?
3336 if (recentEmpty == 0) {
3337 // no, then ignore the partial underruns as they are allowed indefinitely
3338 break;
3339 }
3340 // there has recently been an "empty" underrun: decrement the retry counter
3341 if (--(track->mRetryCount) > 0) {
3342 break;
3343 }
3344 // indicate to client process that the track was disabled because of underrun;
3345 // it will then automatically call start() when data is available
3346 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3347 // remove from active list, but state remains ACTIVE [confusing but true]
3348 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003349 break;
3350 }
3351 // fall through
3352 case TrackBase::STOPPING_2:
3353 case TrackBase::PAUSED:
3354 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003355 case TrackBase::STOPPED:
3356 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003357 // Check for presentation complete if track is inactive
3358 // We have consumed all the buffers of this track.
3359 // This would be incomplete if we auto-paused on underrun
3360 {
3361 size_t audioHALFrames =
3362 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3363 size_t framesWritten =
3364 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003365 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003366 // track stays in active list until presentation is complete
3367 break;
3368 }
3369 }
3370 if (track->isStopping_2()) {
3371 track->mState = TrackBase::STOPPED;
3372 }
3373 if (track->isStopped()) {
3374 // Can't reset directly, as fast mixer is still polling this track
3375 // track->reset();
3376 // So instead mark this track as needing to be reset after push with ack
3377 resetMask |= 1 << i;
3378 }
3379 isActive = false;
3380 break;
3381 case TrackBase::IDLE:
3382 default:
3383 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003384 }
3385
3386 if (isActive) {
3387 // was it previously inactive?
3388 if (!(state->mTrackMask & (1 << j))) {
3389 ExtendedAudioBufferProvider *eabp = track;
3390 VolumeProvider *vp = track;
3391 fastTrack->mBufferProvider = eabp;
3392 fastTrack->mVolumeProvider = vp;
3393 fastTrack->mSampleRate = track->mSampleRate;
3394 fastTrack->mChannelMask = track->mChannelMask;
3395 fastTrack->mGeneration++;
3396 state->mTrackMask |= 1 << j;
3397 didModify = true;
3398 // no acknowledgement required for newly active tracks
3399 }
3400 // cache the combined master volume and stream type volume for fast mixer; this
3401 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3402 track->mCachedVolume = track->isMuted() ?
3403 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3404 ++fastTracks;
3405 } else {
3406 // was it previously active?
3407 if (state->mTrackMask & (1 << j)) {
3408 fastTrack->mBufferProvider = NULL;
3409 fastTrack->mGeneration++;
3410 state->mTrackMask &= ~(1 << j);
3411 didModify = true;
3412 // If any fast tracks were removed, we must wait for acknowledgement
3413 // because we're about to decrement the last sp<> on those tracks.
3414 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003415 } else {
3416 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003417 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003418 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003419 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003420 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003421 }
3422 continue;
3423 }
3424
3425 { // local variable scope to avoid goto warning
3426
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 audio_track_cblk_t* cblk = track->cblk();
3428
3429 // The first time a track is added we wait
3430 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003431 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003432 // make sure that we have enough frames to mix one full buffer.
3433 // enforce this condition only once to enable draining the buffer in case the client
3434 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003435 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003436 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003437 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003438 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003439 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003440 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003441 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003442 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003443 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003444 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003445 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003446 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003447 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3448 // the minimum track buffer size is normally twice the number of frames necessary
3449 // to fill one buffer and the resampler should not leave more than one buffer worth
3450 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003451 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003452 }
3453 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003454 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 !track->isPaused() && !track->isTerminated())
3456 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003457 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458
3459 mixedTracks++;
3460
3461 // track->mainBuffer() != mMixBuffer means there is an effect chain
3462 // connected to the track
3463 chain.clear();
3464 if (track->mainBuffer() != mMixBuffer) {
3465 chain = getEffectChain_l(track->sessionId());
3466 // Delegate volume control to effect in track effect chain if needed
3467 if (chain != 0) {
3468 tracksWithEffect++;
3469 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003470 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003471 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 }
3473 }
3474
3475
3476 int param = AudioMixer::VOLUME;
3477 if (track->mFillingUpStatus == Track::FS_FILLED) {
3478 // no ramp for the first volume setting
3479 track->mFillingUpStatus = Track::FS_ACTIVE;
3480 if (track->mState == TrackBase::RESUMING) {
3481 track->mState = TrackBase::ACTIVE;
3482 param = AudioMixer::RAMP_VOLUME;
3483 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003484 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 } else if (cblk->server != 0) {
3486 // If the track is stopped before the first frame was mixed,
3487 // do not apply ramp
3488 param = AudioMixer::RAMP_VOLUME;
3489 }
3490
3491 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003492 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003493 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003494 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003495 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 if (track->isPausing()) {
3497 track->setPaused();
3498 }
3499 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003500
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003502 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003504 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003505 vl = vlr & 0xFFFF;
3506 vr = vlr >> 16;
3507 // track volumes come from shared memory, so can't be trusted and must be clamped
3508 if (vl > MAX_GAIN_INT) {
3509 ALOGV("Track left volume out of range: %04X", vl);
3510 vl = MAX_GAIN_INT;
3511 }
3512 if (vr > MAX_GAIN_INT) {
3513 ALOGV("Track right volume out of range: %04X", vr);
3514 vr = MAX_GAIN_INT;
3515 }
3516 // now apply the master volume and stream type volume
3517 vl = (uint32_t)(v * vl) << 12;
3518 vr = (uint32_t)(v * vr) << 12;
3519 // assuming master volume and stream type volume each go up to 1.0,
3520 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521
Glenn Kasten05632a52012-01-03 14:22:33 -08003522 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3523 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003524 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003525 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003526 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003527 }
3528 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003530 // Delegate volume control to effect in track effect chain if needed
3531 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3532 // Do not ramp volume if volume is controlled by effect
3533 param = AudioMixer::VOLUME;
3534 track->mHasVolumeController = true;
3535 } else {
3536 // force no volume ramp when volume controller was just disabled or removed
3537 // from effect chain to avoid volume spike
3538 if (track->mHasVolumeController) {
3539 param = AudioMixer::VOLUME;
3540 }
3541 track->mHasVolumeController = false;
3542 }
3543
3544 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003545 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003546 vl = (vl + (1 << 11)) >> 12;
3547 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3548 vr = (vr + (1 << 11)) >> 12;
3549 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003550
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003551 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 -07003552
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003554 mAudioMixer->setBufferProvider(name, track);
3555 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003557 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3558 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3559 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003561 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 AudioMixer::TRACK,
3563 AudioMixer::FORMAT, (void *)track->format());
3564 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003565 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003567 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003569 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 AudioMixer::RESAMPLE,
3571 AudioMixer::SAMPLE_RATE,
3572 (void *)(cblk->sampleRate));
3573 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003574 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 AudioMixer::TRACK,
3576 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3577 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003578 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 AudioMixer::TRACK,
3580 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3581
3582 // reset retry count
3583 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003584
Eric Laurent27741442012-01-17 19:20:12 -08003585 // If one track is ready, set the mixer ready if:
3586 // - the mixer was not ready during previous round OR
3587 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003588 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003589 mixerStatus != MIXER_TRACKS_ENABLED) {
3590 mixerStatus = MIXER_TRACKS_READY;
3591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003593 // clear effect chain input buffer if an active track underruns to avoid sending
3594 // previous audio buffer again to effects
3595 chain = getEffectChain_l(track->sessionId());
3596 if (chain != 0) {
3597 chain->clearInputBuffer();
3598 }
3599
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003600 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003601 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003602 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 // We have consumed all the buffers of this track.
3604 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003605 // TODO: use actual buffer filling status instead of latency when available from
3606 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003607 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003608 size_t framesWritten =
3609 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003610 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003611 if (track->isStopped()) {
3612 track->reset();
3613 }
Eric Laurenta011e352012-03-29 15:51:43 -07003614 tracksToRemove->add(track);
3615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003617 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 // No buffers for this track. Give it a few chances to
3619 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003620 if (--(track->mRetryCount) <= 0) {
3621 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003623 // indicate to client process that the track was disabled because of underrun;
3624 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003625 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003626 // If one track is not ready, mark the mixer also not ready if:
3627 // - the mixer was ready during previous round OR
3628 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003629 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003630 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 mixerStatus = MIXER_TRACKS_ENABLED;
3632 }
3633 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003634 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 }
Glenn Kasten58912562012-04-03 10:45:00 -07003636
3637 } // local variable scope to avoid goto warning
3638track_is_ready: ;
3639
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 }
3641
Glenn Kasten288ed212012-04-25 17:52:27 -07003642 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003643 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003644 if (didModify) {
3645 state->mFastTracksGen++;
3646 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3647 if (kUseFastMixer == FastMixer_Dynamic &&
3648 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3649 state->mCommand = FastMixerState::COLD_IDLE;
3650 state->mColdFutexAddr = &mFastMixerFutex;
3651 state->mColdGen++;
3652 mFastMixerFutex = 0;
3653 if (kUseFastMixer == FastMixer_Dynamic) {
3654 mNormalSink = mOutputSink;
3655 }
3656 // If we go into cold idle, need to wait for acknowledgement
3657 // so that fast mixer stops doing I/O.
3658 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003659 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003660 }
3661 sq->end();
3662 }
3663 if (sq != NULL) {
3664 sq->end(didModify);
3665 sq->push(block);
3666 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003667#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003668 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3669 mAudioWatchdog->pause();
3670 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003671#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003672
3673 // Now perform the deferred reset on fast tracks that have stopped
3674 while (resetMask != 0) {
3675 size_t i = __builtin_ctz(resetMask);
3676 ALOG_ASSERT(i < count);
3677 resetMask &= ~(1 << i);
3678 sp<Track> t = mActiveTracks[i].promote();
3679 if (t == 0) continue;
3680 Track* track = t.get();
3681 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3682 track->reset();
3683 }
Glenn Kasten58912562012-04-03 10:45:00 -07003684
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 // remove all the tracks that need to be...
3686 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003687 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 for (size_t i=0 ; i<count ; i++) {
3689 const sp<Track>& track = tracksToRemove->itemAt(i);
3690 mActiveTracks.remove(track);
3691 if (track->mainBuffer() != mMixBuffer) {
3692 chain = getEffectChain_l(track->sessionId());
3693 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003694 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003695 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 }
3697 }
3698 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003699 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 }
3701 }
3702 }
3703
3704 // mix buffer must be cleared if all tracks are connected to an
3705 // effect chain as in this case the mixer will not write to
3706 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003707 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3708 // FIXME as a performance optimization, should remember previous zero status
3709 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 }
3711
Glenn Kasten58912562012-04-03 10:45:00 -07003712 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003713 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003714 if (fastTracks > 0) {
3715 mixerStatus = MIXER_TRACKS_READY;
3716 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 return mixerStatus;
3718}
3719
Glenn Kasten66fcab92012-02-24 14:59:21 -08003720/*
3721The derived values that are cached:
3722 - mixBufferSize from frame count * frame size
3723 - activeSleepTime from activeSleepTimeUs()
3724 - idleSleepTime from idleSleepTimeUs()
3725 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3726 - maxPeriod from frame count and sample rate (MIXER only)
3727
3728The parameters that affect these derived values are:
3729 - frame count
3730 - frame size
3731 - sample rate
3732 - device type: A2DP or not
3733 - device latency
3734 - format: PCM or not
3735 - active sleep time
3736 - idle sleep time
3737*/
3738
3739void AudioFlinger::PlaybackThread::cacheParameters_l()
3740{
Glenn Kasten58912562012-04-03 10:45:00 -07003741 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003742 activeSleepTime = activeSleepTimeUs();
3743 idleSleepTime = idleSleepTimeUs();
3744}
3745
Eric Laurent22167852012-06-20 12:26:32 -07003746void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747{
Steve Block3856b092011-10-20 11:56:00 +01003748 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003749 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003751
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 size_t size = mTracks.size();
3753 for (size_t i = 0; i < size; i++) {
3754 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003755 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003756 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 }
3759 }
3760}
3761
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003763int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003765 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766}
3767
3768// deleteTrackName_l() must be called with ThreadBase::mLock held
3769void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3770{
Steve Block3856b092011-10-20 11:56:00 +01003771 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 mAudioMixer->deleteTrackName(name);
3773}
3774
3775// checkForNewParameters_l() must be called with ThreadBase::mLock held
3776bool AudioFlinger::MixerThread::checkForNewParameters_l()
3777{
Glenn Kasten58912562012-04-03 10:45:00 -07003778 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3779 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 bool reconfig = false;
3781
3782 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003783
3784 if (mFastMixer != NULL) {
3785 FastMixerStateQueue *sq = mFastMixer->sq();
3786 FastMixerState *state = sq->begin();
3787 if (!(state->mCommand & FastMixerState::IDLE)) {
3788 previousCommand = state->mCommand;
3789 state->mCommand = FastMixerState::HOT_IDLE;
3790 sq->end();
3791 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3792 } else {
3793 sq->end(false /*didModify*/);
3794 }
3795 }
3796
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 status_t status = NO_ERROR;
3798 String8 keyValuePair = mNewParameters[0];
3799 AudioParameter param = AudioParameter(keyValuePair);
3800 int value;
3801
3802 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3803 reconfig = true;
3804 }
3805 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003806 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 status = BAD_VALUE;
3808 } else {
3809 reconfig = true;
3810 }
3811 }
3812 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003813 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 status = BAD_VALUE;
3815 } else {
3816 reconfig = true;
3817 }
3818 }
3819 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3820 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003821 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 // if frame count is changed after track creation
3823 if (!mTracks.isEmpty()) {
3824 status = INVALID_OPERATION;
3825 } else {
3826 reconfig = true;
3827 }
3828 }
3829 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003830#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003831 // when changing the audio output device, call addBatteryData to notify
3832 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003833 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003834 uint32_t params = 0;
3835 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003836 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003837 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3838 }
3839
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003840 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003841 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003842 // check if any other device (except speaker) is on
3843 if (value & deviceWithoutSpeaker ) {
3844 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3845 }
3846
3847 if (params != 0) {
3848 addBatteryData(params);
3849 }
3850 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003851#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003852
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 // forward device change to effects that have requested to be
3854 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003855 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003857 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 }
3859 }
3860
3861 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003862 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003863 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003865 mOutput->stream->common.standby(&mOutput->stream->common);
3866 mStandby = true;
3867 mBytesWritten = 0;
3868 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003869 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 }
3871 if (status == NO_ERROR && reconfig) {
3872 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003873 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3874 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003876 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003878 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 if (name < 0) break;
3880 mTracks[i]->mName = name;
3881 // limit track sample rate to 2 x new output sample rate
3882 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3883 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3884 }
3885 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003886 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 }
3888 }
3889
3890 mNewParameters.removeAt(0);
3891
3892 mParamStatus = status;
3893 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003894 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3895 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003896 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 }
Glenn Kasten58912562012-04-03 10:45:00 -07003898
3899 if (!(previousCommand & FastMixerState::IDLE)) {
3900 ALOG_ASSERT(mFastMixer != NULL);
3901 FastMixerStateQueue *sq = mFastMixer->sq();
3902 FastMixerState *state = sq->begin();
3903 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3904 state->mCommand = previousCommand;
3905 sq->end();
3906 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3907 }
3908
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 return reconfig;
3910}
3911
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003912void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913{
3914 const size_t SIZE = 256;
3915 char buffer[SIZE];
3916 String8 result;
3917
3918 PlaybackThread::dumpInternals(fd, args);
3919
3920 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3921 result.append(buffer);
3922 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003923
3924 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3925 FastMixerDumpState copy = mFastMixerDumpState;
3926 copy.dump(fd);
3927
Glenn Kasten39993082012-05-31 13:40:27 -07003928#ifdef STATE_QUEUE_DUMP
3929 // Similar for state queue
3930 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3931 observerCopy.dump(fd);
3932 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3933 mutatorCopy.dump(fd);
3934#endif
3935
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003936 // Write the tee output to a .wav file
3937 NBAIO_Source *teeSource = mTeeSource.get();
3938 if (teeSource != NULL) {
3939 char teePath[64];
3940 struct timeval tv;
3941 gettimeofday(&tv, NULL);
3942 struct tm tm;
3943 localtime_r(&tv.tv_sec, &tm);
3944 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3945 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3946 if (teeFd >= 0) {
3947 char wavHeader[44];
3948 memcpy(wavHeader,
3949 "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",
3950 sizeof(wavHeader));
3951 NBAIO_Format format = teeSource->format();
3952 unsigned channelCount = Format_channelCount(format);
3953 ALOG_ASSERT(channelCount <= FCC_2);
3954 unsigned sampleRate = Format_sampleRate(format);
3955 wavHeader[22] = channelCount; // number of channels
3956 wavHeader[24] = sampleRate; // sample rate
3957 wavHeader[25] = sampleRate >> 8;
3958 wavHeader[32] = channelCount * 2; // block alignment
3959 write(teeFd, wavHeader, sizeof(wavHeader));
3960 size_t total = 0;
3961 bool firstRead = true;
3962 for (;;) {
3963#define TEE_SINK_READ 1024
3964 short buffer[TEE_SINK_READ * FCC_2];
3965 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003966 ssize_t actual = teeSource->read(buffer, count,
3967 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003968 bool wasFirstRead = firstRead;
3969 firstRead = false;
3970 if (actual <= 0) {
3971 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3972 continue;
3973 }
3974 break;
3975 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003976 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003977 write(teeFd, buffer, actual * channelCount * sizeof(short));
3978 total += actual;
3979 }
3980 lseek(teeFd, (off_t) 4, SEEK_SET);
3981 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3982 write(teeFd, &temp, sizeof(temp));
3983 lseek(teeFd, (off_t) 40, SEEK_SET);
3984 temp = total * channelCount * sizeof(short);
3985 write(teeFd, &temp, sizeof(temp));
3986 close(teeFd);
3987 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3988 } else {
3989 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3990 }
3991 }
3992
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003993#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003994 if (mAudioWatchdog != 0) {
3995 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3996 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3997 wdCopy.dump(fd);
3998 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003999#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000}
4001
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004002uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003{
Glenn Kasten58912562012-04-03 10:45:00 -07004004 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005}
4006
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004007uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004008{
Glenn Kasten58912562012-04-03 10:45:00 -07004009 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004010}
4011
Glenn Kasten66fcab92012-02-24 14:59:21 -08004012void AudioFlinger::MixerThread::cacheParameters_l()
4013{
4014 PlaybackThread::cacheParameters_l();
4015
4016 // FIXME: Relaxed timing because of a certain device that can't meet latency
4017 // Should be reduced to 2x after the vendor fixes the driver issue
4018 // increase threshold again due to low power audio mode. The way this warning
4019 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004020 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004021}
4022
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004024AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004025 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004026 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004027 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
4031AudioFlinger::DirectOutputThread::~DirectOutputThread()
4032{
4033}
4034
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004035AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4036 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004037)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004039 sp<Track> trackToRemove;
4040
Glenn Kastenfec279f2012-03-08 07:47:15 -08004041 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042
Glenn Kasten952eeb22012-03-06 11:30:57 -08004043 // find out which tracks need to be processed
4044 if (mActiveTracks.size() != 0) {
4045 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004046 // The track died recently
4047 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048
Glenn Kasten952eeb22012-03-06 11:30:57 -08004049 Track* const track = t.get();
4050 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051
Glenn Kasten952eeb22012-03-06 11:30:57 -08004052 // The first time a track is added we wait
4053 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004054 uint32_t minFrames;
4055 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4056 minFrames = mNormalFrameCount;
4057 } else {
4058 minFrames = 1;
4059 }
4060 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004061 !track->isPaused() && !track->isTerminated())
4062 {
4063 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064
Glenn Kasten952eeb22012-03-06 11:30:57 -08004065 if (track->mFillingUpStatus == Track::FS_FILLED) {
4066 track->mFillingUpStatus = Track::FS_ACTIVE;
4067 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004068 if (track->mState == TrackBase::RESUMING) {
4069 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004070 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004071 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004072
Glenn Kasten952eeb22012-03-06 11:30:57 -08004073 // compute volume for this track
4074 float left, right;
4075 if (track->isMuted() || mMasterMute || track->isPausing() ||
4076 mStreamTypes[track->streamType()].mute) {
4077 left = right = 0;
4078 if (track->isPausing()) {
4079 track->setPaused();
4080 }
4081 } else {
4082 float typeVolume = mStreamTypes[track->streamType()].volume;
4083 float v = mMasterVolume * typeVolume;
4084 uint32_t vlr = cblk->getVolumeLR();
4085 float v_clamped = v * (vlr & 0xFFFF);
4086 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4087 left = v_clamped/MAX_GAIN;
4088 v_clamped = v * (vlr >> 16);
4089 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4090 right = v_clamped/MAX_GAIN;
4091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092
Glenn Kasten952eeb22012-03-06 11:30:57 -08004093 if (left != mLeftVolFloat || right != mRightVolFloat) {
4094 mLeftVolFloat = left;
4095 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096
Glenn Kasten952eeb22012-03-06 11:30:57 -08004097 // Convert volumes from float to 8.24
4098 uint32_t vl = (uint32_t)(left * (1 << 24));
4099 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100
Glenn Kasten952eeb22012-03-06 11:30:57 -08004101 // Delegate volume control to effect in track effect chain if needed
4102 // only one effect chain can be present on DirectOutputThread, so if
4103 // there is one, the track is connected to it
4104 if (!mEffectChains.isEmpty()) {
4105 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004106 mEffectChains[0]->setVolume_l(&vl, &vr);
4107 left = (float)vl / (1 << 24);
4108 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004109 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004110 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004111 }
4112
4113 // reset retry count
4114 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004115 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004116 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004117 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004118 // clear effect chain input buffer if an active track underruns to avoid sending
4119 // previous audio buffer again to effects
4120 if (!mEffectChains.isEmpty()) {
4121 mEffectChains[0]->clearInputBuffer();
4122 }
4123
Glenn Kasten952eeb22012-03-06 11:30:57 -08004124 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004125 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004126 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004127 // We have consumed all the buffers of this track.
4128 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004129 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004130 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004131 size_t framesWritten =
4132 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004133 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004134 if (track->isStopped()) {
4135 track->reset();
4136 }
Eric Laurenta011e352012-03-29 15:51:43 -07004137 trackToRemove = track;
4138 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004139 } else {
4140 // No buffers for this track. Give it a few chances to
4141 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004142 if (--(track->mRetryCount) <= 0) {
4143 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004144 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004146 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 }
4148 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004149 }
4150 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004152 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004153 // remove all the tracks that need to be...
4154 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004155 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004156 mActiveTracks.remove(trackToRemove);
4157 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004158 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004159 trackToRemove->sessionId());
4160 mEffectChains[0]->decActiveTrackCnt();
4161 }
4162 if (trackToRemove->isTerminated()) {
4163 removeTrack_l(trackToRemove);
4164 }
4165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166
Glenn Kastenfec279f2012-03-08 07:47:15 -08004167 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004168}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169
Glenn Kasten000f0e32012-03-01 17:10:56 -08004170void AudioFlinger::DirectOutputThread::threadLoop_mix()
4171{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004172 AudioBufferProvider::Buffer buffer;
4173 size_t frameCount = mFrameCount;
4174 int8_t *curBuf = (int8_t *)mMixBuffer;
4175 // output audio to hardware
4176 while (frameCount) {
4177 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004178 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004179 if (CC_UNLIKELY(buffer.raw == NULL)) {
4180 memset(curBuf, 0, frameCount * mFrameSize);
4181 break;
4182 }
4183 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4184 frameCount -= buffer.frameCount;
4185 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004186 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004187 }
4188 sleepTime = 0;
4189 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004190 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004191
Glenn Kasten000f0e32012-03-01 17:10:56 -08004192}
4193
4194void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4195{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004196 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004197 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004198 sleepTime = activeSleepTime;
4199 } else {
4200 sleepTime = idleSleepTime;
4201 }
4202 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004203 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004204 sleepTime = 0;
4205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206}
4207
4208// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004209int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4210 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211{
4212 return 0;
4213}
4214
4215// deleteTrackName_l() must be called with ThreadBase::mLock held
4216void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4217{
4218}
4219
4220// checkForNewParameters_l() must be called with ThreadBase::mLock held
4221bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4222{
4223 bool reconfig = false;
4224
4225 while (!mNewParameters.isEmpty()) {
4226 status_t status = NO_ERROR;
4227 String8 keyValuePair = mNewParameters[0];
4228 AudioParameter param = AudioParameter(keyValuePair);
4229 int value;
4230
4231 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4232 // do not accept frame count changes if tracks are open as the track buffer
4233 // size depends on frame count and correct behavior would not be garantied
4234 // if frame count is changed after track creation
4235 if (!mTracks.isEmpty()) {
4236 status = INVALID_OPERATION;
4237 } else {
4238 reconfig = true;
4239 }
4240 }
4241 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004242 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004243 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004245 mOutput->stream->common.standby(&mOutput->stream->common);
4246 mStandby = true;
4247 mBytesWritten = 0;
4248 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004249 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 }
4251 if (status == NO_ERROR && reconfig) {
4252 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004253 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 }
4255 }
4256
4257 mNewParameters.removeAt(0);
4258
4259 mParamStatus = status;
4260 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004261 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4262 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004263 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 }
4265 return reconfig;
4266}
4267
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004268uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269{
4270 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004271 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004272 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 } else {
4274 time = 10000;
4275 }
4276 return time;
4277}
4278
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004279uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280{
4281 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004282 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004283 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 } else {
4285 time = 10000;
4286 }
4287 return time;
4288}
4289
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004290uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004291{
4292 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004293 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004294 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4295 } else {
4296 time = 10000;
4297 }
4298 return time;
4299}
4300
Glenn Kasten66fcab92012-02-24 14:59:21 -08004301void AudioFlinger::DirectOutputThread::cacheParameters_l()
4302{
4303 PlaybackThread::cacheParameters_l();
4304
4305 // use shorter standby delay as on normal output to release
4306 // hardware resources as soon as possible
4307 standbyDelay = microseconds(activeSleepTime*2);
4308}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004309
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310// ----------------------------------------------------------------------------
4311
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004312AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004313 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004314 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004315 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 addOutputTrack(mainThread);
4318}
4319
4320AudioFlinger::DuplicatingThread::~DuplicatingThread()
4321{
4322 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4323 mOutputTracks[i]->destroy();
4324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325}
4326
Glenn Kasten000f0e32012-03-01 17:10:56 -08004327void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004329 // mix buffers...
4330 if (outputsReady(outputTracks)) {
4331 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4332 } else {
4333 memset(mMixBuffer, 0, mixBufferSize);
4334 }
4335 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004336 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004337 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004338}
4339
4340void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4341{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004342 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004343 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004344 sleepTime = activeSleepTime;
4345 } else {
4346 sleepTime = idleSleepTime;
4347 }
4348 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004349 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4350 writeFrames = mNormalFrameCount;
4351 memset(mMixBuffer, 0, mixBufferSize);
4352 } else {
4353 // flush remaining overflow buffers in output tracks
4354 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004355 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004356 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004357 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004358}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359
Glenn Kasten000f0e32012-03-01 17:10:56 -08004360void AudioFlinger::DuplicatingThread::threadLoop_write()
4361{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004362 for (size_t i = 0; i < outputTracks.size(); i++) {
4363 outputTracks[i]->write(mMixBuffer, writeFrames);
4364 }
4365 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004366}
Glenn Kasten688a6402012-02-29 07:57:06 -08004367
Glenn Kasten000f0e32012-03-01 17:10:56 -08004368void AudioFlinger::DuplicatingThread::threadLoop_standby()
4369{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004370 // DuplicatingThread implements standby by stopping all tracks
4371 for (size_t i = 0; i < outputTracks.size(); i++) {
4372 outputTracks[i]->stop();
4373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374}
4375
Glenn Kastenfa26a852012-03-06 11:28:04 -08004376void AudioFlinger::DuplicatingThread::saveOutputTracks()
4377{
4378 outputTracks = mOutputTracks;
4379}
4380
4381void AudioFlinger::DuplicatingThread::clearOutputTracks()
4382{
4383 outputTracks.clear();
4384}
4385
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4387{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004388 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004389 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004390 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004391 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 this,
4393 mSampleRate,
4394 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004395 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 frameCount);
4397 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004398 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004400 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004401 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 }
4403}
4404
4405void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4406{
4407 Mutex::Autolock _l(mLock);
4408 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004409 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 mOutputTracks[i]->destroy();
4411 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004412 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 return;
4414 }
4415 }
Steve Block3856b092011-10-20 11:56:00 +01004416 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417}
4418
Glenn Kasten438b0362012-03-06 11:24:48 -08004419// caller must hold mLock
4420void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421{
4422 mWaitTimeMs = UINT_MAX;
4423 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4424 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004425 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4427 if (waitTimeMs < mWaitTimeMs) {
4428 mWaitTimeMs = waitTimeMs;
4429 }
4430 }
4431 }
4432}
4433
4434
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004435bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436{
4437 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004438 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004440 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 return false;
4442 }
4443 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004444 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004446 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 return false;
4448 }
4449 }
4450 return true;
4451}
4452
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004453uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454{
4455 return (mWaitTimeMs * 1000) / 2;
4456}
4457
Glenn Kasten66fcab92012-02-24 14:59:21 -08004458void AudioFlinger::DuplicatingThread::cacheParameters_l()
4459{
4460 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4461 updateWaitTime_l();
4462
4463 MixerThread::cacheParameters_l();
4464}
4465
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466// ----------------------------------------------------------------------------
4467
4468// TrackBase constructor must be called with AudioFlinger::mLock held
4469AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004470 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 const sp<Client>& client,
4472 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004473 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004474 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 const sp<IMemory>& sharedBuffer,
4477 int sessionId)
4478 : RefBase(),
4479 mThread(thread),
4480 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004481 mCblk(NULL),
4482 // mBuffer
4483 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 mFrameCount(0),
4485 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004486 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004488 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004490 // mChannelCount
4491 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492{
Steve Block3856b092011-10-20 11:56:00 +01004493 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494
Steve Blockb8a80522011-12-20 16:23:08 +00004495 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004496 size_t size = sizeof(audio_track_cblk_t);
4497 uint8_t channelCount = popcount(channelMask);
4498 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4499 if (sharedBuffer == 0) {
4500 size += bufferSize;
4501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004503 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 mCblkMemory = client->heap()->allocate(size);
4505 if (mCblkMemory != 0) {
4506 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004507 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 new(mCblk) audio_track_cblk_t();
4509 // clear all buffers
4510 mCblk->frameCount = frameCount;
4511 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004512// uncomment the following lines to quickly test 32-bit wraparound
4513// mCblk->user = 0xffff0000;
4514// mCblk->server = 0xffff0000;
4515// mCblk->userBase = 0xffff0000;
4516// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004517 mChannelCount = channelCount;
4518 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 if (sharedBuffer == 0) {
4520 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4521 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4522 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004523 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 mCblk->flags = CBLK_UNDERRUN_ON;
4525 } else {
4526 mBuffer = sharedBuffer->pointer();
4527 }
4528 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4529 }
4530 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004531 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 client->heap()->dump("AudioTrack");
4533 return;
4534 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004535 } else {
4536 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004537 // construct the shared structure in-place.
4538 new(mCblk) audio_track_cblk_t();
4539 // clear all buffers
4540 mCblk->frameCount = frameCount;
4541 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004542// uncomment the following lines to quickly test 32-bit wraparound
4543// mCblk->user = 0xffff0000;
4544// mCblk->server = 0xffff0000;
4545// mCblk->userBase = 0xffff0000;
4546// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004547 mChannelCount = channelCount;
4548 mChannelMask = channelMask;
4549 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4550 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4551 // Force underrun condition to avoid false underrun callback until first data is
4552 // written to buffer (other flags are cleared)
4553 mCblk->flags = CBLK_UNDERRUN_ON;
4554 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556}
4557
4558AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4559{
Glenn Kastena0d68332012-01-27 16:47:15 -08004560 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004561 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004563 } else {
4564 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 }
4566 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004567 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004568 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004569 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004571 // If the client's reference count drops to zero, the associated destructor
4572 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4573 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 mClient.clear();
4575 }
4576}
4577
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004578// AudioBufferProvider interface
4579// getNextBuffer() = 0;
4580// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4582{
Glenn Kastene0feee32011-12-13 11:53:26 -08004583 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004585 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004586 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 buffer->frameCount = 0;
4588}
4589
4590bool AudioFlinger::ThreadBase::TrackBase::step() {
4591 bool result;
4592 audio_track_cblk_t* cblk = this->cblk();
4593
4594 result = cblk->stepServer(mFrameCount);
4595 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004596 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004597 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 return result;
4600}
4601
4602void AudioFlinger::ThreadBase::TrackBase::reset() {
4603 audio_track_cblk_t* cblk = this->cblk();
4604
4605 cblk->user = 0;
4606 cblk->server = 0;
4607 cblk->userBase = 0;
4608 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004609 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004610 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611}
4612
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4614 return (int)mCblk->sampleRate;
4615}
4616
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4618 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004619 size_t frameSize = cblk->frameSize;
4620 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4621 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622
4623 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004624 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4625 "TrackBase::getBuffer buffer out of range:\n"
4626 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4627 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004629 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630
4631 return bufferStart;
4632}
4633
Eric Laurenta011e352012-03-29 15:51:43 -07004634status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4635{
4636 mSyncEvents.add(event);
4637 return NO_ERROR;
4638}
4639
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640// ----------------------------------------------------------------------------
4641
4642// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4643AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004644 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004646 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004648 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004649 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 int frameCount,
4651 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004652 int sessionId,
4653 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004654 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004655 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004656 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004657 // mRetryCount initialized later when needed
4658 mSharedBuffer(sharedBuffer),
4659 mStreamType(streamType),
4660 mName(-1), // see note below
4661 mMainBuffer(thread->mixBuffer()),
4662 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004663 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004664 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004665 mFlags(flags),
4666 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004667 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004668 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669{
4670 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4672 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004673 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004674 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004675 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004676 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004677 if (mName < 0) {
4678 ALOGE("no more track names available");
4679 return;
4680 }
4681 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004682 if (flags & IAudioFlinger::TRACK_FAST) {
4683 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4684 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4685 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004686 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004687 // FIXME This is too eager. We allocate a fast track index before the
4688 // fast track becomes active. Since fast tracks are a scarce resource,
4689 // this means we are potentially denying other more important fast tracks from
4690 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004691 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004692 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004693 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004694 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004695 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004698 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699}
4700
4701AudioFlinger::PlaybackThread::Track::~Track()
4702{
Steve Block3856b092011-10-20 11:56:00 +01004703 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004704}
4705
4706void AudioFlinger::PlaybackThread::Track::destroy()
4707{
4708 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4709 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004710 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 // we must acquire a strong reference on this Track before locking mLock
4712 // here so that the destructor is called only when exiting this function.
4713 // On the other hand, as long as Track::destroy() is only called by
4714 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4715 // this Track with its member mTrack.
4716 sp<Track> keep(this);
4717 { // scope for mLock
4718 sp<ThreadBase> thread = mThread.promote();
4719 if (thread != 0) {
4720 if (!isOutputTrack()) {
4721 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004722 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004723
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004724#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004725 // to track the speaker usage
4726 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004727#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 }
4729 AudioSystem::releaseOutput(thread->id());
4730 }
4731 Mutex::Autolock _l(thread->mLock);
4732 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4733 playbackThread->destroyTrack_l(this);
4734 }
4735 }
4736}
4737
Glenn Kasten288ed212012-04-25 17:52:27 -07004738/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4739{
Glenn Kastene213c862012-04-25 13:46:15 -07004740 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 -07004741 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004742}
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4745{
Glenn Kasten83d86532012-01-17 14:39:34 -08004746 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004747 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004748 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004749 } else {
4750 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4751 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004752 track_state state = mState;
4753 char stateChar;
4754 switch (state) {
4755 case IDLE:
4756 stateChar = 'I';
4757 break;
4758 case TERMINATED:
4759 stateChar = 'T';
4760 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004761 case STOPPING_1:
4762 stateChar = 's';
4763 break;
4764 case STOPPING_2:
4765 stateChar = '5';
4766 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004767 case STOPPED:
4768 stateChar = 'S';
4769 break;
4770 case RESUMING:
4771 stateChar = 'R';
4772 break;
4773 case ACTIVE:
4774 stateChar = 'A';
4775 break;
4776 case PAUSING:
4777 stateChar = 'p';
4778 break;
4779 case PAUSED:
4780 stateChar = 'P';
4781 break;
Eric Laurent29864602012-05-08 18:57:51 -07004782 case FLUSHED:
4783 stateChar = 'F';
4784 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004785 default:
4786 stateChar = '?';
4787 break;
4788 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004789 char nowInUnderrun;
4790 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4791 case UNDERRUN_FULL:
4792 nowInUnderrun = ' ';
4793 break;
4794 case UNDERRUN_PARTIAL:
4795 nowInUnderrun = '<';
4796 break;
4797 case UNDERRUN_EMPTY:
4798 nowInUnderrun = '*';
4799 break;
4800 default:
4801 nowInUnderrun = '?';
4802 break;
4803 }
Glenn Kastene213c862012-04-25 13:46:15 -07004804 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4805 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004806 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 mStreamType,
4808 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004809 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004810 mSessionId,
4811 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004812 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004813 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 mMute,
4815 mFillingUpStatus,
4816 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004817 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4818 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 mCblk->server,
4820 mCblk->user,
4821 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004822 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004823 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004824 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004825 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004826}
4827
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004828// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004829status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004830 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004832 audio_track_cblk_t* cblk = this->cblk();
4833 uint32_t framesReady;
4834 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004836 // Check if last stepServer failed, try to step now
4837 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004838 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4839 // Since the fast mixer is higher priority than client callback thread,
4840 // it does not result in priority inversion for client.
4841 // But a non-blocking solution would be preferable to avoid
4842 // fast mixer being unable to tryLock(), and
4843 // to avoid the extra context switches if the client wakes up,
4844 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004845 if (!step()) goto getNextBuffer_exit;
4846 ALOGV("stepServer recovered");
4847 mStepServerFailed = false;
4848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849
Glenn Kasten288ed212012-04-25 17:52:27 -07004850 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004851 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004853 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 uint32_t s = cblk->server;
4855 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4856
4857 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4858 if (framesReq > framesReady) {
4859 framesReq = framesReady;
4860 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004861 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 framesReq = bufferEnd - s;
4863 }
4864
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004865 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004866 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869
4870getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004871 buffer->raw = NULL;
4872 buffer->frameCount = 0;
4873 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4874 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875}
4876
Glenn Kasten288ed212012-04-25 17:52:27 -07004877// Note that framesReady() takes a mutex on the control block using tryLock().
4878// This could result in priority inversion if framesReady() is called by the normal mixer,
4879// as the normal mixer thread runs at lower
4880// priority than the client's callback thread: there is a short window within framesReady()
4881// during which the normal mixer could be preempted, and the client callback would block.
4882// Another problem can occur if framesReady() is called by the fast mixer:
4883// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4884// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4885size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004886 return mCblk->framesReady();
4887}
4888
Glenn Kasten288ed212012-04-25 17:52:27 -07004889// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004891 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004892
John Grossman4ff14ba2012-02-08 16:37:41 -08004893 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4895 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004896 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 return true;
4898 }
4899 return false;
4900}
4901
Glenn Kasten3acbd052012-02-28 10:39:56 -08004902status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004903 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904{
4905 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004906 ALOGV("start(%d), calling pid %d session %d",
4907 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004908
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 sp<ThreadBase> thread = mThread.promote();
4910 if (thread != 0) {
4911 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004912 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 // here the track could be either new, or restarted
4914 // in both cases "unstop" the track
4915 if (mState == PAUSED) {
4916 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004917 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918 } else {
4919 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004920 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 }
4922
4923 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4924 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004925 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004927
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004928#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004929 // to track the speaker usage
4930 if (status == NO_ERROR) {
4931 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4932 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004933#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 }
4935 if (status == NO_ERROR) {
4936 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4937 playbackThread->addTrack_l(this);
4938 } else {
4939 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004940 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941 }
4942 } else {
4943 status = BAD_VALUE;
4944 }
4945 return status;
4946}
4947
4948void AudioFlinger::PlaybackThread::Track::stop()
4949{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004950 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 sp<ThreadBase> thread = mThread.promote();
4952 if (thread != 0) {
4953 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004954 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004955 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004956 // If the track is not active (PAUSED and buffers full), flush buffers
4957 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4958 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4959 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004960 mState = STOPPED;
4961 } else if (!isFastTrack()) {
4962 mState = STOPPED;
4963 } else {
4964 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4965 // and then to STOPPED and reset() when presentation is complete
4966 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004967 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004968 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 }
4970 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4971 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004972 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004974
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004975#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004976 // to track the speaker usage
4977 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004978#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 }
4980 }
4981}
4982
4983void AudioFlinger::PlaybackThread::Track::pause()
4984{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004985 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 sp<ThreadBase> thread = mThread.promote();
4987 if (thread != 0) {
4988 Mutex::Autolock _l(thread->mLock);
4989 if (mState == ACTIVE || mState == RESUMING) {
4990 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004991 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992 if (!isOutputTrack()) {
4993 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004994 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004996
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004997#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004998 // to track the speaker usage
4999 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005000#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 }
5002 }
5003 }
5004}
5005
5006void AudioFlinger::PlaybackThread::Track::flush()
5007{
Steve Block3856b092011-10-20 11:56:00 +01005008 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 sp<ThreadBase> thread = mThread.promote();
5010 if (thread != 0) {
5011 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005012 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
5013 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 return;
5015 }
5016 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005017 // FLUSHED state
5018 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005019 // do not reset the track if it is still in the process of being stopped or paused.
5020 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005021 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005022 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005023 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5024 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5025 reset();
5026 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 }
5028}
5029
5030void AudioFlinger::PlaybackThread::Track::reset()
5031{
5032 // Do not reset twice to avoid discarding data written just after a flush and before
5033 // the audioflinger thread detects the track is stopped.
5034 if (!mResetDone) {
5035 TrackBase::reset();
5036 // Force underrun condition to avoid false underrun callback until first data is
5037 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005038 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5039 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 mFillingUpStatus = FS_FILLING;
5041 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005042 if (mState == FLUSHED) {
5043 mState = IDLE;
5044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 }
5046}
5047
5048void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5049{
5050 mMute = muted;
5051}
5052
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5054{
5055 status_t status = DEAD_OBJECT;
5056 sp<ThreadBase> thread = mThread.promote();
5057 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005058 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005059 sp<AudioFlinger> af = mClient->audioFlinger();
5060
5061 Mutex::Autolock _l(af->mLock);
5062
5063 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005064
Eric Laurent109347d2012-07-02 12:31:03 -07005065 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005066 Mutex::Autolock _dl(playbackThread->mLock);
5067 Mutex::Autolock _sl(srcThread->mLock);
5068 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5069 if (chain == 0) {
5070 return INVALID_OPERATION;
5071 }
5072
5073 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5074 if (effect == 0) {
5075 return INVALID_OPERATION;
5076 }
5077 srcThread->removeEffect_l(effect);
5078 playbackThread->addEffect_l(effect);
5079 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5080 if (effect->state() == EffectModule::ACTIVE ||
5081 effect->state() == EffectModule::STOPPING) {
5082 effect->start();
5083 }
5084
5085 sp<EffectChain> dstChain = effect->chain().promote();
5086 if (dstChain == 0) {
5087 srcThread->addEffect_l(effect);
5088 return INVALID_OPERATION;
5089 }
5090 AudioSystem::unregisterEffect(effect->id());
5091 AudioSystem::registerEffect(&effect->desc(),
5092 srcThread->id(),
5093 dstChain->strategy(),
5094 AUDIO_SESSION_OUTPUT_MIX,
5095 effect->id());
5096 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005097 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 }
5099 return status;
5100}
5101
5102void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5103{
5104 mAuxEffectId = EffectId;
5105 mAuxBuffer = buffer;
5106}
5107
Eric Laurenta011e352012-03-29 15:51:43 -07005108bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5109 size_t audioHalFrames)
5110{
5111 // a track is considered presented when the total number of frames written to audio HAL
5112 // corresponds to the number of frames written when presentationComplete() is called for the
5113 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5114 if (mPresentationCompleteFrames == 0) {
5115 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5116 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5117 mPresentationCompleteFrames, audioHalFrames);
5118 }
5119 if (framesWritten >= mPresentationCompleteFrames) {
5120 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5121 mSessionId, framesWritten);
5122 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005123 return true;
5124 }
5125 return false;
5126}
5127
5128void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5129{
5130 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5131 if (mSyncEvents[i]->type() == type) {
5132 mSyncEvents[i]->trigger();
5133 mSyncEvents.removeAt(i);
5134 i--;
5135 }
5136 }
5137}
5138
Glenn Kasten58912562012-04-03 10:45:00 -07005139// implement VolumeBufferProvider interface
5140
5141uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5142{
5143 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5144 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5145 uint32_t vlr = mCblk->getVolumeLR();
5146 uint32_t vl = vlr & 0xFFFF;
5147 uint32_t vr = vlr >> 16;
5148 // track volumes come from shared memory, so can't be trusted and must be clamped
5149 if (vl > MAX_GAIN_INT) {
5150 vl = MAX_GAIN_INT;
5151 }
5152 if (vr > MAX_GAIN_INT) {
5153 vr = MAX_GAIN_INT;
5154 }
5155 // now apply the cached master volume and stream type volume;
5156 // this is trusted but lacks any synchronization or barrier so may be stale
5157 float v = mCachedVolume;
5158 vl *= v;
5159 vr *= v;
5160 // re-combine into U4.16
5161 vlr = (vr << 16) | (vl & 0xFFFF);
5162 // FIXME look at mute, pause, and stop flags
5163 return vlr;
5164}
Eric Laurenta011e352012-03-29 15:51:43 -07005165
Eric Laurent29864602012-05-08 18:57:51 -07005166status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5167{
5168 if (mState == TERMINATED || mState == PAUSED ||
5169 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5170 (mState == STOPPED)))) {
5171 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5172 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5173 event->cancel();
5174 return INVALID_OPERATION;
5175 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005176 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005177 return NO_ERROR;
5178}
5179
John Grossman4ff14ba2012-02-08 16:37:41 -08005180// timed audio tracks
5181
5182sp<AudioFlinger::PlaybackThread::TimedTrack>
5183AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005184 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 const sp<Client>& client,
5186 audio_stream_type_t streamType,
5187 uint32_t sampleRate,
5188 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005189 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005190 int frameCount,
5191 const sp<IMemory>& sharedBuffer,
5192 int sessionId) {
5193 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005194 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005195
Glenn Kastena0356762012-03-19 10:38:51 -07005196 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005197 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5198 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005199}
5200
5201AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005202 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 const sp<Client>& client,
5204 audio_stream_type_t streamType,
5205 uint32_t sampleRate,
5206 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005207 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005208 int frameCount,
5209 const sp<IMemory>& sharedBuffer,
5210 int sessionId)
5211 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005212 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005213 mQueueHeadInFlight(false),
5214 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005215 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 mTimedSilenceBuffer(NULL),
5217 mTimedSilenceBufferSize(0),
5218 mTimedAudioOutputOnTime(false),
5219 mMediaTimeTransformValid(false)
5220{
5221 LocalClock lc;
5222 mLocalTimeFreq = lc.getLocalFreq();
5223
5224 mLocalTimeToSampleTransform.a_zero = 0;
5225 mLocalTimeToSampleTransform.b_zero = 0;
5226 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5227 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5228 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5229 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005230
5231 mMediaTimeToSampleTransform.a_zero = 0;
5232 mMediaTimeToSampleTransform.b_zero = 0;
5233 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5234 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5235 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5236 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005237}
5238
5239AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5240 mClient->releaseTimedTrack();
5241 delete [] mTimedSilenceBuffer;
5242}
5243
5244status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5245 size_t size, sp<IMemory>* buffer) {
5246
5247 Mutex::Autolock _l(mTimedBufferQueueLock);
5248
5249 trimTimedBufferQueue_l();
5250
5251 // lazily initialize the shared memory heap for timed buffers
5252 if (mTimedMemoryDealer == NULL) {
5253 const int kTimedBufferHeapSize = 512 << 10;
5254
5255 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5256 "AudioFlingerTimed");
5257 if (mTimedMemoryDealer == NULL)
5258 return NO_MEMORY;
5259 }
5260
5261 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5262 if (newBuffer == NULL) {
5263 newBuffer = mTimedMemoryDealer->allocate(size);
5264 if (newBuffer == NULL)
5265 return NO_MEMORY;
5266 }
5267
5268 *buffer = newBuffer;
5269 return NO_ERROR;
5270}
5271
5272// caller must hold mTimedBufferQueueLock
5273void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5274 int64_t mediaTimeNow;
5275 {
5276 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5277 if (!mMediaTimeTransformValid)
5278 return;
5279
5280 int64_t targetTimeNow;
5281 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5282 ? mCCHelper.getCommonTime(&targetTimeNow)
5283 : mCCHelper.getLocalTime(&targetTimeNow);
5284
5285 if (OK != res)
5286 return;
5287
5288 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5289 &mediaTimeNow)) {
5290 return;
5291 }
5292 }
5293
John Grossman1c345192012-03-27 14:00:17 -07005294 size_t trimEnd;
5295 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005296 int64_t bufEnd;
5297
John Grossmanc95cfbb2012-04-12 11:53:11 -07005298 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5299 // We have a next buffer. Just use its PTS as the PTS of the frame
5300 // following the last frame in this buffer. If the stream is sparse
5301 // (ie, there are deliberate gaps left in the stream which should be
5302 // filled with silence by the TimedAudioTrack), then this can result
5303 // in one extra buffer being left un-trimmed when it could have
5304 // been. In general, this is not typical, and we would rather
5305 // optimized away the TS calculation below for the more common case
5306 // where PTSes are contiguous.
5307 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5308 } else {
5309 // We have no next buffer. Compute the PTS of the frame following
5310 // the last frame in this buffer by computing the duration of of
5311 // this frame in media time units and adding it to the PTS of the
5312 // buffer.
5313 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5314 / mCblk->frameSize;
5315
5316 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5317 &bufEnd)) {
5318 ALOGE("Failed to convert frame count of %lld to media time"
5319 " duration" " (scale factor %d/%u) in %s",
5320 frameCount,
5321 mMediaTimeToSampleTransform.a_to_b_numer,
5322 mMediaTimeToSampleTransform.a_to_b_denom,
5323 __PRETTY_FUNCTION__);
5324 break;
5325 }
5326 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005327 }
John Grossman9fbdee12012-03-26 17:51:46 -07005328
5329 if (bufEnd > mediaTimeNow)
5330 break;
5331
5332 // Is the buffer we want to use in the middle of a mix operation right
5333 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5334 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005335 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005336 mTrimQueueHeadOnRelease = true;
5337 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005338 }
5339
John Grossman9fbdee12012-03-26 17:51:46 -07005340 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005341 if (trimStart < trimEnd) {
5342 // Update the bookkeeping for framesReady()
5343 for (size_t i = trimStart; i < trimEnd; ++i) {
5344 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5345 }
5346
5347 // Now actually remove the buffers from the queue.
5348 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005349 }
5350}
5351
John Grossman1c345192012-03-27 14:00:17 -07005352void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5353 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005354 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5355 "%s called (reason \"%s\"), but timed buffer queue has no"
5356 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005357
5358 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5359 mTimedBufferQueue.removeAt(0);
5360}
5361
5362void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5363 const TimedBuffer& buf,
5364 const char* logTag) {
5365 uint32_t bufBytes = buf.buffer()->size();
5366 uint32_t consumedAlready = buf.position();
5367
Eric Laurentb388e532012-04-14 13:32:48 -07005368 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005369 "Bad bookkeeping while updating frames pending. Timed buffer is"
5370 " only %u bytes long, but claims to have consumed %u"
5371 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005372 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005373
5374 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005375 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5376 "Bad bookkeeping while updating frames pending. Should have at"
5377 " least %u queued frames, but we think we have only %u. (update"
5378 " reason: \"%s\")",
5379 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005380
5381 mFramesPendingInQueue -= bufFrames;
5382}
5383
John Grossman4ff14ba2012-02-08 16:37:41 -08005384status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5385 const sp<IMemory>& buffer, int64_t pts) {
5386
5387 {
5388 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5389 if (!mMediaTimeTransformValid)
5390 return INVALID_OPERATION;
5391 }
5392
5393 Mutex::Autolock _l(mTimedBufferQueueLock);
5394
John Grossman1c345192012-03-27 14:00:17 -07005395 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5396 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005397 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5398
5399 return NO_ERROR;
5400}
5401
5402status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5403 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5404
John Grossman1c345192012-03-27 14:00:17 -07005405 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5406 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5407 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005408
5409 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5410 target == TimedAudioTrack::COMMON_TIME)) {
5411 return BAD_VALUE;
5412 }
5413
5414 Mutex::Autolock lock(mMediaTimeTransformLock);
5415 mMediaTimeTransform = xform;
5416 mMediaTimeTransformTarget = target;
5417 mMediaTimeTransformValid = true;
5418
5419 return NO_ERROR;
5420}
5421
5422#define min(a, b) ((a) < (b) ? (a) : (b))
5423
5424// implementation of getNextBuffer for tracks whose buffers have timestamps
5425status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5426 AudioBufferProvider::Buffer* buffer, int64_t pts)
5427{
5428 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005429 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005430 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005431 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005432 return INVALID_OPERATION;
5433 }
5434
John Grossman4ff14ba2012-02-08 16:37:41 -08005435 Mutex::Autolock _l(mTimedBufferQueueLock);
5436
John Grossman9fbdee12012-03-26 17:51:46 -07005437 ALOG_ASSERT(!mQueueHeadInFlight,
5438 "getNextBuffer called without releaseBuffer!");
5439
John Grossman4ff14ba2012-02-08 16:37:41 -08005440 while (true) {
5441
5442 // if we have no timed buffers, then fail
5443 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005444 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005445 buffer->frameCount = 0;
5446 return NOT_ENOUGH_DATA;
5447 }
5448
5449 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5450
5451 // calculate the PTS of the head of the timed buffer queue expressed in
5452 // local time
5453 int64_t headLocalPTS;
5454 {
5455 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5456
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005457 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005458
5459 if (mMediaTimeTransform.a_to_b_denom == 0) {
5460 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005461 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005462 return NO_ERROR;
5463 }
5464
5465 int64_t transformedPTS;
5466 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5467 &transformedPTS)) {
5468 // the transform failed. this shouldn't happen, but if it does
5469 // then just drop this buffer
5470 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005471 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005472 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005473 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005474 return NO_ERROR;
5475 }
5476
5477 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5478 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5479 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005480 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005481 buffer->frameCount = 0;
5482 return INVALID_OPERATION;
5483 }
5484 } else {
5485 headLocalPTS = transformedPTS;
5486 }
5487 }
5488
5489 // adjust the head buffer's PTS to reflect the portion of the head buffer
5490 // that has already been consumed
5491 int64_t effectivePTS = headLocalPTS +
5492 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5493
5494 // Calculate the delta in samples between the head of the input buffer
5495 // queue and the start of the next output buffer that will be written.
5496 // If the transformation fails because of over or underflow, it means
5497 // that the sample's position in the output stream is so far out of
5498 // whack that it should just be dropped.
5499 int64_t sampleDelta;
5500 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5501 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005502 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5503 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005504 continue;
5505 }
5506 if (!mLocalTimeToSampleTransform.doForwardTransform(
5507 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005508 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005509 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005510 continue;
5511 }
5512
John Grossman1c345192012-03-27 14:00:17 -07005513 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5514 " sampleDelta=[%d.%08x]",
5515 head.pts(), head.position(), pts,
5516 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5517 + (sampleDelta >> 32)),
5518 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005519
5520 // if the delta between the ideal placement for the next input sample and
5521 // the current output position is within this threshold, then we will
5522 // concatenate the next input samples to the previous output
5523 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005524 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005525
5526 // if this is the first buffer of audio that we're emitting from this track
5527 // then it should be almost exactly on time.
5528 const int64_t kSampleStartupThreshold = 1LL << 32;
5529
5530 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005531 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005532 // the next input is close enough to being on time, so concatenate it
5533 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005534 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005535
John Grossman1c345192012-03-27 14:00:17 -07005536 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5537 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005538 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005539 }
5540
5541 // Looks like our output is not on time. Reset our on timed status.
5542 // Next time we mix samples from our input queue, then should be within
5543 // the StartupThreshold.
5544 mTimedAudioOutputOnTime = false;
5545 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005546 // the gap between the current output position and the proper start of
5547 // the next input sample is too big, so fill it with silence
5548 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5549
John Grossman9fbdee12012-03-26 17:51:46 -07005550 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005551 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5552 return NO_ERROR;
5553 } else {
5554 // the next input sample is late
5555 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5556 size_t onTimeSamplePosition =
5557 head.position() + lateFrames * mCblk->frameSize;
5558
5559 if (onTimeSamplePosition > head.buffer()->size()) {
5560 // all the remaining samples in the head are too late, so
5561 // drop it and move on
5562 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005563 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005564 continue;
5565 } else {
5566 // skip over the late samples
5567 head.setPosition(onTimeSamplePosition);
5568
5569 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005570 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005571
5572 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5573 return NO_ERROR;
5574 }
5575 }
5576 }
5577}
5578
5579// Yield samples from the timed buffer queue head up to the given output
5580// buffer's capacity.
5581//
5582// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005583void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005584 AudioBufferProvider::Buffer* buffer) {
5585
5586 const TimedBuffer& head = mTimedBufferQueue[0];
5587
5588 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5589 head.position());
5590
5591 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5592 mCblk->frameSize);
5593 size_t framesRequested = buffer->frameCount;
5594 buffer->frameCount = min(framesLeftInHead, framesRequested);
5595
John Grossman9fbdee12012-03-26 17:51:46 -07005596 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005597 mTimedAudioOutputOnTime = true;
5598}
5599
5600// Yield samples of silence up to the given output buffer's capacity
5601//
5602// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005603void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005604 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5605
5606 // lazily allocate a buffer filled with silence
5607 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5608 delete [] mTimedSilenceBuffer;
5609 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5610 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5611 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5612 }
5613
5614 buffer->raw = mTimedSilenceBuffer;
5615 size_t framesRequested = buffer->frameCount;
5616 buffer->frameCount = min(numFrames, framesRequested);
5617
5618 mTimedAudioOutputOnTime = false;
5619}
5620
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005621// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005622void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5623 AudioBufferProvider::Buffer* buffer) {
5624
5625 Mutex::Autolock _l(mTimedBufferQueueLock);
5626
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005627 // If the buffer which was just released is part of the buffer at the head
5628 // of the queue, be sure to update the amt of the buffer which has been
5629 // consumed. If the buffer being returned is not part of the head of the
5630 // queue, its either because the buffer is part of the silence buffer, or
5631 // because the head of the timed queue was trimmed after the mixer called
5632 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005633 if (buffer->raw == mTimedSilenceBuffer) {
5634 ALOG_ASSERT(!mQueueHeadInFlight,
5635 "Queue head in flight during release of silence buffer!");
5636 goto done;
5637 }
5638
5639 ALOG_ASSERT(mQueueHeadInFlight,
5640 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5641 " head in flight.");
5642
5643 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005644 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005645
5646 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005647 void* end = reinterpret_cast<void*>(
5648 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5649 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005650
John Grossman9fbdee12012-03-26 17:51:46 -07005651 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5652 "released buffer not within the head of the timed buffer"
5653 " queue; qHead = [%p, %p], released buffer = %p",
5654 start, end, buffer->raw);
5655
5656 head.setPosition(head.position() +
5657 (buffer->frameCount * mCblk->frameSize));
5658 mQueueHeadInFlight = false;
5659
John Grossman1c345192012-03-27 14:00:17 -07005660 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5661 "Bad bookkeeping during releaseBuffer! Should have at"
5662 " least %u queued frames, but we think we have only %u",
5663 buffer->frameCount, mFramesPendingInQueue);
5664
5665 mFramesPendingInQueue -= buffer->frameCount;
5666
John Grossman9fbdee12012-03-26 17:51:46 -07005667 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5668 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005669 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005670 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005671 }
John Grossman9fbdee12012-03-26 17:51:46 -07005672 } else {
5673 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5674 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005675 }
5676
John Grossman9fbdee12012-03-26 17:51:46 -07005677done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005678 buffer->raw = 0;
5679 buffer->frameCount = 0;
5680}
5681
Glenn Kasten288ed212012-04-25 17:52:27 -07005682size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005683 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005684 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005685}
5686
5687AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5688 : mPTS(0), mPosition(0) {}
5689
5690AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5691 const sp<IMemory>& buffer, int64_t pts)
5692 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5693
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694// ----------------------------------------------------------------------------
5695
5696// RecordTrack constructor must be called with AudioFlinger::mLock held
5697AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005698 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699 const sp<Client>& client,
5700 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005701 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005702 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 int sessionId)
5705 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005706 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 mOverflow(false)
5708{
5709 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005710 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5711 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5712 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5713 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5714 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5715 } else {
5716 mCblk->frameSize = sizeof(int8_t);
5717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 }
5719}
5720
5721AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5722{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005723 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724}
5725
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005726// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005727status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728{
5729 audio_track_cblk_t* cblk = this->cblk();
5730 uint32_t framesAvail;
5731 uint32_t framesReq = buffer->frameCount;
5732
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005733 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005734 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005736 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005737 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 }
5739
5740 framesAvail = cblk->framesAvailable_l();
5741
Glenn Kastenf6b16782011-12-15 09:51:17 -08005742 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 uint32_t s = cblk->server;
5744 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5745
5746 if (framesReq > framesAvail) {
5747 framesReq = framesAvail;
5748 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005749 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 framesReq = bufferEnd - s;
5751 }
5752
5753 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 buffer->frameCount = framesReq;
5755 return NO_ERROR;
5756 }
5757
5758getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005759 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 buffer->frameCount = 0;
5761 return NOT_ENOUGH_DATA;
5762}
5763
Glenn Kasten3acbd052012-02-28 10:39:56 -08005764status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005765 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766{
5767 sp<ThreadBase> thread = mThread.promote();
5768 if (thread != 0) {
5769 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005770 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 } else {
5772 return BAD_VALUE;
5773 }
5774}
5775
5776void AudioFlinger::RecordThread::RecordTrack::stop()
5777{
5778 sp<ThreadBase> thread = mThread.promote();
5779 if (thread != 0) {
5780 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005781 recordThread->mLock.lock();
5782 bool doStop = recordThread->stop_l(this);
5783 if (doStop) {
5784 TrackBase::reset();
5785 // Force overrun condition to avoid false overrun callback until first data is
5786 // read from buffer
5787 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5788 }
5789 recordThread->mLock.unlock();
5790 if (doStop) {
5791 AudioSystem::stopInput(recordThread->id());
5792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 }
5794}
5795
Glenn Kasten510a3d62012-07-16 14:24:34 -07005796/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5797{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005798 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005799}
5800
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5802{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005803 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005804 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005806 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 mSessionId,
5808 mFrameCount,
5809 mState,
5810 mCblk->sampleRate,
5811 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005812 mCblk->user,
5813 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814}
5815
5816
5817// ----------------------------------------------------------------------------
5818
5819AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005820 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 DuplicatingThread *sourceThread,
5822 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005823 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005824 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005826 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5827 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 mActive(false), mSourceThread(sourceThread)
5829{
5830
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 if (mCblk != NULL) {
5832 mCblk->flags |= CBLK_DIRECTION_OUT;
5833 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 mOutBuffer.frameCount = 0;
5835 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005836 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005837 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5838 mCblk, mBuffer, mCblk->buffers,
5839 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005841 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 }
5843}
5844
5845AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5846{
5847 clearBufferQueue();
5848}
5849
Glenn Kasten3acbd052012-02-28 10:39:56 -08005850status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005851 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005853 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854 if (status != NO_ERROR) {
5855 return status;
5856 }
5857
5858 mActive = true;
5859 mRetryCount = 127;
5860 return status;
5861}
5862
5863void AudioFlinger::PlaybackThread::OutputTrack::stop()
5864{
5865 Track::stop();
5866 clearBufferQueue();
5867 mOutBuffer.frameCount = 0;
5868 mActive = false;
5869}
5870
5871bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5872{
5873 Buffer *pInBuffer;
5874 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005875 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 bool outputBufferFull = false;
5877 inBuffer.frameCount = frames;
5878 inBuffer.i16 = data;
5879
5880 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5881
5882 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005883 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 sp<ThreadBase> thread = mThread.promote();
5885 if (thread != 0) {
5886 MixerThread *mixerThread = (MixerThread *)thread.get();
5887 if (mCblk->frameCount > frames){
5888 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5889 uint32_t startFrames = (mCblk->frameCount - frames);
5890 pInBuffer = new Buffer;
5891 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5892 pInBuffer->frameCount = startFrames;
5893 pInBuffer->i16 = pInBuffer->mBuffer;
5894 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5895 mBufferQueue.add(pInBuffer);
5896 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005897 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 }
5899 }
5900 }
5901 }
5902
5903 while (waitTimeLeftMs) {
5904 // First write pending buffers, then new data
5905 if (mBufferQueue.size()) {
5906 pInBuffer = mBufferQueue.itemAt(0);
5907 } else {
5908 pInBuffer = &inBuffer;
5909 }
5910
5911 if (pInBuffer->frameCount == 0) {
5912 break;
5913 }
5914
5915 if (mOutBuffer.frameCount == 0) {
5916 mOutBuffer.frameCount = pInBuffer->frameCount;
5917 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005918 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 outputBufferFull = true;
5921 break;
5922 }
5923 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5924 if (waitTimeLeftMs >= waitTimeMs) {
5925 waitTimeLeftMs -= waitTimeMs;
5926 } else {
5927 waitTimeLeftMs = 0;
5928 }
5929 }
5930
5931 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5932 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5933 mCblk->stepUser(outFrames);
5934 pInBuffer->frameCount -= outFrames;
5935 pInBuffer->i16 += outFrames * channelCount;
5936 mOutBuffer.frameCount -= outFrames;
5937 mOutBuffer.i16 += outFrames * channelCount;
5938
5939 if (pInBuffer->frameCount == 0) {
5940 if (mBufferQueue.size()) {
5941 mBufferQueue.removeAt(0);
5942 delete [] pInBuffer->mBuffer;
5943 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005944 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 } else {
5946 break;
5947 }
5948 }
5949 }
5950
5951 // If we could not write all frames, allocate a buffer and queue it for next time.
5952 if (inBuffer.frameCount) {
5953 sp<ThreadBase> thread = mThread.promote();
5954 if (thread != 0 && !thread->standby()) {
5955 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5956 pInBuffer = new Buffer;
5957 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5958 pInBuffer->frameCount = inBuffer.frameCount;
5959 pInBuffer->i16 = pInBuffer->mBuffer;
5960 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5961 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005962 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005964 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 }
5966 }
5967 }
5968
5969 // Calling write() with a 0 length buffer, means that no more data will be written:
5970 // If no more buffers are pending, fill output track buffer to make sure it is started
5971 // by output mixer.
5972 if (frames == 0 && mBufferQueue.size() == 0) {
5973 if (mCblk->user < mCblk->frameCount) {
5974 frames = mCblk->frameCount - mCblk->user;
5975 pInBuffer = new Buffer;
5976 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5977 pInBuffer->frameCount = frames;
5978 pInBuffer->i16 = pInBuffer->mBuffer;
5979 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5980 mBufferQueue.add(pInBuffer);
5981 } else if (mActive) {
5982 stop();
5983 }
5984 }
5985
5986 return outputBufferFull;
5987}
5988
5989status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5990{
5991 int active;
5992 status_t result;
5993 audio_track_cblk_t* cblk = mCblk;
5994 uint32_t framesReq = buffer->frameCount;
5995
Steve Block3856b092011-10-20 11:56:00 +01005996// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 buffer->frameCount = 0;
5998
5999 uint32_t framesAvail = cblk->framesAvailable();
6000
6001
6002 if (framesAvail == 0) {
6003 Mutex::Autolock _l(cblk->lock);
6004 goto start_loop_here;
6005 while (framesAvail == 0) {
6006 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006007 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006008 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006009 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 }
6011 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6012 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006013 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 }
6015 // read the server count again
6016 start_loop_here:
6017 framesAvail = cblk->framesAvailable_l();
6018 }
6019 }
6020
6021// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006022// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023// }
6024
6025 if (framesReq > framesAvail) {
6026 framesReq = framesAvail;
6027 }
6028
6029 uint32_t u = cblk->user;
6030 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6031
Marco Nelissena1472d92012-03-30 14:36:54 -07006032 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 framesReq = bufferEnd - u;
6034 }
6035
6036 buffer->frameCount = framesReq;
6037 buffer->raw = (void *)cblk->buffer(u);
6038 return NO_ERROR;
6039}
6040
6041
6042void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6043{
6044 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045
6046 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006047 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 delete [] pBuffer->mBuffer;
6049 delete pBuffer;
6050 }
6051 mBufferQueue.clear();
6052}
6053
6054// ----------------------------------------------------------------------------
6055
6056AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6057 : RefBase(),
6058 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006059 // 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 -07006060 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006061 mPid(pid),
6062 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063{
6064 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6065}
6066
6067// Client destructor must be called with AudioFlinger::mLock held
6068AudioFlinger::Client::~Client()
6069{
6070 mAudioFlinger->removeClient_l(mPid);
6071}
6072
Glenn Kasten435dbe62012-01-30 10:15:48 -08006073sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074{
6075 return mMemoryDealer;
6076}
6077
John Grossman4ff14ba2012-02-08 16:37:41 -08006078// Reserve one of the limited slots for a timed audio track associated
6079// with this client
6080bool AudioFlinger::Client::reserveTimedTrack()
6081{
6082 const int kMaxTimedTracksPerClient = 4;
6083
6084 Mutex::Autolock _l(mTimedTrackLock);
6085
6086 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6087 ALOGW("can not create timed track - pid %d has exceeded the limit",
6088 mPid);
6089 return false;
6090 }
6091
6092 mTimedTrackCount++;
6093 return true;
6094}
6095
6096// Release a slot for a timed audio track
6097void AudioFlinger::Client::releaseTimedTrack()
6098{
6099 Mutex::Autolock _l(mTimedTrackLock);
6100 mTimedTrackCount--;
6101}
6102
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103// ----------------------------------------------------------------------------
6104
6105AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6106 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006107 sp<IBinder> binder)
6108 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109{
6110}
6111
6112AudioFlinger::NotificationClient::~NotificationClient()
6113{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114}
6115
6116void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6117{
6118 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006119 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120}
6121
6122// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006123#ifdef QCOM_HARDWARE
6124AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6125 int output, AudioSessionDescriptor *outputDesc,
6126 IDirectTrackClient* client, audio_output_flags_t outflag)
6127 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6128 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6129{
6130 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6131 createEffectThread();
6132
6133 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6134 mAudioFlinger->registerClient(mAudioFlingerClient);
6135
6136 allocateBufPool();
6137 }
6138 mDeathRecipient = new PMDeathRecipient(this);
6139 acquireWakeLock();
6140}
6141
6142AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6143 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6144 requestAndWaitForEffectsThreadExit();
6145 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6146 mAudioFlinger->deleteEffectSession();
6147 deallocateBufPool();
6148 }
6149 releaseWakeLock();
6150 if (mPowerManager != 0) {
6151 sp<IBinder> binder = mPowerManager->asBinder();
6152 binder->unlinkToDeath(mDeathRecipient);
6153 }
6154 AudioSystem::releaseOutput(mOutput);
6155}
6156
6157status_t AudioFlinger::DirectAudioTrack::start() {
6158 if(mIsPaused) {
6159 mIsPaused = false;
6160 mOutputDesc->stream->start(mOutputDesc->stream);
6161 }
6162 mOutputDesc->mActive = true;
6163 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6164 return NO_ERROR;
6165}
6166
6167void AudioFlinger::DirectAudioTrack::stop() {
6168 mOutputDesc->mActive = false;
6169 mOutputDesc->stream->stop(mOutputDesc->stream);
6170 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6171}
6172
6173void AudioFlinger::DirectAudioTrack::pause() {
6174 if(!mIsPaused) {
6175 mIsPaused = true;
6176 mOutputDesc->stream->pause(mOutputDesc->stream);
6177 mOutputDesc->mActive = false;
6178 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6179 }
6180}
6181
6182ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6183 ALOGV("Writing to AudioSessionOut");
6184 int isAvail = 0;
6185 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6186 if (!isAvail) {
6187 return 0;
6188 }
6189
6190 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6191 mEffectLock.lock();
6192 List<BufferInfo>::iterator it = mEffectsPool.begin();
6193 BufferInfo buf = *it;
6194 mEffectsPool.erase(it);
6195 memcpy((char *) buf.localBuf, (char *)buffer, size);
6196 buf.bytesToWrite = size;
6197 mEffectsPool.push_back(buf);
6198 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6199 mEffectLock.unlock();
6200 }
6201 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6202}
6203
6204void AudioFlinger::DirectAudioTrack::flush() {
6205 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6206 mEffectsPool.clear();
6207 mEffectsPool = mBufPool;
6208 }
6209 mOutputDesc->stream->flush(mOutputDesc->stream);
6210}
6211
6212void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6213}
6214
6215void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
6216 mOutputDesc->mVolumeLeft = 1.0;
6217 mOutputDesc->mVolumeRight = 1.0;
6218}
6219
6220int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6221 int64_t time;
6222 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6223 ALOGV("Timestamp %lld",time);
6224 return time;
6225}
6226
6227void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
6228 ALOGV("Notify Audio Track of EOS event");
6229 mClient->notify(DIRECT_TRACK_EOS);
6230}
6231
6232void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6233 void *dsp_buf = NULL;
6234 void *local_buf = NULL;
6235
6236 //1. get the ion buffer information
6237 struct buf_info* buf = NULL;
6238 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6239 ALOGV("get buffer info %p",buf);
6240 if (!buf) {
6241 ALOGV("buffer is NULL");
6242 return;
6243 }
6244 int nSize = buf->bufsize;
6245 int bufferCount = buf->nBufs;
6246
6247 //2. allocate the buffer pool, allocate local buffers
6248 for (int i = 0; i < bufferCount; i++) {
6249 dsp_buf = (void *)buf->buffers[i];
6250 local_buf = malloc(nSize);
6251 memset(local_buf, 0, nSize);
6252 // Store this information for internal mapping / maintanence
6253 BufferInfo buf(local_buf, dsp_buf, nSize);
6254 buf.bytesToWrite = 0;
6255 mBufPool.push_back(buf);
6256 mEffectsPool.push_back(buf);
6257
6258 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6259 }
6260 free(buf);
6261}
6262
6263void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6264
6265 //1. Deallocate the local memory
6266 //2. Remove all the buffers from bufpool
6267 while (!mBufPool.empty()) {
6268 List<BufferInfo>::iterator it = mBufPool.begin();
6269 BufferInfo &memBuffer = *it;
6270 // free the local buffer corresponding to mem buffer
6271 if (memBuffer.localBuf) {
6272 free(memBuffer.localBuf);
6273 memBuffer.localBuf = NULL;
6274 }
6275 ALOGV("Removing from bufpool");
6276 mBufPool.erase(it);
6277 }
6278}
6279
6280status_t AudioFlinger::DirectAudioTrack::onTransact(
6281 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6282{
6283 return BnDirectTrack::onTransact(code, data, reply, flags);
6284}
6285
6286void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6287 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6288 return NULL;
6289}
6290
6291void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6292 while(1) {
6293 mEffectLock.lock();
6294 if (!mEffectConfigChanged && !mKillEffectsThread) {
6295 mEffectCv.wait(mEffectLock);
6296 }
6297
6298 if(mKillEffectsThread) {
6299 mEffectLock.unlock();
6300 break;
6301 }
6302
6303 if (mEffectConfigChanged) {
6304 mEffectConfigChanged = false;
6305 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6306 it != mEffectsPool.end(); it++) {
6307 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6308 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6309 (int16_t *)it->localBuf,
6310 (int16_t *)it->dspBuf,
6311 it->bytesToWrite);
6312 if (mEffectConfigChanged) {
6313 break;
6314 }
6315 }
6316
6317 }
6318 mEffectLock.unlock();
6319 }
6320 ALOGV("Effects thread is dead");
6321 mEffectsThreadAlive = false;
6322}
6323
6324void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6325 if (!mEffectsThreadAlive)
6326 return;
6327 mKillEffectsThread = true;
6328 mEffectCv.signal();
6329 pthread_join(mEffectsThread,NULL);
6330 ALOGV("effects thread killed");
6331}
6332
6333void AudioFlinger::DirectAudioTrack::createEffectThread() {
6334 //Create the effects thread
6335 pthread_attr_t attr;
6336 pthread_attr_init(&attr);
6337 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6338 mEffectsThreadAlive = true;
6339 ALOGV("Creating Effects Thread");
6340 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6341}
6342AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6343{
6344 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6345 pBaseClass = (DirectAudioTrack*)obj;
6346}
6347
6348void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6349 pBaseClass->mAudioFlinger.clear();
6350 ALOGW("AudioFlinger server died!");
6351}
6352
6353void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6354 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6355 ALOGV("ioConfigChanged() event %d", event);
6356 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6357 ALOGV("Received notification for change in effect module");
6358 // Seek to current media time - flush the decoded buffers with the driver
6359 pBaseClass->mEffectConfigChanged = true;
6360 // Signal effects thread to re-apply effects
6361 ALOGV("Signalling Effects Thread");
6362 pBaseClass->mEffectCv.signal();
6363
6364 }
6365 ALOGV("ioConfigChanged Out");
6366}
6367
6368void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6369{
6370 Mutex::Autolock _l(pmLock);
6371
6372 if (mPowerManager == 0) {
6373 // use checkService() to avoid blocking if power service is not up yet
6374 sp<IBinder> binder =
6375 defaultServiceManager()->checkService(String16("power"));
6376 if (binder == 0) {
6377 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6378 } else {
6379 mPowerManager = interface_cast<IPowerManager>(binder);
6380 binder->linkToDeath(mDeathRecipient);
6381 }
6382 }
6383 if (mPowerManager != 0 && mWakeLockToken == 0) {
6384 sp<IBinder> binder = new BBinder();
6385 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6386 binder,
6387 String16(lockName));
6388 if (status == NO_ERROR) {
6389 mWakeLockToken = binder;
6390 }
6391 ALOGV("acquireWakeLock() status %d", status);
6392 }
6393}
6394
6395void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6396{
6397 Mutex::Autolock _l(pmLock);
6398
6399 if (mWakeLockToken != 0) {
6400 ALOGV("releaseWakeLock()");
6401 if (mPowerManager != 0) {
6402 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6403 }
6404 mWakeLockToken.clear();
6405 }
6406}
6407
6408void AudioFlinger::DirectAudioTrack::clearPowerManager()
6409{
6410 Mutex::Autolock _l(pmLock);
6411 releaseWakeLock();
6412 mPowerManager.clear();
6413}
6414
6415void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6416{
6417 parentClass->clearPowerManager();
6418 ALOGW("power manager service died !!!");
6419}
6420#endif
6421
6422// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423
6424AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6425 : BnAudioTrack(),
6426 mTrack(track)
6427{
6428}
6429
6430AudioFlinger::TrackHandle::~TrackHandle() {
6431 // just stop the track on deletion, associated resources
6432 // will be freed from the main thread once all pending buffers have
6433 // been played. Unless it's not in the active track list, in which
6434 // case we free everything now...
6435 mTrack->destroy();
6436}
6437
Glenn Kasten90716c52012-01-26 13:40:12 -08006438sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6439 return mTrack->getCblk();
6440}
6441
Glenn Kasten3acbd052012-02-28 10:39:56 -08006442status_t AudioFlinger::TrackHandle::start() {
6443 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444}
6445
6446void AudioFlinger::TrackHandle::stop() {
6447 mTrack->stop();
6448}
6449
6450void AudioFlinger::TrackHandle::flush() {
6451 mTrack->flush();
6452}
6453
6454void AudioFlinger::TrackHandle::mute(bool e) {
6455 mTrack->mute(e);
6456}
6457
6458void AudioFlinger::TrackHandle::pause() {
6459 mTrack->pause();
6460}
6461
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6463{
6464 return mTrack->attachAuxEffect(EffectId);
6465}
6466
John Grossman4ff14ba2012-02-08 16:37:41 -08006467status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6468 sp<IMemory>* buffer) {
6469 if (!mTrack->isTimedTrack())
6470 return INVALID_OPERATION;
6471
6472 PlaybackThread::TimedTrack* tt =
6473 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6474 return tt->allocateTimedBuffer(size, buffer);
6475}
6476
6477status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6478 int64_t pts) {
6479 if (!mTrack->isTimedTrack())
6480 return INVALID_OPERATION;
6481
6482 PlaybackThread::TimedTrack* tt =
6483 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6484 return tt->queueTimedBuffer(buffer, pts);
6485}
6486
6487status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6488 const LinearTransform& xform, int target) {
6489
6490 if (!mTrack->isTimedTrack())
6491 return INVALID_OPERATION;
6492
6493 PlaybackThread::TimedTrack* tt =
6494 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6495 return tt->setMediaTimeTransform(
6496 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6497}
6498
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499status_t AudioFlinger::TrackHandle::onTransact(
6500 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6501{
6502 return BnAudioTrack::onTransact(code, data, reply, flags);
6503}
6504
6505// ----------------------------------------------------------------------------
6506
6507sp<IAudioRecord> AudioFlinger::openRecord(
6508 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006509 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006511 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006512 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006514 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006515 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 int *sessionId,
6517 status_t *status)
6518{
6519 sp<RecordThread::RecordTrack> recordTrack;
6520 sp<RecordHandle> recordHandle;
6521 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 status_t lStatus;
6523 RecordThread *thread;
6524 size_t inFrameCount;
6525 int lSessionId;
6526
6527 // check calling permissions
6528 if (!recordingAllowed()) {
6529 lStatus = PERMISSION_DENIED;
6530 goto Exit;
6531 }
6532
6533 // add client to list
6534 { // scope for mLock
6535 Mutex::Autolock _l(mLock);
6536 thread = checkRecordThread_l(input);
6537 if (thread == NULL) {
6538 lStatus = BAD_VALUE;
6539 goto Exit;
6540 }
6541
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006542 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543
6544 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006545 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 lSessionId = *sessionId;
6547 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006548 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 if (sessionId != NULL) {
6550 *sessionId = lSessionId;
6551 }
6552 }
6553 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006554 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6555 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006557 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6559 // destructor is called by the TrackBase destructor with mLock held
6560 client.clear();
6561 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 goto Exit;
6563 }
6564
6565 // return to handle to client
6566 recordHandle = new RecordHandle(recordTrack);
6567 lStatus = NO_ERROR;
6568
6569Exit:
6570 if (status) {
6571 *status = lStatus;
6572 }
6573 return recordHandle;
6574}
6575
6576// ----------------------------------------------------------------------------
6577
6578AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6579 : BnAudioRecord(),
6580 mRecordTrack(recordTrack)
6581{
6582}
6583
6584AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006585 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006586 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587}
6588
Glenn Kasten90716c52012-01-26 13:40:12 -08006589sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6590 return mRecordTrack->getCblk();
6591}
6592
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006593status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006594 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006595 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596}
6597
6598void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006599 stop_nonvirtual();
6600}
6601
6602void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006603 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 mRecordTrack->stop();
6605}
6606
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607status_t AudioFlinger::RecordHandle::onTransact(
6608 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6609{
6610 return BnAudioRecord::onTransact(code, data, reply, flags);
6611}
6612
6613// ----------------------------------------------------------------------------
6614
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006615AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6616 AudioStreamIn *input,
6617 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006618 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006619 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006620 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006621 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006622 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006623 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006624 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006625 mReqSampleRate(sampleRate)
6626 // mBytesRead is only meaningful while active, and so is cleared in start()
6627 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628{
Glenn Kasten480b4682012-02-28 12:30:08 -08006629 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006630
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 readInputParameters();
6632}
6633
6634
6635AudioFlinger::RecordThread::~RecordThread()
6636{
6637 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006638 delete mResampler;
6639 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640}
6641
6642void AudioFlinger::RecordThread::onFirstRef()
6643{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006644 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645}
6646
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006647status_t AudioFlinger::RecordThread::readyToRun()
6648{
6649 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006650 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006651 return status;
6652}
6653
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654bool AudioFlinger::RecordThread::threadLoop()
6655{
6656 AudioBufferProvider::Buffer buffer;
6657 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006658 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659
Eric Laurent44d98482010-09-30 16:12:31 -07006660 nsecs_t lastWarning = 0;
6661
Glenn Kastene4e2a372012-07-23 12:55:09 -07006662 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006663 acquireWakeLock();
6664
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006665 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006666 bool readOnce = false;
6667
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 // start recording
6669 while (!exitPending()) {
6670
6671 processConfigEvents();
6672
6673 { // scope for mLock
6674 Mutex::Autolock _l(mLock);
6675 checkForNewParameters_l();
6676 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006677 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678
6679 if (exitPending()) break;
6680
Eric Laurentfeb0db62011-07-22 09:04:31 -07006681 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006682 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 // go to sleep
6684 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006685 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006686 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687 continue;
6688 }
6689 if (mActiveTrack != 0) {
6690 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006691 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692 mActiveTrack.clear();
6693 mStartStopCond.broadcast();
6694 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6695 if (mReqChannelCount != mActiveTrack->channelCount()) {
6696 mActiveTrack.clear();
6697 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006698 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 // record start succeeds only if first read from audio input
6700 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006701 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 mActiveTrack->mState = TrackBase::ACTIVE;
6703 } else {
6704 mActiveTrack.clear();
6705 }
6706 mStartStopCond.broadcast();
6707 }
6708 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006709 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6710 removeTrack_l(mActiveTrack);
6711 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712 }
6713 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006714 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715 }
6716
6717 if (mActiveTrack != 0) {
6718 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6719 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006720 unlockEffectChains(effectChains);
6721 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722 continue;
6723 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006724 for (size_t i = 0; i < effectChains.size(); i ++) {
6725 effectChains[i]->process_l();
6726 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006727
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006729 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006730 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006732 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733 // no resampling
6734 while (framesOut) {
6735 size_t framesIn = mFrameCount - mRsmpInIndex;
6736 if (framesIn) {
6737 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6738 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6739 if (framesIn > framesOut)
6740 framesIn = framesOut;
6741 mRsmpInIndex += framesIn;
6742 framesOut -= framesIn;
6743 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006744 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 memcpy(dst, src, framesIn * mFrameSize);
6746 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006748 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6749 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006751 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6752 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753 }
6754 }
6755 }
6756 if (framesOut && mFrameCount == mRsmpInIndex) {
6757 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006758 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006759 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 framesOut = 0;
6761 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006762 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 mRsmpInIndex = 0;
6764 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006765 if (mBytesRead <= 0) {
6766 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6767 {
6768 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769 // Force input into standby so that it tries to
6770 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006771 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006772 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 }
6774 mRsmpInIndex = mFrameCount;
6775 framesOut = 0;
6776 buffer.frameCount = 0;
6777 }
6778 }
6779 }
6780 } else {
6781 // resampling
6782
6783 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6784 // alter output frame count as if we were expecting stereo samples
6785 if (mChannelCount == 1 && mReqChannelCount == 1) {
6786 framesOut >>= 1;
6787 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006788 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6790 // are 32 bit aligned which should be always true.
6791 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006792 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006793 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006794 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6795 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006797 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 }
6799
6800 }
Eric Laurenta011e352012-03-29 15:51:43 -07006801 if (mFramestoDrop == 0) {
6802 mActiveTrack->releaseBuffer(&buffer);
6803 } else {
6804 if (mFramestoDrop > 0) {
6805 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006806 if (mFramestoDrop <= 0) {
6807 clearSyncStartEvent();
6808 }
6809 } else {
6810 mFramestoDrop += buffer.frameCount;
6811 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6812 mSyncStartEvent->isCancelled()) {
6813 ALOGW("Synced record %s, session %d, trigger session %d",
6814 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6815 mActiveTrack->sessionId(),
6816 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6817 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006818 }
6819 }
6820 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006821 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822 }
6823 // client isn't retrieving buffers fast enough
6824 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006825 if (!mActiveTrack->setOverflow()) {
6826 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006827 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006828 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006829 lastWarning = now;
6830 }
6831 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 // Release the processor for a while before asking for a new buffer.
6833 // This will give the application more chance to read from the buffer and
6834 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006835 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 }
6837 }
Eric Laurentec437d82011-07-26 20:54:46 -07006838 // enable changes in effect chain
6839 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006840 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 }
6842
Glenn Kastene4e2a372012-07-23 12:55:09 -07006843 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844
Glenn Kasten33e6e352012-07-16 15:56:57 -07006845 {
6846 Mutex::Autolock _l(mLock);
6847 mActiveTrack.clear();
6848 mStartStopCond.broadcast();
6849 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850
Eric Laurentfeb0db62011-07-22 09:04:31 -07006851 releaseWakeLock();
6852
Steve Block3856b092011-10-20 11:56:00 +01006853 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 return false;
6855}
6856
Glenn Kastene4e2a372012-07-23 12:55:09 -07006857void AudioFlinger::RecordThread::standby()
6858{
6859 if (!mStandby) {
6860 inputStandBy();
6861 mStandby = true;
6862 }
6863}
6864
6865void AudioFlinger::RecordThread::inputStandBy()
6866{
6867 mInput->stream->common.standby(&mInput->stream->common);
6868}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006869
6870sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6871 const sp<AudioFlinger::Client>& client,
6872 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006873 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006874 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006875 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006877 IAudioFlinger::track_flags_t flags,
6878 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006879 status_t *status)
6880{
6881 sp<RecordTrack> track;
6882 status_t lStatus;
6883
6884 lStatus = initCheck();
6885 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006886 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006887 goto Exit;
6888 }
6889
Glenn Kasten1879fff2012-07-11 15:36:59 -07006890 // FIXME use flags and tid similar to createTrack_l()
6891
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006892 { // scope for mLock
6893 Mutex::Autolock _l(mLock);
6894
6895 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006896 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006897
Glenn Kasten7378ca52012-01-20 13:44:40 -08006898 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006899 lStatus = NO_MEMORY;
6900 goto Exit;
6901 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006902 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006903
Eric Laurent59bd0da2011-08-01 09:52:20 -07006904 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006905 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006906 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006907 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6908 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006909 }
6910 lStatus = NO_ERROR;
6911
6912Exit:
6913 if (status) {
6914 *status = lStatus;
6915 }
6916 return track;
6917}
6918
Eric Laurenta011e352012-03-29 15:51:43 -07006919status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006920 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006921 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922{
Glenn Kasten58912562012-04-03 10:45:00 -07006923 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006924 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006926
6927 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006928 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006929 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6930 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6931 triggerSession,
6932 recordTrack->sessionId(),
6933 syncStartEventCallback,
6934 this);
Eric Laurent29864602012-05-08 18:57:51 -07006935 // Sync event can be cancelled by the trigger session if the track is not in a
6936 // compatible state in which case we start record immediately
6937 if (mSyncStartEvent->isCancelled()) {
6938 clearSyncStartEvent();
6939 } else {
6940 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6941 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6942 }
Eric Laurenta011e352012-03-29 15:51:43 -07006943 }
6944
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006946 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947 if (mActiveTrack != 0) {
6948 if (recordTrack != mActiveTrack.get()) {
6949 status = -EBUSY;
6950 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6951 mActiveTrack->mState = TrackBase::ACTIVE;
6952 }
6953 return status;
6954 }
6955
6956 recordTrack->mState = TrackBase::IDLE;
6957 mActiveTrack = recordTrack;
6958 mLock.unlock();
6959 status_t status = AudioSystem::startInput(mId);
6960 mLock.lock();
6961 if (status != NO_ERROR) {
6962 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006963 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 return status;
6965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 mRsmpInIndex = mFrameCount;
6967 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006968 if (mResampler != NULL) {
6969 mResampler->reset();
6970 }
6971 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006973 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006974 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006976 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 mActiveTrack.clear();
6978 status = INVALID_OPERATION;
6979 goto startError;
6980 }
6981 mStartStopCond.wait(mLock);
6982 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006983 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 status = BAD_VALUE;
6985 goto startError;
6986 }
Steve Block3856b092011-10-20 11:56:00 +01006987 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 return status;
6989 }
6990startError:
6991 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006992 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 return status;
6994}
6995
Eric Laurenta011e352012-03-29 15:51:43 -07006996void AudioFlinger::RecordThread::clearSyncStartEvent()
6997{
6998 if (mSyncStartEvent != 0) {
6999 mSyncStartEvent->cancel();
7000 }
7001 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007002 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007003}
7004
7005void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7006{
7007 sp<SyncEvent> strongEvent = event.promote();
7008
7009 if (strongEvent != 0) {
7010 RecordThread *me = (RecordThread *)strongEvent->cookie();
7011 me->handleSyncStartEvent(strongEvent);
7012 }
7013}
7014
7015void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7016{
Eric Laurent29864602012-05-08 18:57:51 -07007017 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007018 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7019 // from audio HAL
7020 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007021 }
7022}
7023
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007024bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007025 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007026 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7027 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007029 recordTrack->mState = TrackBase::PAUSING;
7030 // do not wait for mStartStopCond if exiting
7031 if (exitPending()) {
7032 return true;
7033 }
7034 mStartStopCond.wait(mLock);
7035 // if we have been restarted, recordTrack == mActiveTrack.get() here
7036 if (exitPending() || recordTrack != mActiveTrack.get()) {
7037 ALOGV("Record stopped OK");
7038 return true;
7039 }
7040 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041}
7042
Glenn Kasten106e8a42012-08-02 13:37:12 -07007043bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007044{
7045 return false;
7046}
7047
7048status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7049{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007050#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
Eric Laurenta011e352012-03-29 15:51:43 -07007051 if (!isValidSyncEvent(event)) {
7052 return BAD_VALUE;
7053 }
7054
Glenn Kasten510a3d62012-07-16 14:24:34 -07007055 int eventSession = event->triggerSession();
7056 status_t ret = NAME_NOT_FOUND;
7057
Eric Laurenta011e352012-03-29 15:51:43 -07007058 Mutex::Autolock _l(mLock);
7059
Glenn Kasten510a3d62012-07-16 14:24:34 -07007060 for (size_t i = 0; i < mTracks.size(); i++) {
7061 sp<RecordTrack> track = mTracks[i];
7062 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007063 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007064 ret = NO_ERROR;
7065 }
Eric Laurenta011e352012-03-29 15:51:43 -07007066 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007067 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007068#else
7069 return BAD_VALUE;
7070#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007071}
7072
7073void AudioFlinger::RecordThread::RecordTrack::destroy()
7074{
7075 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7076 sp<RecordTrack> keep(this);
7077 {
7078 sp<ThreadBase> thread = mThread.promote();
7079 if (thread != 0) {
7080 if (mState == ACTIVE || mState == RESUMING) {
7081 AudioSystem::stopInput(thread->id());
7082 }
7083 AudioSystem::releaseInput(thread->id());
7084 Mutex::Autolock _l(thread->mLock);
7085 RecordThread *recordThread = (RecordThread *) thread.get();
7086 recordThread->destroyTrack_l(this);
7087 }
7088 }
7089}
7090
7091// destroyTrack_l() must be called with ThreadBase::mLock held
7092void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7093{
7094 track->mState = TrackBase::TERMINATED;
7095 // active tracks are removed by threadLoop()
7096 if (mActiveTrack != track) {
7097 removeTrack_l(track);
7098 }
7099}
7100
7101void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7102{
7103 mTracks.remove(track);
7104 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007105}
7106
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007107void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007109 dumpInternals(fd, args);
7110 dumpTracks(fd, args);
7111 dumpEffectChains(fd, args);
7112}
7113
7114void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7115{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007116 const size_t SIZE = 256;
7117 char buffer[SIZE];
7118 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119
7120 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7121 result.append(buffer);
7122
7123 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7125 result.append(buffer);
7126 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7127 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007128 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129 result.append(buffer);
7130 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7131 result.append(buffer);
7132 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7133 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007135 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007137
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138 write(fd, result.string(), result.size());
7139
7140 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007141}
7142
7143void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7144{
7145 const size_t SIZE = 256;
7146 char buffer[SIZE];
7147 String8 result;
7148
7149 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7150 result.append(buffer);
7151 RecordTrack::appendDumpHeader(result);
7152 for (size_t i = 0; i < mTracks.size(); ++i) {
7153 sp<RecordTrack> track = mTracks[i];
7154 if (track != 0) {
7155 track->dump(buffer, SIZE);
7156 result.append(buffer);
7157 }
7158 }
7159
7160 if (mActiveTrack != 0) {
7161 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7162 result.append(buffer);
7163 RecordTrack::appendDumpHeader(result);
7164 mActiveTrack->dump(buffer, SIZE);
7165 result.append(buffer);
7166
7167 }
7168 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169}
7170
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007171// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007172status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173{
7174 size_t framesReq = buffer->frameCount;
7175 size_t framesReady = mFrameCount - mRsmpInIndex;
7176 int channelCount;
7177
7178 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007179 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007180 if (mBytesRead <= 0) {
7181 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7182 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183 // Force input into standby so that it tries to
7184 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007185 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007186 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007188 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 buffer->frameCount = 0;
7190 return NOT_ENOUGH_DATA;
7191 }
7192 mRsmpInIndex = 0;
7193 framesReady = mFrameCount;
7194 }
7195
7196 if (framesReq > framesReady) {
7197 framesReq = framesReady;
7198 }
7199
7200 if (mChannelCount == 1 && mReqChannelCount == 2) {
7201 channelCount = 1;
7202 } else {
7203 channelCount = 2;
7204 }
7205 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7206 buffer->frameCount = framesReq;
7207 return NO_ERROR;
7208}
7209
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007210// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7212{
7213 mRsmpInIndex += buffer->frameCount;
7214 buffer->frameCount = 0;
7215}
7216
7217bool AudioFlinger::RecordThread::checkForNewParameters_l()
7218{
7219 bool reconfig = false;
7220
7221 while (!mNewParameters.isEmpty()) {
7222 status_t status = NO_ERROR;
7223 String8 keyValuePair = mNewParameters[0];
7224 AudioParameter param = AudioParameter(keyValuePair);
7225 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007226 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227 int reqSamplingRate = mReqSampleRate;
7228 int reqChannelCount = mReqChannelCount;
7229
7230 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7231 reqSamplingRate = value;
7232 reconfig = true;
7233 }
7234 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007235 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236 reconfig = true;
7237 }
7238 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007239 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240 reconfig = true;
7241 }
7242 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7243 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007244 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245 // if frame count is changed after track creation
7246 if (mActiveTrack != 0) {
7247 status = INVALID_OPERATION;
7248 } else {
7249 reconfig = true;
7250 }
7251 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007252 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7253 // forward device change to effects that have requested to be
7254 // aware of attached audio device.
7255 for (size_t i = 0; i < mEffectChains.size(); i++) {
7256 mEffectChains[i]->setDevice_l(value);
7257 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007258
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007259 // store input device and output device but do not forward output device to audio HAL.
7260 // Note that status is ignored by the caller for output device
7261 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007262 if (audio_is_output_devices(value)) {
7263 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007264 status = BAD_VALUE;
7265 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007266 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007267 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007268 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007269 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7270 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007271 for (size_t i = 0; i < mTracks.size(); i++) {
7272 sp<RecordTrack> track = mTracks[i];
7273 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7274 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7275 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007276 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007277 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007278 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007279 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7280 mAudioSource != (audio_source_t)value) {
7281 // forward device change to effects that have requested to be
7282 // aware of attached audio device.
7283 for (size_t i = 0; i < mEffectChains.size(); i++) {
7284 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7285 }
7286 mAudioSource = (audio_source_t)value;
7287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007289 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007291 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007292 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7293 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 }
7295 if (reconfig) {
7296 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007297 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007298 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007299 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007300 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007301 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 status = NO_ERROR;
7303 }
7304 if (status == NO_ERROR) {
7305 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007306 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 }
7308 }
7309 }
7310
7311 mNewParameters.removeAt(0);
7312
7313 mParamStatus = status;
7314 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007315 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7316 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007317 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 }
7319 return reconfig;
7320}
7321
7322String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7323{
Dima Zavinfce7a472011-04-19 22:30:36 -07007324 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007325 String8 out_s8 = String8();
7326
7327 Mutex::Autolock _l(mLock);
7328 if (initCheck() != NO_ERROR) {
7329 return out_s8;
7330 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007331
Dima Zavin799a70e2011-04-18 16:57:27 -07007332 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007333 out_s8 = String8(s);
7334 free(s);
7335 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336}
7337
7338void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7339 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007340 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341
7342 switch (event) {
7343 case AudioSystem::INPUT_OPENED:
7344 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007345 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 desc.samplingRate = mSampleRate;
7347 desc.format = mFormat;
7348 desc.frameCount = mFrameCount;
7349 desc.latency = 0;
7350 param2 = &desc;
7351 break;
7352
7353 case AudioSystem::INPUT_CLOSED:
7354 default:
7355 break;
7356 }
7357 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7358}
7359
7360void AudioFlinger::RecordThread::readInputParameters()
7361{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007362 delete mRsmpInBuffer;
7363 // mRsmpInBuffer is always assigned a new[] below
7364 delete mRsmpOutBuffer;
7365 mRsmpOutBuffer = NULL;
7366 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007367 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368
Dima Zavin799a70e2011-04-18 16:57:27 -07007369 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007370 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007371 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007372 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007373 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007374 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007376 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7378
Glenn Kasten53d76db2012-03-08 12:32:47 -08007379 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 {
7381 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007382 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7383 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 if (mChannelCount == 1 && mReqChannelCount == 2) {
7385 channelCount = 1;
7386 } else {
7387 channelCount = 2;
7388 }
7389 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7390 mResampler->setSampleRate(mSampleRate);
7391 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7392 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7393
7394 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7395 if (mChannelCount == 1 && mReqChannelCount == 1) {
7396 mFrameCount >>= 1;
7397 }
7398
7399 }
7400 mRsmpInIndex = mFrameCount;
7401}
7402
7403unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7404{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007405 Mutex::Autolock _l(mLock);
7406 if (initCheck() != NO_ERROR) {
7407 return 0;
7408 }
7409
Dima Zavin799a70e2011-04-18 16:57:27 -07007410 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411}
7412
Glenn Kasten106e8a42012-08-02 13:37:12 -07007413uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007414{
7415 Mutex::Autolock _l(mLock);
7416 uint32_t result = 0;
7417 if (getEffectChain_l(sessionId) != 0) {
7418 result = EFFECT_SESSION;
7419 }
7420
Glenn Kasten510a3d62012-07-16 14:24:34 -07007421 for (size_t i = 0; i < mTracks.size(); ++i) {
7422 if (sessionId == mTracks[i]->sessionId()) {
7423 result |= TRACK_SESSION;
7424 break;
7425 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426 }
7427
7428 return result;
7429}
7430
Glenn Kasten106e8a42012-08-02 13:37:12 -07007431KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007432{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007433 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007434 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007435 for (size_t j = 0; j < mTracks.size(); ++j) {
7436 sp<RecordThread::RecordTrack> track = mTracks[j];
7437 int sessionId = track->sessionId();
7438 if (ids.indexOfKey(sessionId) < 0) {
7439 ids.add(sessionId, true);
7440 }
7441 }
7442 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007443}
7444
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007445AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7446{
7447 Mutex::Autolock _l(mLock);
7448 AudioStreamIn *input = mInput;
7449 mInput = NULL;
7450 return input;
7451}
7452
7453// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007454audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007455{
7456 if (mInput == NULL) {
7457 return NULL;
7458 }
7459 return &mInput->stream->common;
7460}
7461
7462
Mathias Agopian65ab4712010-07-14 17:59:35 -07007463// ----------------------------------------------------------------------------
7464
Eric Laurenta4c5a552012-03-29 10:12:40 -07007465audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7466{
7467 if (!settingsAllowed()) {
7468 return 0;
7469 }
7470 Mutex::Autolock _l(mLock);
7471 return loadHwModule_l(name);
7472}
7473
7474// loadHwModule_l() must be called with AudioFlinger::mLock held
7475audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7476{
7477 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7478 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7479 ALOGW("loadHwModule() module %s already loaded", name);
7480 return mAudioHwDevs.keyAt(i);
7481 }
7482 }
7483
Eric Laurenta4c5a552012-03-29 10:12:40 -07007484 audio_hw_device_t *dev;
7485
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007486 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007487 if (rc) {
7488 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7489 return 0;
7490 }
7491
7492 mHardwareStatus = AUDIO_HW_INIT;
7493 rc = dev->init_check(dev);
7494 mHardwareStatus = AUDIO_HW_IDLE;
7495 if (rc) {
7496 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7497 return 0;
7498 }
7499
John Grossmanee578c02012-07-23 17:05:46 -07007500 // Check and cache this HAL's level of support for master mute and master
7501 // volume. If this is the first HAL opened, and it supports the get
7502 // methods, use the initial values provided by the HAL as the current
7503 // master mute and volume settings.
7504
7505 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7506 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007507 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007508
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007509#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007510 if (0 == mAudioHwDevs.size()) {
7511 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7512 if (NULL != dev->get_master_volume) {
7513 float mv;
7514 if (OK == dev->get_master_volume(dev, &mv)) {
7515 mMasterVolume = mv;
7516 }
7517 }
7518
7519 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7520 if (NULL != dev->get_master_mute) {
7521 bool mm;
7522 if (OK == dev->get_master_mute(dev, &mm)) {
7523 mMasterMute = mm;
7524 }
7525 }
7526 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007527#endif
John Grossmanee578c02012-07-23 17:05:46 -07007528
Eric Laurenta4c5a552012-03-29 10:12:40 -07007529 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007530 if ((NULL != dev->set_master_volume) &&
7531 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7532 flags = static_cast<AudioHwDevice::Flags>(flags |
7533 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7534 }
7535
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007536#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007537 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7538 if ((NULL != dev->set_master_mute) &&
7539 (OK == dev->set_master_mute(dev, mMasterMute))) {
7540 flags = static_cast<AudioHwDevice::Flags>(flags |
7541 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7542 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007543#endif
John Grossmanee578c02012-07-23 17:05:46 -07007544
Eric Laurenta4c5a552012-03-29 10:12:40 -07007545 mHardwareStatus = AUDIO_HW_IDLE;
7546 }
7547
7548 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007549 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007550
7551 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007552 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007553
7554 return handle;
7555
7556}
7557
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007558// ----------------------------------------------------------------------------
7559
7560int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7561{
7562 Mutex::Autolock _l(mLock);
7563 PlaybackThread *thread = primaryPlaybackThread_l();
7564 return thread != NULL ? thread->sampleRate() : 0;
7565}
7566
7567int32_t AudioFlinger::getPrimaryOutputFrameCount()
7568{
7569 Mutex::Autolock _l(mLock);
7570 PlaybackThread *thread = primaryPlaybackThread_l();
7571 return thread != NULL ? thread->frameCountHAL() : 0;
7572}
7573
7574// ----------------------------------------------------------------------------
7575
Eric Laurenta4c5a552012-03-29 10:12:40 -07007576audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7577 audio_devices_t *pDevices,
7578 uint32_t *pSamplingRate,
7579 audio_format_t *pFormat,
7580 audio_channel_mask_t *pChannelMask,
7581 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007582 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583{
7584 status_t status;
7585 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007586 struct audio_config config = {
7587 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7588 channel_mask: pChannelMask ? *pChannelMask : 0,
7589 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7590 };
7591 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007592 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593
Eric Laurenta4c5a552012-03-29 10:12:40 -07007594 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7595 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007596 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007597 config.sample_rate,
7598 config.format,
7599 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007600 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601
7602 if (pDevices == NULL || *pDevices == 0) {
7603 return 0;
7604 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007605
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 Mutex::Autolock _l(mLock);
7607
Eric Laurenta4c5a552012-03-29 10:12:40 -07007608 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007609 if (outHwDev == NULL)
7610 return 0;
7611
John Grossmanee578c02012-07-23 17:05:46 -07007612 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007613 audio_io_handle_t id = nextUniqueId();
7614
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007615 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007616
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007617#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007618 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007619 id,
7620 *pDevices,
7621 (audio_output_flags_t)flags,
7622 &config,
7623 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007624#else
7625 status = hwDevHal->open_output_stream(hwDevHal,
7626 *pDevices,
7627 (int *)&config.format,
7628 &config.channel_mask,
7629 &config.sample_rate,
7630 &outStream);
7631 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7632 flags = (audio_output_flags_t)newflags;
7633#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007634
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007635 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007636 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007637 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007638 config.sample_rate,
7639 config.format,
7640 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 status);
7642
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007643 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007644 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007645#ifdef QCOM_HARDWARE
7646 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7647 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7648 desc->mActive = true;
7649 //TODO: no stream type
7650 //desc->mStreamType = streamType;
7651 desc->mVolumeLeft = 1.0;
7652 desc->mVolumeRight = 1.0;
7653 desc->device = *pDevices;
7654 mDirectAudioTracks.add(id, desc);
7655 } else
7656#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007657 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007658 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7659 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007661 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662 } else {
7663 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007664 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665 }
vivek mehta2192bc92012-12-04 11:46:08 -08007666#ifdef QCOM_HARDWARE
7667 if (thread != NULL)
7668#endif
7669 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007670
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007671 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7672 if (pFormat != NULL) *pFormat = config.format;
7673 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007674#ifdef QCOM_HARDWARE
7675 if (thread != NULL) {
7676#endif
7677 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7678 // notify client processes of the new output creation
7679 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7680#ifdef QCOM_HARDWARE
7681 }
7682 else {
7683 *pLatencyMs = 0;
7684 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7685 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7686 *pLatencyMs = desc->stream->get_latency(desc->stream);
7687 }
7688 }
7689#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007690 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007691 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007692 ALOGI("Using module %d has the primary audio interface", module);
7693 mPrimaryHardwareDev = outHwDev;
7694
7695 AutoMutex lock(mHardwareLock);
7696 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007697 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007698 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 return id;
7701 }
7702
7703 return 0;
7704}
7705
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007706audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7707 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708{
7709 Mutex::Autolock _l(mLock);
7710 MixerThread *thread1 = checkMixerThread_l(output1);
7711 MixerThread *thread2 = checkMixerThread_l(output2);
7712
7713 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007714 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007715 return 0;
7716 }
7717
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007718 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7720 thread->addOutputTrack(thread2);
7721 mPlaybackThreads.add(id, thread);
7722 // notify client processes of the new output creation
7723 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7724 return id;
7725}
7726
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007727status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728{
Glenn Kastend96c5722012-04-25 13:44:49 -07007729 return closeOutput_nonvirtual(output);
7730}
7731
7732status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7733{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734 // keep strong reference on the playback thread so that
7735 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007736#ifdef QCOM_HARDWARE
7737 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7738 if (desc) {
7739 ALOGV("Closing DirectTrack output %d", output);
7740 desc->mActive = false;
7741 desc->stream->common.standby(&desc->stream->common);
7742 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7743 desc->trackRefPtr = NULL;
7744 mDirectAudioTracks.removeItem(output);
7745 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7746 delete desc;
7747 return NO_ERROR;
7748 }
7749#endif
7750
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007751 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 {
7753 Mutex::Autolock _l(mLock);
7754 thread = checkPlaybackThread_l(output);
7755 if (thread == NULL) {
7756 return BAD_VALUE;
7757 }
7758
Steve Block3856b092011-10-20 11:56:00 +01007759 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007761 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007763 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7765 dupThread->removeOutputTrack((MixerThread *)thread.get());
7766 }
7767 }
7768 }
Glenn Kastena1117922012-01-26 10:53:32 -08007769 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 mPlaybackThreads.removeItem(output);
7771 }
7772 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007773 // The thread entity (active unit of execution) is no longer running here,
7774 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007776 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007777 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007778 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007779 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007780 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007781 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 }
7783 return NO_ERROR;
7784}
7785
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007786status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787{
7788 Mutex::Autolock _l(mLock);
7789 PlaybackThread *thread = checkPlaybackThread_l(output);
7790
7791 if (thread == NULL) {
7792 return BAD_VALUE;
7793 }
7794
Steve Block3856b092011-10-20 11:56:00 +01007795 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 thread->suspend();
7797
7798 return NO_ERROR;
7799}
7800
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007801status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802{
7803 Mutex::Autolock _l(mLock);
7804 PlaybackThread *thread = checkPlaybackThread_l(output);
7805
7806 if (thread == NULL) {
7807 return BAD_VALUE;
7808 }
7809
Steve Block3856b092011-10-20 11:56:00 +01007810 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811
7812 thread->restore();
7813
7814 return NO_ERROR;
7815}
7816
Eric Laurenta4c5a552012-03-29 10:12:40 -07007817audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7818 audio_devices_t *pDevices,
7819 uint32_t *pSamplingRate,
7820 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007821 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822{
7823 status_t status;
7824 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007825 struct audio_config config = {
7826 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7827 channel_mask: pChannelMask ? *pChannelMask : 0,
7828 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7829 };
7830 uint32_t reqSamplingRate = config.sample_rate;
7831 audio_format_t reqFormat = config.format;
7832 audio_channel_mask_t reqChannels = config.channel_mask;
7833 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007834 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835
7836 if (pDevices == NULL || *pDevices == 0) {
7837 return 0;
7838 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007839
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840 Mutex::Autolock _l(mLock);
7841
Eric Laurenta4c5a552012-03-29 10:12:40 -07007842 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007843 if (inHwDev == NULL)
7844 return 0;
7845
John Grossmanee578c02012-07-23 17:05:46 -07007846 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007847 audio_io_handle_t id = nextUniqueId();
7848
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007849#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007850 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007851 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007852#else
7853 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7854 (int *)&config.format,
7855 &config.channel_mask,
7856 &config.sample_rate, (audio_in_acoustics_t)0,
7857 &inStream);
7858#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007859 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007860 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007861 config.sample_rate,
7862 config.format,
7863 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 status);
7865
7866 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7867 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7868 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007869 if (status == BAD_VALUE &&
7870 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7871 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007872 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007873 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007874 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007875#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007876 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007877#else
7878 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7879 (int *)&config.format,
7880 &config.channel_mask,
7881 &config.sample_rate, (audio_in_acoustics_t)0,
7882 &inStream);
7883#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 }
7885
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007886 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007887 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7888
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007889 // Start record thread
7890 // RecorThread require both input and output device indication to forward to audio
7891 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007892 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007893 thread = new RecordThread(this,
7894 input,
7895 reqSamplingRate,
7896 reqChannels,
7897 id,
7898 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007900 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007901 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007902 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007903 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 // notify client processes of the new input creation
7906 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7907 return id;
7908 }
7909
7910 return 0;
7911}
7912
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007913status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914{
Glenn Kastend96c5722012-04-25 13:44:49 -07007915 return closeInput_nonvirtual(input);
7916}
7917
7918status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7919{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007920 // keep strong reference on the record thread so that
7921 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007922 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007923 {
7924 Mutex::Autolock _l(mLock);
7925 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007926 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007927 return BAD_VALUE;
7928 }
7929
Steve Block3856b092011-10-20 11:56:00 +01007930 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007931 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 mRecordThreads.removeItem(input);
7933 }
7934 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007935 // The thread entity (active unit of execution) is no longer running here,
7936 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007938 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007939 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007940 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007941 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007942 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943
7944 return NO_ERROR;
7945}
7946
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007947status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948{
7949 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951
7952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7953 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007954 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007955 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956
7957 return NO_ERROR;
7958}
7959
7960
7961int AudioFlinger::newAudioSessionId()
7962{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007963 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964}
7965
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007966void AudioFlinger::acquireAudioSessionId(int audioSession)
7967{
7968 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007969 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007970 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007971 size_t num = mAudioSessionRefs.size();
7972 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007973 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007974 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7975 ref->mCnt++;
7976 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007977 return;
7978 }
7979 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007980 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7981 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007982}
7983
7984void AudioFlinger::releaseAudioSessionId(int audioSession)
7985{
7986 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007987 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007988 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007989 size_t num = mAudioSessionRefs.size();
7990 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007991 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007992 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7993 ref->mCnt--;
7994 ALOGV(" decremented refcount to %d", ref->mCnt);
7995 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007996 mAudioSessionRefs.removeAt(i);
7997 delete ref;
7998 purgeStaleEffects_l();
7999 }
8000 return;
8001 }
8002 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008003 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008004}
8005
8006void AudioFlinger::purgeStaleEffects_l() {
8007
Steve Block3856b092011-10-20 11:56:00 +01008008 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008009
8010 Vector< sp<EffectChain> > chains;
8011
8012 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8013 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8014 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8015 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008016 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8017 chains.push(ec);
8018 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008019 }
8020 }
8021 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8022 sp<RecordThread> t = mRecordThreads.valueAt(i);
8023 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8024 sp<EffectChain> ec = t->mEffectChains[j];
8025 chains.push(ec);
8026 }
8027 }
8028
8029 for (size_t i = 0; i < chains.size(); i++) {
8030 sp<EffectChain> ec = chains[i];
8031 int sessionid = ec->sessionId();
8032 sp<ThreadBase> t = ec->mThread.promote();
8033 if (t == 0) {
8034 continue;
8035 }
8036 size_t numsessionrefs = mAudioSessionRefs.size();
8037 bool found = false;
8038 for (size_t k = 0; k < numsessionrefs; k++) {
8039 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008040 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008041 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008042 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008043 found = true;
8044 break;
8045 }
8046 }
8047 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008048 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008049 // remove all effects from the chain
8050 while (ec->mEffects.size()) {
8051 sp<EffectModule> effect = ec->mEffects[0];
8052 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008053 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008054 if (effect->purgeHandles()) {
8055 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008056 }
8057 AudioSystem::unregisterEffect(effect->id());
8058 }
8059 }
8060 }
8061 return;
8062}
8063
Mathias Agopian65ab4712010-07-14 17:59:35 -07008064// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008065AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066{
Glenn Kastena1117922012-01-26 10:53:32 -08008067 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068}
8069
8070// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008071AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008072{
8073 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008074 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075}
8076
8077// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008078AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008079{
Glenn Kastena1117922012-01-26 10:53:32 -08008080 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008081}
8082
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008083uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008085 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086}
8087
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008088AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008089{
8090 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8091 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008092 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008093 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008094 return thread;
8095 }
8096 }
8097 return NULL;
8098}
8099
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008100audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008101{
8102 PlaybackThread *thread = primaryPlaybackThread_l();
8103
8104 if (thread == NULL) {
8105 return 0;
8106 }
8107
Eric Laurentf1c04f92012-08-28 14:26:53 -07008108 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008109}
8110
Eric Laurenta011e352012-03-29 15:51:43 -07008111sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8112 int triggerSession,
8113 int listenerSession,
8114 sync_event_callback_t callBack,
8115 void *cookie)
8116{
8117 Mutex::Autolock _l(mLock);
8118
8119 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8120 status_t playStatus = NAME_NOT_FOUND;
8121 status_t recStatus = NAME_NOT_FOUND;
8122 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8123 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8124 if (playStatus == NO_ERROR) {
8125 return event;
8126 }
8127 }
8128 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8129 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8130 if (recStatus == NO_ERROR) {
8131 return event;
8132 }
8133 }
8134 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8135 mPendingSyncEvents.add(event);
8136 } else {
8137 ALOGV("createSyncEvent() invalid event %d", event->type());
8138 event.clear();
8139 }
8140 return event;
8141}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008142
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143// ----------------------------------------------------------------------------
8144// Effect management
8145// ----------------------------------------------------------------------------
8146
8147
Glenn Kastenf587ba52012-01-26 16:25:10 -08008148status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149{
8150 Mutex::Autolock _l(mLock);
8151 return EffectQueryNumberEffects(numEffects);
8152}
8153
Glenn Kastenf587ba52012-01-26 16:25:10 -08008154status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155{
8156 Mutex::Autolock _l(mLock);
8157 return EffectQueryEffect(index, descriptor);
8158}
8159
Glenn Kasten5e92a782012-01-30 07:40:52 -08008160status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008161 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162{
8163 Mutex::Autolock _l(mLock);
8164 return EffectGetDescriptor(pUuid, descriptor);
8165}
8166
8167
Mathias Agopian65ab4712010-07-14 17:59:35 -07008168sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8169 effect_descriptor_t *pDesc,
8170 const sp<IEffectClient>& effectClient,
8171 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008172 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 int sessionId,
8174 status_t *status,
8175 int *id,
8176 int *enabled)
8177{
8178 status_t lStatus = NO_ERROR;
8179 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008182 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008183 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184
8185 if (pDesc == NULL) {
8186 lStatus = BAD_VALUE;
8187 goto Exit;
8188 }
8189
Eric Laurent84e9a102010-09-23 16:10:16 -07008190 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008191 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008192 lStatus = PERMISSION_DENIED;
8193 goto Exit;
8194 }
8195
Dima Zavinfce7a472011-04-19 22:30:36 -07008196 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008197 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008198 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008199 lStatus = PERMISSION_DENIED;
8200 goto Exit;
8201 }
8202
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008203 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008204 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008205 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008206 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008207 lStatus = BAD_VALUE;
8208 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008209 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008210 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008211 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008212 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008213 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008214 }
8215 }
8216
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 {
8218 Mutex::Autolock _l(mLock);
8219
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220
8221 if (!EffectIsNullUuid(&pDesc->uuid)) {
8222 // if uuid is specified, request effect descriptor
8223 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8224 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008225 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008226 goto Exit;
8227 }
8228 } else {
8229 // if uuid is not specified, look for an available implementation
8230 // of the required type in effect factory
8231 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008232 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008233 lStatus = BAD_VALUE;
8234 goto Exit;
8235 }
8236 uint32_t numEffects = 0;
8237 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008238 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 bool found = false;
8240
8241 lStatus = EffectQueryNumberEffects(&numEffects);
8242 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008243 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008244 goto Exit;
8245 }
8246 for (uint32_t i = 0; i < numEffects; i++) {
8247 lStatus = EffectQueryEffect(i, &desc);
8248 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008249 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250 continue;
8251 }
8252 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8253 // If matching type found save effect descriptor. If the session is
8254 // 0 and the effect is not auxiliary, continue enumeration in case
8255 // an auxiliary version of this effect type is available
8256 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008257 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008258 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8260 break;
8261 }
8262 }
8263 }
8264 if (!found) {
8265 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008266 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008267 goto Exit;
8268 }
8269 // For same effect type, chose auxiliary version over insert version if
8270 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008271 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008273 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 }
8275 }
8276
8277 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008278 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008279 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8280 lStatus = INVALID_OPERATION;
8281 goto Exit;
8282 }
8283
Eric Laurent59255e42011-07-27 19:49:51 -07008284 // check recording permission for visualizer
8285 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8286 !recordingAllowed()) {
8287 lStatus = PERMISSION_DENIED;
8288 goto Exit;
8289 }
8290
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008292 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293
8294 // If output is not specified try to find a matching audio session ID in one of the
8295 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008296 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8297 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008298 // Note: io is never 0 when creating an effect on an input
8299 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008300 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008301 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8302 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008303 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008304 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008306 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008307 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008308 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8309 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8310 io = mRecordThreads.keyAt(i);
8311 break;
8312 }
8313 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008314 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008315 // If no output thread contains the requested session ID, default to
8316 // first output. The effect chain will be moved to the correct output
8317 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008318 if (io == 0 && mPlaybackThreads.size()) {
8319 io = mPlaybackThreads.keyAt(0);
8320 }
Steve Block3856b092011-10-20 11:56:00 +01008321 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008322 }
8323 ThreadBase *thread = checkRecordThread_l(io);
8324 if (thread == NULL) {
8325 thread = checkPlaybackThread_l(io);
8326 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008327 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008328 lStatus = BAD_VALUE;
8329 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008332
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008333 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008334
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008335 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008336 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8337 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008338 if (handle != 0 && id != NULL) {
8339 *id = handle->id();
8340 }
8341 }
8342
8343Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008344 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008345 *status = lStatus;
8346 }
8347 return handle;
8348}
8349
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008350status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8351 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008352{
Steve Block3856b092011-10-20 11:56:00 +01008353 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008354 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008355 Mutex::Autolock _l(mLock);
8356 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008357 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008358 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 }
Eric Laurentde070132010-07-13 04:45:46 -07008360 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8361 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008362 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008363 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364 }
Eric Laurentde070132010-07-13 04:45:46 -07008365 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8366 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008367 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008368 return BAD_VALUE;
8369 }
8370
8371 Mutex::Autolock _dl(dstThread->mLock);
8372 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008373 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008374
Mathias Agopian65ab4712010-07-14 17:59:35 -07008375 return NO_ERROR;
8376}
8377
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008378// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008379status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008380 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008381 AudioFlinger::PlaybackThread *dstThread,
8382 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008383{
Steve Block3856b092011-10-20 11:56:00 +01008384 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008385 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008386
Eric Laurent59255e42011-07-27 19:49:51 -07008387 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008388 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008389 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008390 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008391 return INVALID_OPERATION;
8392 }
8393
Eric Laurent39e94f82010-07-28 01:32:47 -07008394 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008395 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008396 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008397 // removed.
8398 srcThread->removeEffectChain_l(chain);
8399
8400 // transfer all effects one by one so that new effect chain is created on new thread with
8401 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008402 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008403 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008404 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008405 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8406 while (effect != 0) {
8407 srcThread->removeEffect_l(effect);
8408 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008409 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8410 if (effect->state() == EffectModule::ACTIVE ||
8411 effect->state() == EffectModule::STOPPING) {
8412 effect->start();
8413 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008414 // if the move request is not received from audio policy manager, the effect must be
8415 // re-registered with the new strategy and output
8416 if (dstChain == 0) {
8417 dstChain = effect->chain().promote();
8418 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008419 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008420 srcThread->addEffect_l(effect);
8421 return NO_INIT;
8422 }
8423 strategy = dstChain->strategy();
8424 }
8425 if (reRegister) {
8426 AudioSystem::unregisterEffect(effect->id());
8427 AudioSystem::registerEffect(&effect->desc(),
8428 dstOutput,
8429 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008430 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008431 effect->id());
8432 }
Eric Laurentde070132010-07-13 04:45:46 -07008433 effect = chain->getEffectFromId_l(0);
8434 }
8435
8436 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437}
8438
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008439
Mathias Agopian65ab4712010-07-14 17:59:35 -07008440// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008441sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008442 const sp<AudioFlinger::Client>& client,
8443 const sp<IEffectClient>& effectClient,
8444 int32_t priority,
8445 int sessionId,
8446 effect_descriptor_t *desc,
8447 int *enabled,
8448 status_t *status
8449 )
8450{
8451 sp<EffectModule> effect;
8452 sp<EffectHandle> handle;
8453 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008455 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456 bool effectCreated = false;
8457 bool effectRegistered = false;
8458
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008459 lStatus = initCheck();
8460 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008461 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008462 goto Exit;
8463 }
8464
8465 // Do not allow effects with session ID 0 on direct output or duplicating threads
8466 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008467 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008468 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008469 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 lStatus = BAD_VALUE;
8471 goto Exit;
8472 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008473 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008474 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008475 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008476 desc->name, desc->flags, mType);
8477 lStatus = BAD_VALUE;
8478 goto Exit;
8479 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008480
Steve Block3856b092011-10-20 11:56:00 +01008481 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008482
8483 { // scope for mLock
8484 Mutex::Autolock _l(mLock);
8485
8486 // check for existing effect chain with the requested audio session
8487 chain = getEffectChain_l(sessionId);
8488 if (chain == 0) {
8489 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008490 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008491 chain = new EffectChain(this, sessionId);
8492 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008493 chain->setStrategy(getStrategyForSession_l(sessionId));
8494 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008495#ifdef QCOM_HARDWARE
8496 if(sessionId == mAudioFlinger->mLPASessionId) {
8497 // Clear reference to previous effect chain if any
8498 if(mAudioFlinger->mLPAEffectChain.get()) {
8499 mAudioFlinger->mLPAEffectChain.clear();
8500 }
8501 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8502 mAudioFlinger->mLPAEffectChain = chain;
8503 chain->setLPAFlag(true);
8504 // For LPA, the volume will be applied in DSP. No need for volume
8505 // control in the Effect chain, so setting it to unity.
8506 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8507 chain->setVolume_l(&volume,&volume);
8508 }
8509#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008511 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512 }
8513
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008514 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008515
8516 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008517 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008519 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520 if (lStatus != NO_ERROR) {
8521 goto Exit;
8522 }
8523 effectRegistered = true;
8524 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008525 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526 lStatus = effect->status();
8527 if (lStatus != NO_ERROR) {
8528 goto Exit;
8529 }
Eric Laurentcab11242010-07-15 12:50:15 -07008530 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008531 if (lStatus != NO_ERROR) {
8532 goto Exit;
8533 }
8534 effectCreated = true;
8535
Eric Laurentf1c04f92012-08-28 14:26:53 -07008536 effect->setDevice(mOutDevice);
8537 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008539 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008540#ifdef QCOM_HARDWARE
8541 if(chain == mAudioFlinger->mLPAEffectChain) {
8542 effect->setLPAFlag(true);
8543 }
8544#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008545 }
8546 // create effect handle and connect it to effect module
8547 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008548 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008549 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550 *enabled = (int)effect->isEnabled();
8551 }
8552 }
8553
8554Exit:
8555 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008556 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008558 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008559 }
8560 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008561 AudioSystem::unregisterEffect(effect->id());
8562 }
8563 if (chainCreated) {
8564 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565 }
8566 handle.clear();
8567 }
8568
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008569 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008570 *status = lStatus;
8571 }
8572 return handle;
8573}
8574
Eric Laurent717e1282012-06-29 16:36:52 -07008575sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8576{
8577 Mutex::Autolock _l(mLock);
8578 return getEffect_l(sessionId, effectId);
8579}
8580
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008581sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8582{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008583 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008584 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008585}
8586
Eric Laurentde070132010-07-13 04:45:46 -07008587// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8588// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008589status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008590{
8591 // check for existing effect chain with the requested audio session
8592 int sessionId = effect->sessionId();
8593 sp<EffectChain> chain = getEffectChain_l(sessionId);
8594 bool chainCreated = false;
8595
8596 if (chain == 0) {
8597 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008598 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008599 chain = new EffectChain(this, sessionId);
8600 addEffectChain_l(chain);
8601 chain->setStrategy(getStrategyForSession_l(sessionId));
8602 chainCreated = true;
8603 }
Steve Block3856b092011-10-20 11:56:00 +01008604 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008605
8606 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008607 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008608 this, effect->desc().name, chain.get());
8609 return BAD_VALUE;
8610 }
8611
8612 status_t status = chain->addEffect_l(effect);
8613 if (status != NO_ERROR) {
8614 if (chainCreated) {
8615 removeEffectChain_l(chain);
8616 }
8617 return status;
8618 }
8619
Eric Laurentf1c04f92012-08-28 14:26:53 -07008620 effect->setDevice(mOutDevice);
8621 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008622 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008623 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008624 return NO_ERROR;
8625}
8626
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008627void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008628
Steve Block3856b092011-10-20 11:56:00 +01008629 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008630 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008631 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8632 detachAuxEffect_l(effect->id());
8633 }
8634
8635 sp<EffectChain> chain = effect->chain().promote();
8636 if (chain != 0) {
8637 // remove effect chain if removing last effect
8638 if (chain->removeEffect_l(effect) == 0) {
8639 removeEffectChain_l(chain);
8640 }
8641 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008642 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008643 }
8644}
8645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008646void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008647 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008648{
8649 effectChains = mEffectChains;
8650 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008651#ifdef QCOM_HARDWARE
8652 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8653#endif
8654 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008655 }
8656}
8657
8658void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008659 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008660{
8661 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008662#ifdef QCOM_HARDWARE
8663 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8664#endif
8665 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008666 }
8667}
8668
8669sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8670{
8671 Mutex::Autolock _l(mLock);
8672 return getEffectChain_l(sessionId);
8673}
8674
Glenn Kasten106e8a42012-08-02 13:37:12 -07008675sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008676{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008677 size_t size = mEffectChains.size();
8678 for (size_t i = 0; i < size; i++) {
8679 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008680 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008681 }
8682 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008683 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008684}
8685
Glenn Kastenf78aee72012-01-04 11:00:47 -08008686void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008687{
8688 Mutex::Autolock _l(mLock);
8689 size_t size = mEffectChains.size();
8690 for (size_t i = 0; i < size; i++) {
8691 mEffectChains[i]->setMode_l(mode);
8692 }
8693}
8694
8695void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008696 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008697 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008698
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008700 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008701 // delete the effect module if removing last handle on it
8702 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008703 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008704 removeEffect_l(effect);
8705 AudioSystem::unregisterEffect(effect->id());
8706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 }
8708}
8709
8710status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8711{
8712 int session = chain->sessionId();
8713 int16_t *buffer = mMixBuffer;
8714 bool ownsBuffer = false;
8715
Steve Block3856b092011-10-20 11:56:00 +01008716 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008717 if (session > 0) {
8718 // Only one effect chain can be present in direct output thread and it uses
8719 // the mix buffer as input
8720 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008721 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008722 buffer = new int16_t[numSamples];
8723 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008724 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 ownsBuffer = true;
8726 }
8727
8728 // Attach all tracks with same session ID to this chain.
8729 for (size_t i = 0; i < mTracks.size(); ++i) {
8730 sp<Track> track = mTracks[i];
8731 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008732 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008734 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 }
8736 }
8737
8738 // indicate all active tracks in the chain
8739 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8740 sp<Track> track = mActiveTracks[i].promote();
8741 if (track == 0) continue;
8742 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008743 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008744 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008745 }
8746 }
8747 }
8748
8749 chain->setInBuffer(buffer, ownsBuffer);
8750 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008751 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008752 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008753 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8754 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008756 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8757 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008758 // Effect chain for other sessions are inserted at beginning of effect
8759 // chains list to be processed before output mix effects. Relative order between other
8760 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761 size_t size = mEffectChains.size();
8762 size_t i = 0;
8763 for (i = 0; i < size; i++) {
8764 if (mEffectChains[i]->sessionId() < session) break;
8765 }
8766 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008767 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768
8769 return NO_ERROR;
8770}
8771
8772size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8773{
8774 int session = chain->sessionId();
8775
Steve Block3856b092011-10-20 11:56:00 +01008776 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008777
8778 for (size_t i = 0; i < mEffectChains.size(); i++) {
8779 if (chain == mEffectChains[i]) {
8780 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008781 // detach all active tracks from the chain
8782 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8783 sp<Track> track = mActiveTracks[i].promote();
8784 if (track == 0) continue;
8785 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008786 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008787 chain.get(), session);
8788 chain->decActiveTrackCnt();
8789 }
8790 }
8791
Mathias Agopian65ab4712010-07-14 17:59:35 -07008792 // detach all tracks with same session ID from this chain
8793 for (size_t i = 0; i < mTracks.size(); ++i) {
8794 sp<Track> track = mTracks[i];
8795 if (session == track->sessionId()) {
8796 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008797 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798 }
8799 }
Eric Laurentde070132010-07-13 04:45:46 -07008800 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008801 }
8802 }
8803 return mEffectChains.size();
8804}
8805
Eric Laurentde070132010-07-13 04:45:46 -07008806status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8807 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808{
8809 Mutex::Autolock _l(mLock);
8810 return attachAuxEffect_l(track, EffectId);
8811}
8812
Eric Laurentde070132010-07-13 04:45:46 -07008813status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8814 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008815{
8816 status_t status = NO_ERROR;
8817
8818 if (EffectId == 0) {
8819 track->setAuxBuffer(0, NULL);
8820 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008821 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8822 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008823 if (effect != 0) {
8824 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8825 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8826 } else {
8827 status = INVALID_OPERATION;
8828 }
8829 } else {
8830 status = BAD_VALUE;
8831 }
8832 }
8833 return status;
8834}
8835
8836void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8837{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008838 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 sp<Track> track = mTracks[i];
8840 if (track->auxEffectId() == effectId) {
8841 attachAuxEffect_l(track, 0);
8842 }
8843 }
8844}
8845
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008846status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8847{
8848 // only one chain per input thread
8849 if (mEffectChains.size() != 0) {
8850 return INVALID_OPERATION;
8851 }
Steve Block3856b092011-10-20 11:56:00 +01008852 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008853
8854 chain->setInBuffer(NULL);
8855 chain->setOutBuffer(NULL);
8856
Eric Laurent59255e42011-07-27 19:49:51 -07008857 checkSuspendOnAddEffectChain_l(chain);
8858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008859 mEffectChains.add(chain);
8860
8861 return NO_ERROR;
8862}
8863
8864size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8865{
Steve Block3856b092011-10-20 11:56:00 +01008866 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008867 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008868 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8869 chain.get(), mEffectChains.size(), this);
8870 if (mEffectChains.size() == 1) {
8871 mEffectChains.removeAt(0);
8872 }
8873 return 0;
8874}
8875
Mathias Agopian65ab4712010-07-14 17:59:35 -07008876// ----------------------------------------------------------------------------
8877// EffectModule implementation
8878// ----------------------------------------------------------------------------
8879
8880#undef LOG_TAG
8881#define LOG_TAG "AudioFlinger::EffectModule"
8882
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008883AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008884 const wp<AudioFlinger::EffectChain>& chain,
8885 effect_descriptor_t *desc,
8886 int id,
8887 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008888 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8889 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008890 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008891 // mConfig is set by configure() and not used before then
8892 mEffectInterface(NULL),
8893 mStatus(NO_INIT), mState(IDLE),
8894 // mMaxDisableWaitCnt is set by configure() and not used before then
8895 // mDisableWaitCnt is set by process() and updateState() and not used before then
8896 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08008897#ifdef QCOM_HARDWARE
8898 ,mIsForLPA(false)
8899#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008900{
Steve Block3856b092011-10-20 11:56:00 +01008901 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008902 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903
8904 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008905 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008906
8907 if (mStatus != NO_ERROR) {
8908 return;
8909 }
8910 lStatus = init();
8911 if (lStatus < 0) {
8912 mStatus = lStatus;
8913 goto Error;
8914 }
8915
Steve Block3856b092011-10-20 11:56:00 +01008916 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917 return;
8918Error:
8919 EffectRelease(mEffectInterface);
8920 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008921 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922}
8923
8924AudioFlinger::EffectModule::~EffectModule()
8925{
Steve Block3856b092011-10-20 11:56:00 +01008926 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008927 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008928 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8929 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8930 sp<ThreadBase> thread = mThread.promote();
8931 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008932 audio_stream_t *stream = thread->stream();
8933 if (stream != NULL) {
8934 stream->remove_audio_effect(stream, mEffectInterface);
8935 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008936 }
8937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938 // release effect engine
8939 EffectRelease(mEffectInterface);
8940 }
8941}
8942
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008943status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008944{
8945 status_t status;
8946
8947 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008948 int priority = handle->priority();
8949 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008950 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951 size_t i;
8952 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008953 EffectHandle *h = mHandles[i];
8954 if (h == NULL || h->destroyed_l()) continue;
8955 // first non destroyed handle is considered in control
8956 if (controlHandle == NULL)
8957 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008958 if (h->priority() <= priority) break;
8959 }
8960 // if inserted in first place, move effect control from previous owner to this handle
8961 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008962 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008963 if (controlHandle != NULL) {
8964 enabled = controlHandle->enabled();
8965 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966 }
Eric Laurent59255e42011-07-27 19:49:51 -07008967 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008968 status = NO_ERROR;
8969 } else {
8970 status = ALREADY_EXISTS;
8971 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008972 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973 mHandles.insertAt(handle, i);
8974 return status;
8975}
8976
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008977size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978{
8979 Mutex::Autolock _l(mLock);
8980 size_t size = mHandles.size();
8981 size_t i;
8982 for (i = 0; i < size; i++) {
8983 if (mHandles[i] == handle) break;
8984 }
8985 if (i == size) {
8986 return size;
8987 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008988 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008989
Mathias Agopian65ab4712010-07-14 17:59:35 -07008990 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008992 if (i == 0) {
8993 EffectHandle *h = controlHandle_l();
8994 if (h != NULL) {
8995 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008996 }
8997 }
8998
Eric Laurentec437d82011-07-26 20:54:46 -07008999 // Prevent calls to process() and other functions on effect interface from now on.
9000 // The effect engine will be released by the destructor when the last strong reference on
9001 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009002 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009003 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009004 }
9005
Eric Laurente65c8912012-07-20 15:57:23 -07009006 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009007}
9008
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009009// must be called with EffectModule::mLock held
9010AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009011{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009012 // the first valid handle in the list has control over the module
9013 for (size_t i = 0; i < mHandles.size(); i++) {
9014 EffectHandle *h = mHandles[i];
9015 if (h != NULL && !h->destroyed_l()) {
9016 return h;
9017 }
9018 }
9019
9020 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009021}
9022
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009023size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009024{
vivek mehta2192bc92012-12-04 11:46:08 -08009025#ifdef QCOM_HARDWARE
9026 setEnabled(false);
9027#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009028 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029 // keep a strong reference on this EffectModule to avoid calling the
9030 // destructor before we exit
9031 sp<EffectModule> keep(this);
9032 {
9033 sp<ThreadBase> thread = mThread.promote();
9034 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009035 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009036 }
9037 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009038 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009039}
9040
9041void AudioFlinger::EffectModule::updateState() {
9042 Mutex::Autolock _l(mLock);
9043
9044 switch (mState) {
9045 case RESTART:
9046 reset_l();
9047 // FALL THROUGH
9048
9049 case STARTING:
9050 // clear auxiliary effect input buffer for next accumulation
9051 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9052 memset(mConfig.inputCfg.buffer.raw,
9053 0,
9054 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9055 }
9056 start_l();
9057 mState = ACTIVE;
9058 break;
9059 case STOPPING:
9060 stop_l();
9061 mDisableWaitCnt = mMaxDisableWaitCnt;
9062 mState = STOPPED;
9063 break;
9064 case STOPPED:
9065 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9066 // turn off sequence.
9067 if (--mDisableWaitCnt == 0) {
9068 reset_l();
9069 mState = IDLE;
9070 }
9071 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009072 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009073 break;
9074 }
9075}
9076
9077void AudioFlinger::EffectModule::process()
9078{
9079 Mutex::Autolock _l(mLock);
9080
Eric Laurentec437d82011-07-26 20:54:46 -07009081 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009082 mConfig.inputCfg.buffer.raw == NULL ||
9083 mConfig.outputCfg.buffer.raw == NULL) {
9084 return;
9085 }
9086
Eric Laurent8f45bd72010-08-31 13:50:07 -07009087 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009088 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9089 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009090 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009092 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009093 }
9094
9095 // do the actual processing in the effect engine
9096 int ret = (*mEffectInterface)->process(mEffectInterface,
9097 &mConfig.inputCfg.buffer,
9098 &mConfig.outputCfg.buffer);
9099
9100 // force transition to IDLE state when engine is ready
9101 if (mState == STOPPED && ret == -ENODATA) {
9102 mDisableWaitCnt = 1;
9103 }
9104
9105 // clear auxiliary effect input buffer for next accumulation
9106 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009107 memset(mConfig.inputCfg.buffer.raw, 0,
9108 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009109 }
9110 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009111 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9112 // If an insert effect is idle and input buffer is different from output buffer,
9113 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009114 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009115 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009116 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9117 int16_t *in = mConfig.inputCfg.buffer.s16;
9118 int16_t *out = mConfig.outputCfg.buffer.s16;
9119 for (size_t i = 0; i < frameCnt; i++) {
9120 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122 }
9123 }
9124}
9125
9126void AudioFlinger::EffectModule::reset_l()
9127{
9128 if (mEffectInterface == NULL) {
9129 return;
9130 }
9131 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9132}
9133
vivek mehta2192bc92012-12-04 11:46:08 -08009134#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009135status_t AudioFlinger::EffectModule::configure()
9136{
vivek mehta2192bc92012-12-04 11:46:08 -08009137#else
9138status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9139{
9140 uint32_t channels;
9141
9142 // Acquire lock here to make sure that any other thread does not delete
9143 // the effect handle and release the effect module.
9144 Mutex::Autolock _l(mLock);
9145#endif
9146
Mathias Agopian65ab4712010-07-14 17:59:35 -07009147 if (mEffectInterface == NULL) {
9148 return NO_INIT;
9149 }
9150
9151 sp<ThreadBase> thread = mThread.promote();
9152 if (thread == 0) {
9153 return DEAD_OBJECT;
9154 }
9155
9156 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009157 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009158#ifdef QCOM_HARDWARE
9159 mIsForLPA = isForLPA;
9160 if(isForLPA) {
9161 if (channelCount == 1) {
9162 channels = AUDIO_CHANNEL_OUT_MONO;
9163 } else {
9164 channels = AUDIO_CHANNEL_OUT_STEREO;
9165 }
9166 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9167 } else {
9168 if (thread->channelCount() == 1) {
9169 channels = AUDIO_CHANNEL_OUT_MONO;
9170 } else {
9171 channels = AUDIO_CHANNEL_OUT_STEREO;
9172 }
9173 }
9174#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175
9176 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009177 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009178 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009179 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009180 }
Glenn Kasten254af182012-07-03 14:59:05 -07009181 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009182 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9183 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009184#ifdef QCOM_HARDWARE
9185 if(isForLPA){
9186 mConfig.inputCfg.samplingRate = sampleRate;
9187 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9188 } else
9189#endif
9190 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009191 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9192 mConfig.inputCfg.bufferProvider.cookie = NULL;
9193 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9194 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9195 mConfig.outputCfg.bufferProvider.cookie = NULL;
9196 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9197 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9198 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9199 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009200 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009201 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009202 // - in other sessions:
9203 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9204 // other effect: overwrites output buffer: input buffer == output buffer
9205 // Auxiliary effect:
9206 // accumulates in output buffer: input buffer != output buffer
9207 // Therefore: accumulate <=> input buffer != output buffer
9208 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9209 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9210 } else {
9211 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9212 }
9213 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9214 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009215#ifdef QCOM_HARDWARE
9216 if(isForLPA) {
9217 mConfig.inputCfg.buffer.frameCount = frameCount;
9218 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9219 } else
9220#endif
9221 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9223
Steve Block3856b092011-10-20 11:56:00 +01009224 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009225 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9226
Mathias Agopian65ab4712010-07-14 17:59:35 -07009227 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009228 uint32_t size = sizeof(int);
9229 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009230 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009231 sizeof(effect_config_t),
9232 &mConfig,
9233 &size,
9234 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235 if (status == 0) {
9236 status = cmdStatus;
9237 }
9238
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009239 if (status == 0 &&
9240 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9241 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9242 effect_param_t *p = (effect_param_t *)buf32;
9243
9244 p->psize = sizeof(uint32_t);
9245 p->vsize = sizeof(uint32_t);
9246 size = sizeof(int);
9247 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9248
9249 uint32_t latency = 0;
9250 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9251 if (pbt != NULL) {
9252 latency = pbt->latency_l();
9253 }
9254
9255 *((int32_t *)p->data + 1)= latency;
9256 (*mEffectInterface)->command(mEffectInterface,
9257 EFFECT_CMD_SET_PARAM,
9258 sizeof(effect_param_t) + 8,
9259 &buf32,
9260 &size,
9261 &cmdStatus);
9262 }
9263
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9265 (1000 * mConfig.outputCfg.buffer.frameCount);
9266
9267 return status;
9268}
9269
9270status_t AudioFlinger::EffectModule::init()
9271{
9272 Mutex::Autolock _l(mLock);
9273 if (mEffectInterface == NULL) {
9274 return NO_INIT;
9275 }
9276 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009277 uint32_t size = sizeof(status_t);
9278 status_t status = (*mEffectInterface)->command(mEffectInterface,
9279 EFFECT_CMD_INIT,
9280 0,
9281 NULL,
9282 &size,
9283 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009284 if (status == 0) {
9285 status = cmdStatus;
9286 }
9287 return status;
9288}
9289
Eric Laurentec35a142011-10-05 17:42:25 -07009290status_t AudioFlinger::EffectModule::start()
9291{
9292 Mutex::Autolock _l(mLock);
9293 return start_l();
9294}
9295
Mathias Agopian65ab4712010-07-14 17:59:35 -07009296status_t AudioFlinger::EffectModule::start_l()
9297{
9298 if (mEffectInterface == NULL) {
9299 return NO_INIT;
9300 }
9301 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009302 uint32_t size = sizeof(status_t);
9303 status_t status = (*mEffectInterface)->command(mEffectInterface,
9304 EFFECT_CMD_ENABLE,
9305 0,
9306 NULL,
9307 &size,
9308 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009309 if (status == 0) {
9310 status = cmdStatus;
9311 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009312 if (status == 0 &&
9313 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9314 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9315 sp<ThreadBase> thread = mThread.promote();
9316 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009317 audio_stream_t *stream = thread->stream();
9318 if (stream != NULL) {
9319 stream->add_audio_effect(stream, mEffectInterface);
9320 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009321 }
9322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009323 return status;
9324}
9325
Eric Laurentec437d82011-07-26 20:54:46 -07009326status_t AudioFlinger::EffectModule::stop()
9327{
9328 Mutex::Autolock _l(mLock);
9329 return stop_l();
9330}
9331
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332status_t AudioFlinger::EffectModule::stop_l()
9333{
9334 if (mEffectInterface == NULL) {
9335 return NO_INIT;
9336 }
9337 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009338 uint32_t size = sizeof(status_t);
9339 status_t status = (*mEffectInterface)->command(mEffectInterface,
9340 EFFECT_CMD_DISABLE,
9341 0,
9342 NULL,
9343 &size,
9344 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009345 if (status == 0) {
9346 status = cmdStatus;
9347 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009348 if (status == 0 &&
9349 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9350 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9351 sp<ThreadBase> thread = mThread.promote();
9352 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009353 audio_stream_t *stream = thread->stream();
9354 if (stream != NULL) {
9355 stream->remove_audio_effect(stream, mEffectInterface);
9356 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009357 }
9358 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009359 return status;
9360}
9361
Eric Laurent25f43952010-07-28 05:40:18 -07009362status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9363 uint32_t cmdSize,
9364 void *pCmdData,
9365 uint32_t *replySize,
9366 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009367{
9368 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009369// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009370
Eric Laurentec437d82011-07-26 20:54:46 -07009371 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009372 return NO_INIT;
9373 }
Eric Laurent25f43952010-07-28 05:40:18 -07009374 status_t status = (*mEffectInterface)->command(mEffectInterface,
9375 cmdCode,
9376 cmdSize,
9377 pCmdData,
9378 replySize,
9379 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009380 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009381 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009382 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009383 EffectHandle *h = mHandles[i];
9384 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009385 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9386 }
9387 }
9388 }
9389 return status;
9390}
9391
9392status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9393{
9394 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009395 return setEnabled_l(enabled);
9396}
9397
9398// must be called with EffectModule::mLock held
9399status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9400{
vivek mehta2192bc92012-12-04 11:46:08 -08009401#ifdef QCOM_HARDWARE
9402 bool effectStateChanged = false;
9403#endif
Steve Block3856b092011-10-20 11:56:00 +01009404 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009405
9406 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009407#ifdef QCOM_HARDWARE
9408 effectStateChanged = true;
9409#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009410 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9411 if (enabled && status != NO_ERROR) {
9412 return status;
9413 }
9414
Mathias Agopian65ab4712010-07-14 17:59:35 -07009415 switch (mState) {
9416 // going from disabled to enabled
9417 case IDLE:
9418 mState = STARTING;
9419 break;
9420 case STOPPED:
9421 mState = RESTART;
9422 break;
9423 case STOPPING:
9424 mState = ACTIVE;
9425 break;
9426
9427 // going from enabled to disabled
9428 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009429 mState = STOPPED;
9430 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009431 case STARTING:
9432 mState = IDLE;
9433 break;
9434 case ACTIVE:
9435 mState = STOPPING;
9436 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009437 case DESTROYED:
9438 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009439 }
9440 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009441 EffectHandle *h = mHandles[i];
9442 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009443 h->setEnabled(enabled);
9444 }
9445 }
9446 }
vivek mehta2192bc92012-12-04 11:46:08 -08009447#ifdef QCOM_HARDWARE
9448 /*
9449 Send notification event to LPA Player when an effect for
9450 LPA output is enabled or disabled.
9451 */
9452 if (effectStateChanged && mIsForLPA) {
9453 sp<ThreadBase> thread = mThread.promote();
9454 thread->effectConfigChanged();
9455 }
9456#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009457 return NO_ERROR;
9458}
9459
Glenn Kastenc59c0042012-02-02 14:06:11 -08009460bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009461{
9462 switch (mState) {
9463 case RESTART:
9464 case STARTING:
9465 case ACTIVE:
9466 return true;
9467 case IDLE:
9468 case STOPPING:
9469 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009470 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009471 default:
9472 return false;
9473 }
9474}
9475
Glenn Kastenc59c0042012-02-02 14:06:11 -08009476bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009477{
9478 switch (mState) {
9479 case RESTART:
9480 case ACTIVE:
9481 case STOPPING:
9482 case STOPPED:
9483 return true;
9484 case IDLE:
9485 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009486 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009487 default:
9488 return false;
9489 }
9490}
9491
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9493{
9494 Mutex::Autolock _l(mLock);
9495 status_t status = NO_ERROR;
9496
9497 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9498 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009499 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009500 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9501 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009502 status_t cmdStatus;
9503 uint32_t volume[2];
9504 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009505 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009506 volume[0] = *left;
9507 volume[1] = *right;
9508 if (controller) {
9509 pVolume = volume;
9510 }
Eric Laurent25f43952010-07-28 05:40:18 -07009511 status = (*mEffectInterface)->command(mEffectInterface,
9512 EFFECT_CMD_SET_VOLUME,
9513 size,
9514 volume,
9515 &size,
9516 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009517 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9518 *left = volume[0];
9519 *right = volume[1];
9520 }
9521 }
9522 return status;
9523}
9524
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009525status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009526{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009527 if (device == AUDIO_DEVICE_NONE) {
9528 return NO_ERROR;
9529 }
9530
Mathias Agopian65ab4712010-07-14 17:59:35 -07009531 Mutex::Autolock _l(mLock);
9532 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009533 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009534 status_t cmdStatus;
9535 uint32_t size = sizeof(status_t);
9536 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9537 EFFECT_CMD_SET_INPUT_DEVICE;
9538 status = (*mEffectInterface)->command(mEffectInterface,
9539 cmd,
9540 sizeof(uint32_t),
9541 &device,
9542 &size,
9543 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009544 }
9545 return status;
9546}
9547
Glenn Kastenf78aee72012-01-04 11:00:47 -08009548status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009549{
9550 Mutex::Autolock _l(mLock);
9551 status_t status = NO_ERROR;
9552 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009553 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009554 uint32_t size = sizeof(status_t);
9555 status = (*mEffectInterface)->command(mEffectInterface,
9556 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009557 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009558 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009559 &size,
9560 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009561 if (status == NO_ERROR) {
9562 status = cmdStatus;
9563 }
9564 }
9565 return status;
9566}
9567
Eric Laurent57b2dd12012-08-31 17:44:06 -07009568status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9569{
9570 Mutex::Autolock _l(mLock);
9571 status_t status = NO_ERROR;
9572 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9573 uint32_t size = 0;
9574 status = (*mEffectInterface)->command(mEffectInterface,
9575 EFFECT_CMD_SET_AUDIO_SOURCE,
9576 sizeof(audio_source_t),
9577 &source,
9578 &size,
9579 NULL);
9580 }
9581 return status;
9582}
9583
Eric Laurent59255e42011-07-27 19:49:51 -07009584void AudioFlinger::EffectModule::setSuspended(bool suspended)
9585{
9586 Mutex::Autolock _l(mLock);
9587 mSuspended = suspended;
9588}
Glenn Kastena3a85482012-01-04 11:01:11 -08009589
9590bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009591{
9592 Mutex::Autolock _l(mLock);
9593 return mSuspended;
9594}
9595
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009596bool AudioFlinger::EffectModule::purgeHandles()
9597{
9598 bool enabled = false;
9599 Mutex::Autolock _l(mLock);
9600 for (size_t i = 0; i < mHandles.size(); i++) {
9601 EffectHandle *handle = mHandles[i];
9602 if (handle != NULL && !handle->destroyed_l()) {
9603 handle->effect().clear();
9604 if (handle->hasControl()) {
9605 enabled = handle->enabled();
9606 }
9607 }
9608 }
9609 return enabled;
9610}
9611
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009612void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009613{
9614 const size_t SIZE = 256;
9615 char buffer[SIZE];
9616 String8 result;
9617
9618 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9619 result.append(buffer);
9620
9621 bool locked = tryLock(mLock);
9622 // failed to lock - AudioFlinger is probably deadlocked
9623 if (!locked) {
9624 result.append("\t\tCould not lock Fx mutex:\n");
9625 }
9626
9627 result.append("\t\tSession Status State Engine:\n");
9628 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9629 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9630 result.append(buffer);
9631
9632 result.append("\t\tDescriptor:\n");
9633 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9634 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9635 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9636 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9637 result.append(buffer);
9638 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9639 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9640 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9641 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9642 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009643 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009644 mDescriptor.apiVersion,
9645 mDescriptor.flags);
9646 result.append(buffer);
9647 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9648 mDescriptor.name);
9649 result.append(buffer);
9650 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9651 mDescriptor.implementor);
9652 result.append(buffer);
9653
9654 result.append("\t\t- Input configuration:\n");
9655 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9656 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9657 (uint32_t)mConfig.inputCfg.buffer.raw,
9658 mConfig.inputCfg.buffer.frameCount,
9659 mConfig.inputCfg.samplingRate,
9660 mConfig.inputCfg.channels,
9661 mConfig.inputCfg.format);
9662 result.append(buffer);
9663
9664 result.append("\t\t- Output configuration:\n");
9665 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9666 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9667 (uint32_t)mConfig.outputCfg.buffer.raw,
9668 mConfig.outputCfg.buffer.frameCount,
9669 mConfig.outputCfg.samplingRate,
9670 mConfig.outputCfg.channels,
9671 mConfig.outputCfg.format);
9672 result.append(buffer);
9673
9674 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9675 result.append(buffer);
9676 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9677 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009678 EffectHandle *handle = mHandles[i];
9679 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009680 handle->dump(buffer, SIZE);
9681 result.append(buffer);
9682 }
9683 }
9684
9685 result.append("\n");
9686
9687 write(fd, result.string(), result.length());
9688
9689 if (locked) {
9690 mLock.unlock();
9691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009692}
9693
9694// ----------------------------------------------------------------------------
9695// EffectHandle implementation
9696// ----------------------------------------------------------------------------
9697
9698#undef LOG_TAG
9699#define LOG_TAG "AudioFlinger::EffectHandle"
9700
9701AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9702 const sp<AudioFlinger::Client>& client,
9703 const sp<IEffectClient>& effectClient,
9704 int32_t priority)
9705 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009706 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009707 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009708{
Steve Block3856b092011-10-20 11:56:00 +01009709 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009710
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009711 if (client == 0) {
9712 return;
9713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009714 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9715 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9716 if (mCblkMemory != 0) {
9717 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9718
Glenn Kastena0d68332012-01-27 16:47:15 -08009719 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009720 new(mCblk) effect_param_cblk_t();
9721 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009723 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009724 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009725 return;
9726 }
9727}
9728
9729AudioFlinger::EffectHandle::~EffectHandle()
9730{
Steve Block3856b092011-10-20 11:56:00 +01009731 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009732
9733 if (mEffect == 0) {
9734 mDestroyed = true;
9735 return;
9736 }
9737 mEffect->lock();
9738 mDestroyed = true;
9739 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009740 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009741}
9742
9743status_t AudioFlinger::EffectHandle::enable()
9744{
Steve Block3856b092011-10-20 11:56:00 +01009745 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009746 if (!mHasControl) return INVALID_OPERATION;
9747 if (mEffect == 0) return DEAD_OBJECT;
9748
Eric Laurentdb7c0792011-08-10 10:37:50 -07009749 if (mEnabled) {
9750 return NO_ERROR;
9751 }
9752
Eric Laurent59255e42011-07-27 19:49:51 -07009753 mEnabled = true;
9754
9755 sp<ThreadBase> thread = mEffect->thread().promote();
9756 if (thread != 0) {
9757 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9758 }
9759
9760 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9761 if (mEffect->suspended()) {
9762 return NO_ERROR;
9763 }
9764
Eric Laurentdb7c0792011-08-10 10:37:50 -07009765 status_t status = mEffect->setEnabled(true);
9766 if (status != NO_ERROR) {
9767 if (thread != 0) {
9768 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9769 }
9770 mEnabled = false;
9771 }
9772 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009773}
9774
9775status_t AudioFlinger::EffectHandle::disable()
9776{
Steve Block3856b092011-10-20 11:56:00 +01009777 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009778 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009779 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009780
Eric Laurentdb7c0792011-08-10 10:37:50 -07009781 if (!mEnabled) {
9782 return NO_ERROR;
9783 }
Eric Laurent59255e42011-07-27 19:49:51 -07009784 mEnabled = false;
9785
9786 if (mEffect->suspended()) {
9787 return NO_ERROR;
9788 }
9789
9790 status_t status = mEffect->setEnabled(false);
9791
9792 sp<ThreadBase> thread = mEffect->thread().promote();
9793 if (thread != 0) {
9794 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9795 }
9796
9797 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009798}
9799
9800void AudioFlinger::EffectHandle::disconnect()
9801{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009802 disconnect(true);
9803}
9804
Glenn Kasten58123c32012-02-03 10:32:24 -08009805void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009806{
Glenn Kasten58123c32012-02-03 10:32:24 -08009807 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009808 if (mEffect == 0) {
9809 return;
9810 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009811 // restore suspended effects if the disconnected handle was enabled and the last one.
9812 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009813 sp<ThreadBase> thread = mEffect->thread().promote();
9814 if (thread != 0) {
9815 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9816 }
Eric Laurent59255e42011-07-27 19:49:51 -07009817 }
9818
Mathias Agopian65ab4712010-07-14 17:59:35 -07009819 // release sp on module => module destructor can be called now
9820 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009821 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009822 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009823 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009824 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9825 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009826 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009827 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009828 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9829 mClient.clear();
9830 }
9831}
9832
Eric Laurent25f43952010-07-28 05:40:18 -07009833status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9834 uint32_t cmdSize,
9835 void *pCmdData,
9836 uint32_t *replySize,
9837 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009838{
Steve Block3856b092011-10-20 11:56:00 +01009839// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009840// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009841
9842 // only get parameter command is permitted for applications not controlling the effect
9843 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9844 return INVALID_OPERATION;
9845 }
9846 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009847 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009848
9849 // handle commands that are not forwarded transparently to effect engine
9850 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9851 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9852 // no risk to block the whole media server process or mixer threads is we are stuck here
9853 Mutex::Autolock _l(mCblk->lock);
9854 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9855 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9856 mCblk->serverIndex = 0;
9857 mCblk->clientIndex = 0;
9858 return BAD_VALUE;
9859 }
9860 status_t status = NO_ERROR;
9861 while (mCblk->serverIndex < mCblk->clientIndex) {
9862 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009863 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009864 int *p = (int *)(mBuffer + mCblk->serverIndex);
9865 int size = *p++;
9866 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009867 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009868 break;
9869 }
9870 effect_param_t *param = (effect_param_t *)p;
9871 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009872 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009873 mCblk->serverIndex += size;
9874 continue;
9875 }
Eric Laurent25f43952010-07-28 05:40:18 -07009876 uint32_t psize = sizeof(effect_param_t) +
9877 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9878 param->vsize;
9879 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9880 psize,
9881 p,
9882 &rsize,
9883 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009884 // stop at first error encountered
9885 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009886 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009887 *(int *)pReplyData = reply;
9888 break;
9889 } else if (reply != NO_ERROR) {
9890 *(int *)pReplyData = reply;
9891 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009892 }
9893 mCblk->serverIndex += size;
9894 }
9895 mCblk->serverIndex = 0;
9896 mCblk->clientIndex = 0;
9897 return status;
9898 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009899 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009900 return enable();
9901 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009902 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009903 return disable();
9904 }
9905
vivek mehta2192bc92012-12-04 11:46:08 -08009906#ifdef QCOM_HARDWARE
9907 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
9908 if(mEffect->isOnLPA() &&
9909 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
9910 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
9911 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
9912 // Notify Direct track for the change in Effect module
9913 // TODO: check if it is required to send mLPAHandle
9914 ALOGV("Notifying Direct Track for the change in effect config");
9915 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
9916 }
9917#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009918 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9919}
9920
Eric Laurent59255e42011-07-27 19:49:51 -07009921void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009922{
Steve Block3856b092011-10-20 11:56:00 +01009923 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009924
9925 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009926 mEnabled = enabled;
9927
Mathias Agopian65ab4712010-07-14 17:59:35 -07009928 if (signal && mEffectClient != 0) {
9929 mEffectClient->controlStatusChanged(hasControl);
9930 }
9931}
9932
Eric Laurent25f43952010-07-28 05:40:18 -07009933void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9934 uint32_t cmdSize,
9935 void *pCmdData,
9936 uint32_t replySize,
9937 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009938{
9939 if (mEffectClient != 0) {
9940 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9941 }
9942}
9943
9944
9945
9946void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9947{
9948 if (mEffectClient != 0) {
9949 mEffectClient->enableStatusChanged(enabled);
9950 }
9951}
9952
9953status_t AudioFlinger::EffectHandle::onTransact(
9954 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9955{
9956 return BnEffect::onTransact(code, data, reply, flags);
9957}
9958
9959
9960void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9961{
Glenn Kastena0d68332012-01-27 16:47:15 -08009962 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009963
9964 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009965 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009966 mPriority,
9967 mHasControl,
9968 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009969 mCblk ? mCblk->clientIndex : 0,
9970 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009971 );
9972
9973 if (locked) {
9974 mCblk->lock.unlock();
9975 }
9976}
9977
9978#undef LOG_TAG
9979#define LOG_TAG "AudioFlinger::EffectChain"
9980
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009981AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009982 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009983 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009984 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9985 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -08009986#ifdef QCOM_HARDWARE
9987 ,mIsForLPATrack(false)
9988#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009989{
Dima Zavinfce7a472011-04-19 22:30:36 -07009990 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009991 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009992 return;
9993 }
9994 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9995 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009996}
9997
9998AudioFlinger::EffectChain::~EffectChain()
9999{
10000 if (mOwnInBuffer) {
10001 delete mInBuffer;
10002 }
10003
10004}
10005
Eric Laurent59255e42011-07-27 19:49:51 -070010006// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010007sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010008{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010009 size_t size = mEffects.size();
10010
10011 for (size_t i = 0; i < size; i++) {
10012 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010013 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010014 }
10015 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010016 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010017}
10018
Eric Laurent59255e42011-07-27 19:49:51 -070010019// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010020sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010021{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010022 size_t size = mEffects.size();
10023
10024 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010025 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10026 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010027 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010028 }
10029 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010030 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010031}
10032
vivek mehta2192bc92012-12-04 11:46:08 -080010033#ifdef QCOM_HARDWARE
10034sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10035{
10036 sp<EffectModule> effect = NULL;
10037 if(idx < 0 || idx >= mEffects.size()) {
10038 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10039 }
10040 if(mEffects.size() > 0){
10041 effect = mEffects[idx];
10042 }
10043 return effect;
10044}
10045#endif
10046
Eric Laurent59255e42011-07-27 19:49:51 -070010047// getEffectFromType_l() must be called with ThreadBase::mLock held
10048sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10049 const effect_uuid_t *type)
10050{
Eric Laurent59255e42011-07-27 19:49:51 -070010051 size_t size = mEffects.size();
10052
10053 for (size_t i = 0; i < size; i++) {
10054 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010055 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010056 }
10057 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010058 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010059}
10060
Eric Laurent91b14c42012-05-30 12:30:29 -070010061void AudioFlinger::EffectChain::clearInputBuffer()
10062{
10063 Mutex::Autolock _l(mLock);
10064 sp<ThreadBase> thread = mThread.promote();
10065 if (thread == 0) {
10066 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10067 return;
10068 }
10069 clearInputBuffer_l(thread);
10070}
10071
10072// Must be called with EffectChain::mLock locked
10073void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10074{
10075 size_t numSamples = thread->frameCount() * thread->channelCount();
10076 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10077
10078}
10079
Mathias Agopian65ab4712010-07-14 17:59:35 -070010080// Must be called with EffectChain::mLock locked
10081void AudioFlinger::EffectChain::process_l()
10082{
Eric Laurentdac69112010-09-28 14:09:57 -070010083 sp<ThreadBase> thread = mThread.promote();
10084 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010085 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010086 return;
10087 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010088 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10089 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010090 // always process effects unless no more tracks are on the session and the effect tail
10091 // has been rendered
10092 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010093 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010094 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010095
Eric Laurent544fe9b2011-11-11 15:42:52 -080010096 if (!tracksOnSession && mTailBufferCount == 0) {
10097 doProcess = false;
10098 }
10099
10100 if (activeTrackCnt() == 0) {
10101 // if no track is active and the effect tail has not been rendered,
10102 // the input buffer must be cleared here as the mixer process will not do it
10103 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010104 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010105 if (mTailBufferCount > 0) {
10106 mTailBufferCount--;
10107 }
10108 }
10109 }
Eric Laurentdac69112010-09-28 14:09:57 -070010110 }
10111
Mathias Agopian65ab4712010-07-14 17:59:35 -070010112 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010113#ifdef QCOM_HARDWARE
10114 if (doProcess || isForLPATrack()) {
10115#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010116 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010117#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010118 for (size_t i = 0; i < size; i++) {
10119 mEffects[i]->process();
10120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010121 }
10122 for (size_t i = 0; i < size; i++) {
10123 mEffects[i]->updateState();
10124 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010125}
10126
Eric Laurentcab11242010-07-15 12:50:15 -070010127// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010128status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010129{
10130 effect_descriptor_t desc = effect->desc();
10131 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10132
10133 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010134 effect->setChain(this);
10135 sp<ThreadBase> thread = mThread.promote();
10136 if (thread == 0) {
10137 return NO_INIT;
10138 }
10139 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010140
10141 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10142 // Auxiliary effects are inserted at the beginning of mEffects vector as
10143 // they are processed first and accumulated in chain input buffer
10144 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010145
Mathias Agopian65ab4712010-07-14 17:59:35 -070010146 // the input buffer for auxiliary effect contains mono samples in
10147 // 32 bit format. This is to avoid saturation in AudoMixer
10148 // accumulation stage. Saturation is done in EffectModule::process() before
10149 // calling the process in effect engine
10150 size_t numSamples = thread->frameCount();
10151 int32_t *buffer = new int32_t[numSamples];
10152 memset(buffer, 0, numSamples * sizeof(int32_t));
10153 effect->setInBuffer((int16_t *)buffer);
10154 // auxiliary effects output samples to chain input buffer for further processing
10155 // by insert effects
10156 effect->setOutBuffer(mInBuffer);
10157 } else {
10158 // Insert effects are inserted at the end of mEffects vector as they are processed
10159 // after track and auxiliary effects.
10160 // Insert effect order as a function of indicated preference:
10161 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10162 // another effect is present
10163 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10164 // last effect claiming first position
10165 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10166 // first effect claiming last position
10167 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10168 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10169 // already present
10170
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010171 size_t size = mEffects.size();
10172 size_t idx_insert = size;
10173 ssize_t idx_insert_first = -1;
10174 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010175
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010176 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010177 effect_descriptor_t d = mEffects[i]->desc();
10178 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10179 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10180 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10181 // check invalid effect chaining combinations
10182 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10183 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010184 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010185 return INVALID_OPERATION;
10186 }
10187 // remember position of first insert effect and by default
10188 // select this as insert position for new effect
10189 if (idx_insert == size) {
10190 idx_insert = i;
10191 }
10192 // remember position of last insert effect claiming
10193 // first position
10194 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10195 idx_insert_first = i;
10196 }
10197 // remember position of first insert effect claiming
10198 // last position
10199 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10200 idx_insert_last == -1) {
10201 idx_insert_last = i;
10202 }
10203 }
10204 }
10205
10206 // modify idx_insert from first position if needed
10207 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10208 if (idx_insert_last != -1) {
10209 idx_insert = idx_insert_last;
10210 } else {
10211 idx_insert = size;
10212 }
10213 } else {
10214 if (idx_insert_first != -1) {
10215 idx_insert = idx_insert_first + 1;
10216 }
10217 }
10218
10219 // always read samples from chain input buffer
10220 effect->setInBuffer(mInBuffer);
10221
10222 // if last effect in the chain, output samples to chain
10223 // output buffer, otherwise to chain input buffer
10224 if (idx_insert == size) {
10225 if (idx_insert != 0) {
10226 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10227 mEffects[idx_insert-1]->configure();
10228 }
10229 effect->setOutBuffer(mOutBuffer);
10230 } else {
10231 effect->setOutBuffer(mInBuffer);
10232 }
10233 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010234
Steve Block3856b092011-10-20 11:56:00 +010010235 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010236 }
10237 effect->configure();
10238 return NO_ERROR;
10239}
10240
Eric Laurentcab11242010-07-15 12:50:15 -070010241// removeEffect_l() must be called with PlaybackThread::mLock held
10242size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010243{
10244 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010245 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010246 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10247
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010248 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010249 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010250 // calling stop here will remove pre-processing effect from the audio HAL.
10251 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10252 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010253 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10254 mEffects[i]->state() == EffectModule::STOPPING) {
10255 mEffects[i]->stop();
10256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010257 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10258 delete[] effect->inBuffer();
10259 } else {
10260 if (i == size - 1 && i != 0) {
10261 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10262 mEffects[i - 1]->configure();
10263 }
10264 }
10265 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010266 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010267 break;
10268 }
10269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010270
10271 return mEffects.size();
10272}
10273
Eric Laurentcab11242010-07-15 12:50:15 -070010274// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010275void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010276{
10277 size_t size = mEffects.size();
10278 for (size_t i = 0; i < size; i++) {
10279 mEffects[i]->setDevice(device);
10280 }
10281}
10282
Eric Laurentcab11242010-07-15 12:50:15 -070010283// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010284void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010285{
10286 size_t size = mEffects.size();
10287 for (size_t i = 0; i < size; i++) {
10288 mEffects[i]->setMode(mode);
10289 }
10290}
10291
Eric Laurent57b2dd12012-08-31 17:44:06 -070010292// setAudioSource_l() must be called with PlaybackThread::mLock held
10293void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10294{
10295 size_t size = mEffects.size();
10296 for (size_t i = 0; i < size; i++) {
10297 mEffects[i]->setAudioSource(source);
10298 }
10299}
10300
Eric Laurentcab11242010-07-15 12:50:15 -070010301// setVolume_l() must be called with PlaybackThread::mLock held
10302bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010303{
10304 uint32_t newLeft = *left;
10305 uint32_t newRight = *right;
10306 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010307 int ctrlIdx = -1;
10308 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010309
Eric Laurentcab11242010-07-15 12:50:15 -070010310 // first update volume controller
10311 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010312 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010313 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10314 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010315 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010316 break;
10317 }
10318 }
10319
10320 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010321 if (hasControl) {
10322 *left = mNewLeftVolume;
10323 *right = mNewRightVolume;
10324 }
10325 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010326 }
10327
10328 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010329 mLeftVolume = newLeft;
10330 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010331
10332 // second get volume update from volume controller
10333 if (ctrlIdx >= 0) {
10334 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010335 mNewLeftVolume = newLeft;
10336 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010337 }
10338 // then indicate volume to all other effects in chain.
10339 // Pass altered volume to effects before volume controller
10340 // and requested volume to effects after controller
10341 uint32_t lVol = newLeft;
10342 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010343
Mathias Agopian65ab4712010-07-14 17:59:35 -070010344 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010345 if ((int)i == ctrlIdx) continue;
10346 // this also works for ctrlIdx == -1 when there is no volume controller
10347 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010348 lVol = *left;
10349 rVol = *right;
10350 }
10351 mEffects[i]->setVolume(&lVol, &rVol, false);
10352 }
10353 *left = newLeft;
10354 *right = newRight;
10355
10356 return hasControl;
10357}
10358
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010359void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010360{
10361 const size_t SIZE = 256;
10362 char buffer[SIZE];
10363 String8 result;
10364
10365 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10366 result.append(buffer);
10367
10368 bool locked = tryLock(mLock);
10369 // failed to lock - AudioFlinger is probably deadlocked
10370 if (!locked) {
10371 result.append("\tCould not lock mutex:\n");
10372 }
10373
Eric Laurentcab11242010-07-15 12:50:15 -070010374 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10375 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010376 mEffects.size(),
10377 (uint32_t)mInBuffer,
10378 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010379 mActiveTrackCnt);
10380 result.append(buffer);
10381 write(fd, result.string(), result.size());
10382
10383 for (size_t i = 0; i < mEffects.size(); ++i) {
10384 sp<EffectModule> effect = mEffects[i];
10385 if (effect != 0) {
10386 effect->dump(fd, args);
10387 }
10388 }
10389
10390 if (locked) {
10391 mLock.unlock();
10392 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010393}
10394
Eric Laurent59255e42011-07-27 19:49:51 -070010395// must be called with ThreadBase::mLock held
10396void AudioFlinger::EffectChain::setEffectSuspended_l(
10397 const effect_uuid_t *type, bool suspend)
10398{
10399 sp<SuspendedEffectDesc> desc;
10400 // use effect type UUID timelow as key as there is no real risk of identical
10401 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010402 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010403 if (suspend) {
10404 if (index >= 0) {
10405 desc = mSuspendedEffects.valueAt(index);
10406 } else {
10407 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010408 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010409 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010410 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010411 }
10412 if (desc->mRefCount++ == 0) {
10413 sp<EffectModule> effect = getEffectIfEnabled(type);
10414 if (effect != 0) {
10415 desc->mEffect = effect;
10416 effect->setSuspended(true);
10417 effect->setEnabled(false);
10418 }
10419 }
10420 } else {
10421 if (index < 0) {
10422 return;
10423 }
10424 desc = mSuspendedEffects.valueAt(index);
10425 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010426 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010427 desc->mRefCount = 1;
10428 }
10429 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010430 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010431 if (desc->mEffect != 0) {
10432 sp<EffectModule> effect = desc->mEffect.promote();
10433 if (effect != 0) {
10434 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010435 effect->lock();
10436 EffectHandle *handle = effect->controlHandle_l();
10437 if (handle != NULL && !handle->destroyed_l()) {
10438 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010439 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010440 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010441 }
10442 desc->mEffect.clear();
10443 }
10444 mSuspendedEffects.removeItemsAt(index);
10445 }
10446 }
10447}
10448
10449// must be called with ThreadBase::mLock held
10450void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10451{
10452 sp<SuspendedEffectDesc> desc;
10453
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010454 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010455 if (suspend) {
10456 if (index >= 0) {
10457 desc = mSuspendedEffects.valueAt(index);
10458 } else {
10459 desc = new SuspendedEffectDesc();
10460 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010461 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010462 }
10463 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010464 Vector< sp<EffectModule> > effects;
10465 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010466 for (size_t i = 0; i < effects.size(); i++) {
10467 setEffectSuspended_l(&effects[i]->desc().type, true);
10468 }
10469 }
10470 } else {
10471 if (index < 0) {
10472 return;
10473 }
10474 desc = mSuspendedEffects.valueAt(index);
10475 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010476 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010477 desc->mRefCount = 1;
10478 }
10479 if (--desc->mRefCount == 0) {
10480 Vector<const effect_uuid_t *> types;
10481 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10482 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10483 continue;
10484 }
10485 types.add(&mSuspendedEffects.valueAt(i)->mType);
10486 }
10487 for (size_t i = 0; i < types.size(); i++) {
10488 setEffectSuspended_l(types[i], false);
10489 }
Steve Block3856b092011-10-20 11:56:00 +010010490 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010491 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10492 }
10493 }
10494}
10495
Eric Laurent6bffdb82011-09-23 08:40:41 -070010496
10497// The volume effect is used for automated tests only
10498#ifndef OPENSL_ES_H_
10499static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10500 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10501const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10502#endif //OPENSL_ES_H_
10503
Eric Laurentdb7c0792011-08-10 10:37:50 -070010504bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10505{
10506 // auxiliary effects and visualizer are never suspended on output mix
10507 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10508 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010509 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10510 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010511 return false;
10512 }
10513 return true;
10514}
10515
Glenn Kastend0539712012-01-30 12:56:03 -080010516void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010517{
Glenn Kastend0539712012-01-30 12:56:03 -080010518 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010519 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010520 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10521 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010522 }
Eric Laurent59255e42011-07-27 19:49:51 -070010523 }
Eric Laurent59255e42011-07-27 19:49:51 -070010524}
10525
10526sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10527 const effect_uuid_t *type)
10528{
Glenn Kasten090f0192012-01-30 13:00:02 -080010529 sp<EffectModule> effect = getEffectFromType_l(type);
10530 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010531}
10532
10533void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10534 bool enabled)
10535{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010536 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010537 if (enabled) {
10538 if (index < 0) {
10539 // if the effect is not suspend check if all effects are suspended
10540 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10541 if (index < 0) {
10542 return;
10543 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010544 if (!isEffectEligibleForSuspend(effect->desc())) {
10545 return;
10546 }
Eric Laurent59255e42011-07-27 19:49:51 -070010547 setEffectSuspended_l(&effect->desc().type, enabled);
10548 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010549 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010550 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010551 return;
10552 }
Eric Laurent59255e42011-07-27 19:49:51 -070010553 }
Steve Block3856b092011-10-20 11:56:00 +010010554 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010555 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010556 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10557 // if effect is requested to suspended but was not yet enabled, supend it now.
10558 if (desc->mEffect == 0) {
10559 desc->mEffect = effect;
10560 effect->setEnabled(false);
10561 effect->setSuspended(true);
10562 }
10563 } else {
10564 if (index < 0) {
10565 return;
10566 }
Steve Block3856b092011-10-20 11:56:00 +010010567 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010568 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010569 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10570 desc->mEffect.clear();
10571 effect->setSuspended(false);
10572 }
10573}
10574
Mathias Agopian65ab4712010-07-14 17:59:35 -070010575#undef LOG_TAG
10576#define LOG_TAG "AudioFlinger"
10577
10578// ----------------------------------------------------------------------------
10579
10580status_t AudioFlinger::onTransact(
10581 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10582{
10583 return BnAudioFlinger::onTransact(code, data, reply, flags);
10584}
10585
Mathias Agopian65ab4712010-07-14 17:59:35 -070010586}; // namespace android