blob: 23a04687cbdf3058f0e6fe918d7eef17debc5037 [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());
Mingming Yin9b3dd172013-01-10 18:42:38 -08001194 AudioParameter param = AudioParameter(keyValuePairs);
1195 String8 key = String8(AudioParameter::keyRouting);
1196 int device;
1197 if (param.getInt(key, device) == NO_ERROR) {
1198 if(mLPAEffectChain != NULL){
1199 mLPAEffectChain->setDevice_l(device);
1200 audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1201 }
1202 }
vivek mehta2192bc92012-12-04 11:46:08 -08001203 }
1204 }
1205#endif
1206
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1208 // and the thread is exited once the lock is released
1209 sp<ThreadBase> thread;
1210 {
1211 Mutex::Autolock _l(mLock);
1212 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001213 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001215 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001216 // indicate output device change to all input threads for pre processing
1217 AudioParameter param = AudioParameter(keyValuePairs);
1218 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001219 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1220 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001221 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1222 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001223 for (size_t i = 0; i < recordThreads.size(); i++) {
1224 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001225 }
1226 }
vivek mehta2192bc92012-12-04 11:46:08 -08001227 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 }
vivek mehta2192bc92012-12-04 11:46:08 -08001229 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001231 if (thread != 0) {
1232 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 }
1234 return BAD_VALUE;
1235}
1236
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001237String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001239// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1241
Eric Laurenta4c5a552012-03-29 10:12:40 -07001242 Mutex::Autolock _l(mLock);
1243
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001245 String8 out_s8;
1246
Dima Zavin799a70e2011-04-18 16:57:27 -07001247 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001248 char *s;
1249 {
1250 AutoMutex lock(mHardwareLock);
1251 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001252 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001253 s = dev->get_parameters(dev, keys.string());
1254 mHardwareStatus = AUDIO_HW_IDLE;
1255 }
John Grossmanef7740b2012-02-09 11:28:36 -08001256 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001257 free(s);
1258 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001259 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 }
1261
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1263 if (playbackThread != NULL) {
1264 return playbackThread->getParameters(keys);
1265 }
1266 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1267 if (recordThread != NULL) {
1268 return recordThread->getParameters(keys);
1269 }
1270 return String8("");
1271}
1272
Glenn Kastendd8104c2012-07-02 12:42:44 -07001273size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1274 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275{
Eric Laurenta1884f92011-08-23 08:25:03 -07001276 status_t ret = initCheck();
1277 if (ret != NO_ERROR) {
1278 return 0;
1279 }
1280
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001281 AutoMutex lock(mHardwareLock);
1282 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001283 struct audio_config config = {
1284 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001285 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001286 format: format,
1287 };
John Grossmanee578c02012-07-23 17:05:46 -07001288 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001289#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001290 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001291#else
1292 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1293#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001294 mHardwareStatus = AUDIO_HW_IDLE;
1295 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296}
1297
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001298unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 Mutex::Autolock _l(mLock);
1301
1302 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1303 if (recordThread != NULL) {
1304 return recordThread->getInputFramesLost();
1305 }
1306 return 0;
1307}
1308
1309status_t AudioFlinger::setVoiceVolume(float value)
1310{
Eric Laurenta1884f92011-08-23 08:25:03 -07001311 status_t ret = initCheck();
1312 if (ret != NO_ERROR) {
1313 return ret;
1314 }
1315
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316 // check calling permissions
1317 if (!settingsAllowed()) {
1318 return PERMISSION_DENIED;
1319 }
1320
1321 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001322 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001323 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001324 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 mHardwareStatus = AUDIO_HW_IDLE;
1326
1327 return ret;
1328}
1329
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001330status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1331 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332{
1333 status_t status;
1334
1335 Mutex::Autolock _l(mLock);
1336
1337 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1338 if (playbackThread != NULL) {
1339 return playbackThread->getRenderPosition(halFrames, dspFrames);
1340 }
1341
1342 return BAD_VALUE;
1343}
1344
1345void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1346{
1347
1348 Mutex::Autolock _l(mLock);
1349
vivek mehta2192bc92012-12-04 11:46:08 -08001350 sp<IBinder> binder = client->asBinder();
1351 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352 sp<NotificationClient> notificationClient = new NotificationClient(this,
1353 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001354 binder);
1355 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356
vivek mehta2192bc92012-12-04 11:46:08 -08001357 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358
1359 sp<IBinder> binder = client->asBinder();
1360 binder->linkToDeath(notificationClient);
1361
1362 // the config change is always sent from playback or record threads to avoid deadlock
1363 // with AudioSystem::gLock
1364 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001365 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366 }
1367
1368 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001369 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370 }
1371 }
1372}
1373
vivek mehta2192bc92012-12-04 11:46:08 -08001374#ifdef QCOM_HARDWARE
1375status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1376{
1377 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1378 Mutex::Autolock _l(mLock);
1379
1380 sp<IBinder> binder = client->asBinder();
1381 int index = mNotificationClients.indexOfKey(binder);
1382 if (index >= 0) {
1383 mNotificationClients.removeItemsAt(index);
1384 return true;
1385 }
1386
1387 return false;
1388}
1389#endif
1390
1391void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392{
1393 Mutex::Autolock _l(mLock);
1394
vivek mehta2192bc92012-12-04 11:46:08 -08001395 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001396
vivek mehta2192bc92012-12-04 11:46:08 -08001397 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001398 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001399 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001400 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001401 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001402 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001403 ALOGV(" pid %d @ %d", ref->mPid, i);
1404 if (ref->mPid == pid) {
1405 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001406 mAudioSessionRefs.removeAt(i);
1407 delete ref;
1408 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001409 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001410 } else {
1411 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001412 }
1413 }
1414 if (removed) {
1415 purgeStaleEffects_l();
1416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417}
1418
1419// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001420void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421{
vivek mehta2192bc92012-12-04 11:46:08 -08001422#ifdef QCOM_HARDWARE
1423 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1424 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1425 mIsEffectConfigChanged = true;
1426 }
1427#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 size_t size = mNotificationClients.size();
1429 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001430 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1431 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 }
1433}
1434
1435// removeClient_l() must be called with AudioFlinger::mLock held
1436void AudioFlinger::removeClient_l(pid_t pid)
1437{
Steve Block3856b092011-10-20 11:56:00 +01001438 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 mClients.removeItem(pid);
1440}
1441
Eric Laurent717e1282012-06-29 16:36:52 -07001442// getEffectThread_l() must be called with AudioFlinger::mLock held
1443sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1444{
1445 sp<PlaybackThread> thread;
1446
1447 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1448 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1449 ALOG_ASSERT(thread == 0);
1450 thread = mPlaybackThreads.valueAt(i);
1451 }
1452 }
1453
1454 return thread;
1455}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456
1457// ----------------------------------------------------------------------------
1458
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001459AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001460 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001461 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001462 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001463 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001464 // mChannelMask
1465 mChannelCount(0),
1466 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1467 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001468 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1469 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001470 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001471 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472{
1473}
1474
1475AudioFlinger::ThreadBase::~ThreadBase()
1476{
1477 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001478 // do not lock the mutex in destructor
1479 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001480 if (mPowerManager != 0) {
1481 sp<IBinder> binder = mPowerManager->asBinder();
1482 binder->unlinkToDeath(mDeathRecipient);
1483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484}
1485
1486void AudioFlinger::ThreadBase::exit()
1487{
Steve Block3856b092011-10-20 11:56:00 +01001488 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001489 // do any cleanup required for exit to succeed
1490 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001492 // This lock prevents the following race in thread (uniprocessor for illustration):
1493 // if (!exitPending()) {
1494 // // context switch from here to exit()
1495 // // exit() calls requestExit(), what exitPending() observes
1496 // // exit() calls signal(), which is dropped since no waiters
1497 // // context switch back from exit() to here
1498 // mWaitWorkCV.wait(...);
1499 // // now thread is hung
1500 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001501 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001503 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001505 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1506 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 requestExitAndWait();
1508}
1509
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1511{
1512 status_t status;
1513
Steve Block3856b092011-10-20 11:56:00 +01001514 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 Mutex::Autolock _l(mLock);
1516
1517 mNewParameters.add(keyValuePairs);
1518 mWaitWorkCV.signal();
1519 // wait condition with timeout in case the thread loop has exited
1520 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001521 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 status = mParamStatus;
1523 mWaitWorkCV.signal();
1524 } else {
1525 status = TIMED_OUT;
1526 }
1527 return status;
1528}
1529
vivek mehta2192bc92012-12-04 11:46:08 -08001530#ifdef QCOM_HARDWARE
1531void AudioFlinger::ThreadBase::effectConfigChanged() {
1532 mAudioFlinger->mLock.lock();
1533 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1534 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1535 mAudioFlinger->mLock.unlock();
1536}
1537#endif
1538
Eric Laurent896adcd2012-09-13 11:18:23 -07001539void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540{
1541 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001542 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543}
1544
Eric Laurent896adcd2012-09-13 11:18:23 -07001545// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1546void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547{
Eric Laurent896adcd2012-09-13 11:18:23 -07001548 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1549 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1550 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1551 mWaitWorkCV.signal();
1552}
1553
1554// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1555void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1556{
1557 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1558 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1559 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1560 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 mWaitWorkCV.signal();
1562}
1563
1564void AudioFlinger::ThreadBase::processConfigEvents()
1565{
1566 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001567 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001568 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001569 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 mConfigEvents.removeAt(0);
1571 // release mLock before locking AudioFlinger mLock: lock order is always
1572 // AudioFlinger then ThreadBase to avoid cross deadlock
1573 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001574 switch(event->type()) {
1575 case CFG_EVENT_PRIO: {
1576 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1577 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1578 if (err != 0) {
1579 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1580 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1581 }
1582 } break;
1583 case CFG_EVENT_IO: {
1584 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1585 mAudioFlinger->mLock.lock();
1586 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1587 mAudioFlinger->mLock.unlock();
1588 } break;
1589 default:
1590 ALOGE("processConfigEvents() unknown event type %d", event->type());
1591 break;
1592 }
1593 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 mLock.lock();
1595 }
1596 mLock.unlock();
1597}
1598
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001599void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600{
1601 const size_t SIZE = 256;
1602 char buffer[SIZE];
1603 String8 result;
1604
1605 bool locked = tryLock(mLock);
1606 if (!locked) {
1607 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1608 write(fd, buffer, strlen(buffer));
1609 }
1610
Eric Laurent612bbb52012-03-14 15:03:26 -07001611 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1612 result.append(buffer);
1613 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1614 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1616 result.append(buffer);
1617 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1618 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001619 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1620 result.append(buffer);
1621 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 result.append(buffer);
1623 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1624 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001625 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1626 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1628 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001629 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 result.append(buffer);
1631
1632 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1633 result.append(buffer);
1634 result.append(" Index Command");
1635 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1636 snprintf(buffer, SIZE, "\n %02d ", i);
1637 result.append(buffer);
1638 result.append(mNewParameters[i]);
1639 }
1640
1641 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1642 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001644 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 result.append(buffer);
1646 }
1647 result.append("\n");
1648
1649 write(fd, result.string(), result.size());
1650
1651 if (locked) {
1652 mLock.unlock();
1653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654}
1655
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001656void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001657{
1658 const size_t SIZE = 256;
1659 char buffer[SIZE];
1660 String8 result;
1661
1662 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1663 write(fd, buffer, strlen(buffer));
1664
1665 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1666 sp<EffectChain> chain = mEffectChains[i];
1667 if (chain != 0) {
1668 chain->dump(fd, args);
1669 }
1670 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001671}
1672
Eric Laurentfeb0db62011-07-22 09:04:31 -07001673void AudioFlinger::ThreadBase::acquireWakeLock()
1674{
1675 Mutex::Autolock _l(mLock);
1676 acquireWakeLock_l();
1677}
1678
1679void AudioFlinger::ThreadBase::acquireWakeLock_l()
1680{
1681 if (mPowerManager == 0) {
1682 // use checkService() to avoid blocking if power service is not up yet
1683 sp<IBinder> binder =
1684 defaultServiceManager()->checkService(String16("power"));
1685 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001686 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001687 } else {
1688 mPowerManager = interface_cast<IPowerManager>(binder);
1689 binder->linkToDeath(mDeathRecipient);
1690 }
1691 }
1692 if (mPowerManager != 0) {
1693 sp<IBinder> binder = new BBinder();
1694 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1695 binder,
1696 String16(mName));
1697 if (status == NO_ERROR) {
1698 mWakeLockToken = binder;
1699 }
Steve Block3856b092011-10-20 11:56:00 +01001700 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001701 }
1702}
1703
1704void AudioFlinger::ThreadBase::releaseWakeLock()
1705{
1706 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001707 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001708}
1709
1710void AudioFlinger::ThreadBase::releaseWakeLock_l()
1711{
1712 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001713 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001714 if (mPowerManager != 0) {
1715 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1716 }
1717 mWakeLockToken.clear();
1718 }
1719}
1720
1721void AudioFlinger::ThreadBase::clearPowerManager()
1722{
1723 Mutex::Autolock _l(mLock);
1724 releaseWakeLock_l();
1725 mPowerManager.clear();
1726}
1727
1728void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1729{
1730 sp<ThreadBase> thread = mThread.promote();
1731 if (thread != 0) {
1732 thread->clearPowerManager();
1733 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001734 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001735}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001736
Eric Laurent59255e42011-07-27 19:49:51 -07001737void AudioFlinger::ThreadBase::setEffectSuspended(
1738 const effect_uuid_t *type, bool suspend, int sessionId)
1739{
1740 Mutex::Autolock _l(mLock);
1741 setEffectSuspended_l(type, suspend, sessionId);
1742}
1743
1744void AudioFlinger::ThreadBase::setEffectSuspended_l(
1745 const effect_uuid_t *type, bool suspend, int sessionId)
1746{
Glenn Kasten090f0192012-01-30 13:00:02 -08001747 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001748 if (chain != 0) {
1749 if (type != NULL) {
1750 chain->setEffectSuspended_l(type, suspend);
1751 } else {
1752 chain->setEffectSuspendedAll_l(suspend);
1753 }
1754 }
1755
1756 updateSuspendedSessions_l(type, suspend, sessionId);
1757}
1758
1759void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1760{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001761 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001762 if (index < 0) {
1763 return;
1764 }
1765
Glenn Kasten0a7af182012-07-09 16:09:19 -07001766 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1767 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001768
1769 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001770 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001771 for (int j = 0; j < desc->mRefCount; j++) {
1772 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1773 chain->setEffectSuspendedAll_l(true);
1774 } else {
Steve Block3856b092011-10-20 11:56:00 +01001775 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001776 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001777 chain->setEffectSuspended_l(&desc->mType, true);
1778 }
1779 }
1780 }
1781}
1782
Eric Laurent59255e42011-07-27 19:49:51 -07001783void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1784 bool suspend,
1785 int sessionId)
1786{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001787 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001788
1789 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1790
1791 if (suspend) {
1792 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001793 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001794 } else {
1795 mSuspendedSessions.add(sessionId, sessionEffects);
1796 }
1797 } else {
1798 if (index < 0) {
1799 return;
1800 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001801 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001802 }
1803
1804
1805 int key = EffectChain::kKeyForSuspendAll;
1806 if (type != NULL) {
1807 key = type->timeLow;
1808 }
1809 index = sessionEffects.indexOfKey(key);
1810
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001811 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001812 if (suspend) {
1813 if (index >= 0) {
1814 desc = sessionEffects.valueAt(index);
1815 } else {
1816 desc = new SuspendedSessionDesc();
1817 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001818 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001819 }
1820 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001821 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001822 }
1823 desc->mRefCount++;
1824 } else {
1825 if (index < 0) {
1826 return;
1827 }
1828 desc = sessionEffects.valueAt(index);
1829 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001830 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001831 sessionEffects.removeItemsAt(index);
1832 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001833 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001834 sessionId);
1835 mSuspendedSessions.removeItem(sessionId);
1836 }
1837 }
1838 }
1839 if (!sessionEffects.isEmpty()) {
1840 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1841 }
1842}
1843
1844void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1845 bool enabled,
1846 int sessionId)
1847{
1848 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001849 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1850}
Eric Laurent59255e42011-07-27 19:49:51 -07001851
Eric Laurenta85a74a2011-10-19 11:44:54 -07001852void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1853 bool enabled,
1854 int sessionId)
1855{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001856 if (mType != RECORD) {
1857 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1858 // another session. This gives the priority to well behaved effect control panels
1859 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001860 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1861 // global effects
1862 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001863 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1864 }
1865 }
Eric Laurent59255e42011-07-27 19:49:51 -07001866
1867 sp<EffectChain> chain = getEffectChain_l(sessionId);
1868 if (chain != 0) {
1869 chain->checkSuspendOnEffectEnabled(effect, enabled);
1870 }
1871}
1872
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873// ----------------------------------------------------------------------------
1874
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001875AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1876 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001877 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001878 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001879 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001880 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001881 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001882 // mStreamTypes[] initialized in constructor body
1883 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001884 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001885 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001886 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001887 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001888 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001889 // index 0 is reserved for normal mixer's submix
1890 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891{
Glenn Kasten480b4682012-02-28 12:30:08 -08001892 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001893
John Grossmanee578c02012-07-23 17:05:46 -07001894 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1895 // it would be safer to explicitly pass initial masterVolume/masterMute as
1896 // parameter.
1897 //
1898 // If the HAL we are using has support for master volume or master mute,
1899 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1900 // and the mute set to false).
1901 mMasterVolume = audioFlinger->masterVolume_l();
1902 mMasterMute = audioFlinger->masterMute_l();
1903 if (mOutput && mOutput->audioHwDev) {
1904 if (mOutput->audioHwDev->canSetMasterVolume()) {
1905 mMasterVolume = 1.0;
1906 }
1907
1908 if (mOutput->audioHwDev->canSetMasterMute()) {
1909 mMasterMute = false;
1910 }
1911 }
1912
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 readOutputParameters();
1914
Glenn Kasten263709e2012-01-06 08:40:01 -08001915 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001916 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1917 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1918 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001919 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1920 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1923 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924}
1925
1926AudioFlinger::PlaybackThread::~PlaybackThread()
1927{
1928 delete [] mMixBuffer;
1929}
1930
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001931void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932{
1933 dumpInternals(fd, args);
1934 dumpTracks(fd, args);
1935 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936}
1937
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001938void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939{
1940 const size_t SIZE = 256;
1941 char buffer[SIZE];
1942 String8 result;
1943
Glenn Kasten58912562012-04-03 10:45:00 -07001944 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1945 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1946 const stream_type_t *st = &mStreamTypes[i];
1947 if (i > 0) {
1948 result.appendFormat(", ");
1949 }
1950 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1951 if (st->mute) {
1952 result.append("M");
1953 }
1954 }
1955 result.append("\n");
1956 write(fd, result.string(), result.length());
1957 result.clear();
1958
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1960 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001961 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 for (size_t i = 0; i < mTracks.size(); ++i) {
1963 sp<Track> track = mTracks[i];
1964 if (track != 0) {
1965 track->dump(buffer, SIZE);
1966 result.append(buffer);
1967 }
1968 }
1969
1970 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1971 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001972 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001974 sp<Track> track = mActiveTracks[i].promote();
1975 if (track != 0) {
1976 track->dump(buffer, SIZE);
1977 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 }
1979 }
1980 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001981
1982 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1983 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1984 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1985 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986}
1987
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001988void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989{
1990 const size_t SIZE = 256;
1991 char buffer[SIZE];
1992 String8 result;
1993
1994 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1995 result.append(buffer);
1996 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1997 result.append(buffer);
1998 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1999 result.append(buffer);
2000 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
2001 result.append(buffer);
2002 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
2003 result.append(buffer);
2004 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
2005 result.append(buffer);
2006 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
2007 result.append(buffer);
2008 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002009 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
2011 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012}
2013
2014// Thread virtuals
2015status_t AudioFlinger::PlaybackThread::readyToRun()
2016{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002017 status_t status = initCheck();
2018 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002019 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002020 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002021 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002023 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024}
2025
2026void AudioFlinger::PlaybackThread::onFirstRef()
2027{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002028 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029}
2030
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002031// ThreadBase virtuals
2032void AudioFlinger::PlaybackThread::preExit()
2033{
2034 ALOGV(" preExit()");
2035 // FIXME this is using hard-coded strings but in the future, this functionality will be
2036 // converted to use audio HAL extensions required to support tunneling
2037 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2038}
2039
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002041sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002043 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002045 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002046 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 int frameCount,
2048 const sp<IMemory>& sharedBuffer,
2049 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002050 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002051 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 status_t *status)
2053{
2054 sp<Track> track;
2055 status_t lStatus;
2056
Glenn Kasten73d22752012-03-19 13:38:30 -07002057 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2058
2059 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002060 if (flags & IAudioFlinger::TRACK_FAST) {
2061 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002062 // not timed
2063 (!isTimed) &&
2064 // either of these use cases:
2065 (
2066 // use case 1: shared buffer with any frame count
2067 (
2068 (sharedBuffer != 0)
2069 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002070 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002071 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002072 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002073 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002074 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002075 )
2076 ) &&
2077 // PCM data
2078 audio_is_linear_pcm(format) &&
2079 // mono or stereo
2080 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2081 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002082#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002083 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002084 (sampleRate == mSampleRate) &&
2085#endif
2086 // normal mixer has an associated fast mixer
2087 hasFastMixer() &&
2088 // there are sufficient fast track slots available
2089 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002090 // FIXME test that MixerThread for this fast track has a capable output HAL
2091 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002092 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002093 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2094 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002095 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002096 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002097 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002098 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002099 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002100 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002101 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002102 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2103 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2104 audio_is_linear_pcm(format),
2105 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002106 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002107 // For compatibility with AudioTrack calculation, buffer depth is forced
2108 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2109 // This is probably too conservative, but legacy application code may depend on it.
2110 // If you change this calculation, also review the start threshold which is related.
2111 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2112 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2113 if (minBufCount < 2) {
2114 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002115 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002116 int minFrameCount = mNormalFrameCount * minBufCount;
2117 if (frameCount < minFrameCount) {
2118 frameCount = minFrameCount;
2119 }
2120 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002121 }
2122
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002124 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2125 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002126 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002127 "for output %p with format %d",
2128 sampleRate, format, channelMask, mOutput, mFormat);
2129 lStatus = BAD_VALUE;
2130 goto Exit;
2131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 }
2133 } else {
2134 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2135 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002136 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 lStatus = BAD_VALUE;
2138 goto Exit;
2139 }
2140 }
2141
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002142 lStatus = initCheck();
2143 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002144 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 goto Exit;
2146 }
2147
2148 { // scope for mLock
2149 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002150
2151 // all tracks in same audio session must share the same routing strategy otherwise
2152 // conflicts will happen when tracks are moved from one output to another by audio policy
2153 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002154 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002155 for (size_t i = 0; i < mTracks.size(); ++i) {
2156 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002157 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002158 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002159 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002160 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002161 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002162 lStatus = BAD_VALUE;
2163 goto Exit;
2164 }
2165 }
2166 }
2167
John Grossman4ff14ba2012-02-08 16:37:41 -08002168 if (!isTimed) {
2169 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002170 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002171 } else {
2172 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2173 channelMask, frameCount, sharedBuffer, sessionId);
2174 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002175 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 lStatus = NO_MEMORY;
2177 goto Exit;
2178 }
2179 mTracks.add(track);
2180
2181 sp<EffectChain> chain = getEffectChain_l(sessionId);
2182 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002183 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002185 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002186 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002188
Eric Laurent896adcd2012-09-13 11:18:23 -07002189 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2190 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2191 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2192 // so ask activity manager to do this on our behalf
2193 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002194 }
2195 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002196
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 lStatus = NO_ERROR;
2198
2199Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002200 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 *status = lStatus;
2202 }
2203 return track;
2204}
2205
Eric Laurente737cda2012-05-22 18:55:44 -07002206uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2207{
2208 if (mFastMixer != NULL) {
2209 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2210 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2211 }
2212 return latency;
2213}
2214
2215uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2216{
2217 return latency;
2218}
2219
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220uint32_t AudioFlinger::PlaybackThread::latency() const
2221{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002222 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002223 return latency_l();
2224}
2225uint32_t AudioFlinger::PlaybackThread::latency_l() const
2226{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002227 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002228 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002229 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 return 0;
2231 }
2232}
2233
Glenn Kasten6637baa2012-01-09 09:40:36 -08002234void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002236 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002237 // Don't apply master volume in SW if our HAL can do it for us.
2238 if (mOutput && mOutput->audioHwDev &&
2239 mOutput->audioHwDev->canSetMasterVolume()) {
2240 mMasterVolume = 1.0;
2241 } else {
2242 mMasterVolume = value;
2243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244}
2245
Glenn Kasten6637baa2012-01-09 09:40:36 -08002246void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002248 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002249 // Don't apply master mute in SW if our HAL can do it for us.
2250 if (mOutput && mOutput->audioHwDev &&
2251 mOutput->audioHwDev->canSetMasterMute()) {
2252 mMasterMute = false;
2253 } else {
2254 mMasterMute = muted;
2255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256}
2257
Glenn Kasten6637baa2012-01-09 09:40:36 -08002258void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002260 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262}
2263
Glenn Kasten6637baa2012-01-09 09:40:36 -08002264void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002266 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268}
2269
Glenn Kastenfff6d712012-01-12 16:38:12 -08002270float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002272 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 return mStreamTypes[stream].volume;
2274}
2275
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276// addTrack_l() must be called with ThreadBase::mLock held
2277status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2278{
2279 status_t status = ALREADY_EXISTS;
2280
2281 // set retry count for buffer fill
2282 track->mRetryCount = kMaxTrackStartupRetries;
2283 if (mActiveTracks.indexOf(track) < 0) {
2284 // the track is newly added, make sure it fills up all its
2285 // buffers before playing. This is to ensure the client will
2286 // effectively get the latency it requested.
2287 track->mFillingUpStatus = Track::FS_FILLING;
2288 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002289 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 mActiveTracks.add(track);
2291 if (track->mainBuffer() != mMixBuffer) {
2292 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2293 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002295 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 }
2297 }
2298
2299 status = NO_ERROR;
2300 }
2301
Steve Block3856b092011-10-20 11:56:00 +01002302 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 mWaitWorkCV.broadcast();
2304
2305 return status;
2306}
2307
2308// destroyTrack_l() must be called with ThreadBase::mLock held
2309void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2310{
2311 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002312 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002314 removeTrack_l(track);
2315 }
2316}
2317
2318void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2319{
Eric Laurent29864602012-05-08 18:57:51 -07002320 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002321 mTracks.remove(track);
2322 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002323 // redundant as track is about to be destroyed, for dumpsys only
2324 track->mName = -1;
2325 if (track->isFastTrack()) {
2326 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002327 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002328 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2329 mFastTrackAvailMask |= 1 << index;
2330 // redundant as track is about to be destroyed, for dumpsys only
2331 track->mFastIndex = -1;
2332 }
Eric Laurentb469b942011-05-09 12:09:06 -07002333 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2334 if (chain != 0) {
2335 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
2337}
2338
2339String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2340{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002341 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002342 char *s;
2343
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002344 Mutex::Autolock _l(mLock);
2345 if (initCheck() != NO_ERROR) {
2346 return out_s8;
2347 }
2348
Dima Zavin799a70e2011-04-18 16:57:27 -07002349 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002350 out_s8 = String8(s);
2351 free(s);
2352 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353}
2354
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002355// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2357 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002358 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359
Steve Block3856b092011-10-20 11:56:00 +01002360 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361
2362 switch (event) {
2363 case AudioSystem::OUTPUT_OPENED:
2364 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002365 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366 desc.samplingRate = mSampleRate;
2367 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002368 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 desc.latency = latency();
2370 param2 = &desc;
2371 break;
2372
2373 case AudioSystem::STREAM_CONFIG_CHANGED:
2374 param2 = &param;
2375 case AudioSystem::OUTPUT_CLOSED:
2376 default:
2377 break;
2378 }
2379 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2380}
2381
2382void AudioFlinger::PlaybackThread::readOutputParameters()
2383{
Dima Zavin799a70e2011-04-18 16:57:27 -07002384 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002385 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2386 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002387 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002388 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002389 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002390 if (mFrameCount & 15) {
2391 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2392 mFrameCount);
2393 }
2394
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002395 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002396 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002397 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002398 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002399 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2400 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2401 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2402 maxNormalFrameCount = maxNormalFrameCount & ~15;
2403 if (maxNormalFrameCount < minNormalFrameCount) {
2404 maxNormalFrameCount = minNormalFrameCount;
2405 }
2406 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2407 if (multiplier <= 1.0) {
2408 multiplier = 1.0;
2409 } else if (multiplier <= 2.0) {
2410 if (2 * mFrameCount <= maxNormalFrameCount) {
2411 multiplier = 2.0;
2412 } else {
2413 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2414 }
2415 } else {
2416 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2417 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2418 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2419 // FIXME this rounding up should not be done if no HAL SRC
2420 uint32_t truncMult = (uint32_t) multiplier;
2421 if ((truncMult & 1)) {
2422 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2423 ++truncMult;
2424 }
2425 }
2426 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002427 }
Glenn Kasten58912562012-04-03 10:45:00 -07002428 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002429 mNormalFrameCount = multiplier * mFrameCount;
2430 // round up to nearest 16 frames to satisfy AudioMixer
2431 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002432 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433
Glenn Kastene9dd0172012-01-27 18:08:45 -08002434 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002435 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2436 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437
Eric Laurentde070132010-07-13 04:45:46 -07002438 // force reconfiguration of effect chains and engines to take new buffer size and audio
2439 // parameters into account
2440 // Note that mLock is not held when readOutputParameters() is called from the constructor
2441 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2442 // matter.
2443 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2444 Vector< sp<EffectChain> > effectChains = mEffectChains;
2445 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002446 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002447 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448}
2449
Eric Laurente737cda2012-05-22 18:55:44 -07002450
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2452{
Glenn Kastena0d68332012-01-27 16:47:15 -08002453 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 return BAD_VALUE;
2455 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002456 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002457 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 return INVALID_OPERATION;
2459 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002460 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461
Eric Laurent1afc26d2012-09-23 15:20:50 -07002462 if (isSuspended()) {
2463 // return an estimation of rendered frames when the output is suspended
2464 int32_t frames = mBytesWritten - latency_l();
2465 if (frames < 0) {
2466 frames = 0;
2467 }
2468 *dspFrames = (uint32_t)frames;
2469 return NO_ERROR;
2470 } else {
2471 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473}
2474
Glenn Kasten106e8a42012-08-02 13:37:12 -07002475uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476{
2477 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002478 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002480 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
2482
2483 for (size_t i = 0; i < mTracks.size(); ++i) {
2484 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002485 if (sessionId == track->sessionId() &&
2486 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002487 result |= TRACK_SESSION;
2488 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489 }
2490 }
2491
Eric Laurent39e94f82010-07-28 01:32:47 -07002492 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493}
2494
Eric Laurentde070132010-07-13 04:45:46 -07002495uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2496{
Dima Zavinfce7a472011-04-19 22:30:36 -07002497 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002498 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2500 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002501 }
2502 for (size_t i = 0; i < mTracks.size(); i++) {
2503 sp<Track> track = mTracks[i];
2504 if (sessionId == track->sessionId() &&
2505 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002506 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002507 }
2508 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002509 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002510}
2511
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512
Glenn Kastenaed850d2012-01-26 09:46:34 -08002513AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002514{
2515 Mutex::Autolock _l(mLock);
2516 return mOutput;
2517}
2518
2519AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2520{
2521 Mutex::Autolock _l(mLock);
2522 AudioStreamOut *output = mOutput;
2523 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002524 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2525 // must push a NULL and wait for ack
2526 mOutputSink.clear();
2527 mPipeSink.clear();
2528 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002529 return output;
2530}
2531
2532// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002533audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002534{
2535 if (mOutput == NULL) {
2536 return NULL;
2537 }
2538 return &mOutput->stream->common;
2539}
2540
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002541uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002542{
Eric Laurentab9071b2012-06-04 13:45:29 -07002543 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002544}
2545
Eric Laurenta011e352012-03-29 15:51:43 -07002546status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2547{
2548 if (!isValidSyncEvent(event)) {
2549 return BAD_VALUE;
2550 }
2551
2552 Mutex::Autolock _l(mLock);
2553
2554 for (size_t i = 0; i < mTracks.size(); ++i) {
2555 sp<Track> track = mTracks[i];
2556 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002557 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002558 return NO_ERROR;
2559 }
2560 }
2561
2562 return NAME_NOT_FOUND;
2563}
2564
Glenn Kasten106e8a42012-08-02 13:37:12 -07002565bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002566{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002567 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002568}
2569
Eric Laurent44a957f2012-05-15 15:26:05 -07002570void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2571{
2572 size_t count = tracksToRemove.size();
2573 if (CC_UNLIKELY(count)) {
2574 for (size_t i = 0 ; i < count ; i++) {
2575 const sp<Track>& track = tracksToRemove.itemAt(i);
2576 if ((track->sharedBuffer() != 0) &&
2577 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2578 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2579 }
2580 }
2581 }
2582
2583}
2584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585// ----------------------------------------------------------------------------
2586
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002587AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002588 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002589 : PlaybackThread(audioFlinger, output, id, device, type),
2590 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002591 // mFastMixer below
2592 mFastMixerFutex(0)
2593 // mOutputSink below
2594 // mPipeSink below
2595 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002597 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002598 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002599 "mFrameCount=%d, mNormalFrameCount=%d",
2600 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2601 mNormalFrameCount);
2602 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002605 if (mChannelCount != FCC_2) {
2606 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 }
Glenn Kasten58912562012-04-03 10:45:00 -07002608
2609 // create an NBAIO sink for the HAL output stream, and negotiate
2610 mOutputSink = new AudioStreamOutSink(output->stream);
2611 size_t numCounterOffers = 0;
2612 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2613 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2614 ALOG_ASSERT(index == 0);
2615
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002616 // initialize fast mixer depending on configuration
2617 bool initFastMixer;
2618 switch (kUseFastMixer) {
2619 case FastMixer_Never:
2620 initFastMixer = false;
2621 break;
2622 case FastMixer_Always:
2623 initFastMixer = true;
2624 break;
2625 case FastMixer_Static:
2626 case FastMixer_Dynamic:
2627 initFastMixer = mFrameCount < mNormalFrameCount;
2628 break;
2629 }
2630 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002631
2632 // create a MonoPipe to connect our submix to FastMixer
2633 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002634 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2635 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2636 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2637 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002638 const NBAIO_Format offers[1] = {format};
2639 size_t numCounterOffers = 0;
2640 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2641 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002642 monoPipe->setAvgFrames((mScreenState & 1) ?
2643 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002644 mPipeSink = monoPipe;
2645
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002646#ifdef TEE_SINK_FRAMES
2647 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2648 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2649 numCounterOffers = 0;
2650 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2651 ALOG_ASSERT(index == 0);
2652 mTeeSink = teeSink;
2653 PipeReader *teeSource = new PipeReader(*teeSink);
2654 numCounterOffers = 0;
2655 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2656 ALOG_ASSERT(index == 0);
2657 mTeeSource = teeSource;
2658#endif
2659
Glenn Kasten58912562012-04-03 10:45:00 -07002660 // create fast mixer and configure it initially with just one fast track for our submix
2661 mFastMixer = new FastMixer();
2662 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002663#ifdef STATE_QUEUE_DUMP
2664 sq->setObserverDump(&mStateQueueObserverDump);
2665 sq->setMutatorDump(&mStateQueueMutatorDump);
2666#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002667 FastMixerState *state = sq->begin();
2668 FastTrack *fastTrack = &state->mFastTracks[0];
2669 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2670 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2671 fastTrack->mVolumeProvider = NULL;
2672 fastTrack->mGeneration++;
2673 state->mFastTracksGen++;
2674 state->mTrackMask = 1;
2675 // fast mixer will use the HAL output sink
2676 state->mOutputSink = mOutputSink.get();
2677 state->mOutputSinkGen++;
2678 state->mFrameCount = mFrameCount;
2679 state->mCommand = FastMixerState::COLD_IDLE;
2680 // already done in constructor initialization list
2681 //mFastMixerFutex = 0;
2682 state->mColdFutexAddr = &mFastMixerFutex;
2683 state->mColdGen++;
2684 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002685 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002686 sq->end();
2687 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2688
2689 // start the fast mixer
2690 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002691 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002692 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002693 if (err != 0) {
2694 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002695 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002696 }
Glenn Kasten58912562012-04-03 10:45:00 -07002697
Glenn Kastenc15d6652012-05-30 14:52:57 -07002698#ifdef AUDIO_WATCHDOG
2699 // create and start the watchdog
2700 mAudioWatchdog = new AudioWatchdog();
2701 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2702 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2703 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002704 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002705 if (err != 0) {
2706 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002707 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002708 }
2709#endif
2710
Glenn Kasten58912562012-04-03 10:45:00 -07002711 } else {
2712 mFastMixer = NULL;
2713 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002714
2715 switch (kUseFastMixer) {
2716 case FastMixer_Never:
2717 case FastMixer_Dynamic:
2718 mNormalSink = mOutputSink;
2719 break;
2720 case FastMixer_Always:
2721 mNormalSink = mPipeSink;
2722 break;
2723 case FastMixer_Static:
2724 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2725 break;
2726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727}
2728
2729AudioFlinger::MixerThread::~MixerThread()
2730{
Glenn Kasten58912562012-04-03 10:45:00 -07002731 if (mFastMixer != NULL) {
2732 FastMixerStateQueue *sq = mFastMixer->sq();
2733 FastMixerState *state = sq->begin();
2734 if (state->mCommand == FastMixerState::COLD_IDLE) {
2735 int32_t old = android_atomic_inc(&mFastMixerFutex);
2736 if (old == -1) {
2737 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2738 }
2739 }
2740 state->mCommand = FastMixerState::EXIT;
2741 sq->end();
2742 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2743 mFastMixer->join();
2744 // Though the fast mixer thread has exited, it's state queue is still valid.
2745 // We'll use that extract the final state which contains one remaining fast track
2746 // corresponding to our sub-mix.
2747 state = sq->begin();
2748 ALOG_ASSERT(state->mTrackMask == 1);
2749 FastTrack *fastTrack = &state->mFastTracks[0];
2750 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2751 delete fastTrack->mBufferProvider;
2752 sq->end(false /*didModify*/);
2753 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002754#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002755 if (mAudioWatchdog != 0) {
2756 mAudioWatchdog->requestExit();
2757 mAudioWatchdog->requestExitAndWait();
2758 mAudioWatchdog.clear();
2759 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002760#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762 delete mAudioMixer;
2763}
2764
Glenn Kasten83efdd02012-02-24 07:21:32 -08002765class CpuStats {
2766public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002767 CpuStats();
2768 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002769#ifdef DEBUG_CPU_USAGE
2770private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002771 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2772 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2773
2774 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2775
2776 int mCpuNum; // thread's current CPU number
2777 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002778#endif
2779};
2780
Glenn Kasten190a46f2012-03-06 11:27:10 -08002781CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002782#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002783 : mCpuNum(-1), mCpukHz(-1)
2784#endif
2785{
2786}
2787
2788void CpuStats::sample(const String8 &title) {
2789#ifdef DEBUG_CPU_USAGE
2790 // get current thread's delta CPU time in wall clock ns
2791 double wcNs;
2792 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2793
2794 // record sample for wall clock statistics
2795 if (valid) {
2796 mWcStats.sample(wcNs);
2797 }
2798
2799 // get the current CPU number
2800 int cpuNum = sched_getcpu();
2801
2802 // get the current CPU frequency in kHz
2803 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2804
2805 // check if either CPU number or frequency changed
2806 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2807 mCpuNum = cpuNum;
2808 mCpukHz = cpukHz;
2809 // ignore sample for purposes of cycles
2810 valid = false;
2811 }
2812
2813 // if no change in CPU number or frequency, then record sample for cycle statistics
2814 if (valid && mCpukHz > 0) {
2815 double cycles = wcNs * cpukHz * 0.000001;
2816 mHzStats.sample(cycles);
2817 }
2818
2819 unsigned n = mWcStats.n();
2820 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002821 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002822 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002823 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2824 double perLoop = elapsed / (double) n;
2825 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002826 double perLoop1k = perLoop * 0.001;
2827 double mean = mWcStats.mean();
2828 double stddev = mWcStats.stddev();
2829 double minimum = mWcStats.minimum();
2830 double maximum = mWcStats.maximum();
2831 double meanCycles = mHzStats.mean();
2832 double stddevCycles = mHzStats.stddev();
2833 double minCycles = mHzStats.minimum();
2834 double maxCycles = mHzStats.maximum();
2835 mCpuUsage.resetElapsed();
2836 mWcStats.reset();
2837 mHzStats.reset();
2838 ALOGD("CPU usage for %s over past %.1f secs\n"
2839 " (%u mixer loops at %.1f mean ms per loop):\n"
2840 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2841 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2842 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2843 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002844 elapsed * .000000001, n, perLoop * .000001,
2845 mean * .001,
2846 stddev * .001,
2847 minimum * .001,
2848 maximum * .001,
2849 mean / perLoop100,
2850 stddev / perLoop100,
2851 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002852 maximum / perLoop100,
2853 meanCycles / perLoop1k,
2854 stddevCycles / perLoop1k,
2855 minCycles / perLoop1k,
2856 maxCycles / perLoop1k);
2857
Glenn Kasten83efdd02012-02-24 07:21:32 -08002858 }
2859 }
2860#endif
2861};
2862
Glenn Kasten37d825e2012-02-24 07:21:48 -08002863void AudioFlinger::PlaybackThread::checkSilentMode_l()
2864{
2865 if (!mMasterMute) {
2866 char value[PROPERTY_VALUE_MAX];
2867 if (property_get("ro.audio.silent", value, "0") > 0) {
2868 char *endptr;
2869 unsigned long ul = strtoul(value, &endptr, 0);
2870 if (*endptr == '\0' && ul != 0) {
2871 ALOGD("Silence is golden");
2872 // The setprop command will not allow a property to be changed after
2873 // the first time it is set, so we don't have to worry about un-muting.
2874 setMasterMute_l(true);
2875 }
2876 }
2877 }
2878}
2879
Glenn Kasten000f0e32012-03-01 17:10:56 -08002880bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881{
2882 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002883
Glenn Kasten000f0e32012-03-01 17:10:56 -08002884 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002885
2886 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002888
Glenn Kasten000f0e32012-03-01 17:10:56 -08002889 // DUPLICATING
2890 // FIXME could this be made local to while loop?
2891 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002892
Glenn Kasten66fcab92012-02-24 14:59:21 -08002893 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002894 sleepTime = idleSleepTime;
2895
Glenn Kasten9f34a362012-03-20 16:46:41 -07002896 if (mType == MIXER) {
2897 sleepTimeShift = 0;
2898 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002899
Glenn Kasten83efdd02012-02-24 07:21:32 -08002900 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002901 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902
Eric Laurentfeb0db62011-07-22 09:04:31 -07002903 acquireWakeLock();
2904
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 while (!exitPending())
2906 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002907 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002908
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002909 Vector< sp<EffectChain> > effectChains;
2910
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 processConfigEvents();
2912
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 { // scope for mLock
2914
2915 Mutex::Autolock _l(mLock);
2916
2917 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002918 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 }
2920
Glenn Kastenfa26a852012-03-06 11:28:04 -08002921 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002922
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002924 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002925 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002927
2928 threadLoop_standby();
2929
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 }
2932
Glenn Kasten3e074702012-02-28 18:40:35 -08002933 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 // we're about to wait, flush the binder command buffer
2935 IPCThreadState::self()->flushCommands();
2936
Glenn Kastenfa26a852012-03-06 11:28:04 -08002937 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002938
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 if (exitPending()) break;
2940
Eric Laurentfeb0db62011-07-22 09:04:31 -07002941 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002943 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002945 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002946 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947
Eric Laurentda747442012-04-25 18:53:13 -07002948 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002949 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002950 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002951
Glenn Kasten37d825e2012-02-24 07:21:48 -08002952 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953
Glenn Kasten000f0e32012-03-01 17:10:56 -08002954 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002956 if (mType == MIXER) {
2957 sleepTimeShift = 0;
2958 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002959
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 continue;
2961 }
2962 }
2963
Glenn Kasten81028042012-04-30 18:15:12 -07002964 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002965 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966
2967 // prevent any changes in effect chain list and in each effect chain
2968 // during mixing and effect process as the audio buffers could be deleted
2969 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002970 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972
Glenn Kastenfec279f2012-03-08 07:47:15 -08002973 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002974 threadLoop_mix();
2975 } else {
2976 threadLoop_sleepTime();
2977 }
2978
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002979 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002980 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002981 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002982 }
2983
2984 // only process effects if we're going to write
2985 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002986 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08002987#ifdef QCOM_HARDWARE
2988 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
2989#endif
2990 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002991 }
2992 }
2993
2994 // enable changes in effect chain
2995 unlockEffectChains(effectChains);
2996
2997 // sleepTime == 0 means we must write to audio hardware
2998 if (sleepTime == 0) {
2999
3000 threadLoop_write();
3001
3002if (mType == MIXER) {
3003 // write blocked detection
3004 nsecs_t now = systemTime();
3005 nsecs_t delta = now - mLastWriteTime;
3006 if (!mStandby && delta > maxPeriod) {
3007 mNumDelayedWrites++;
3008 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003009#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003010 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003011#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003012 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3013 ns2ms(delta), mNumDelayedWrites, this);
3014 lastWarning = now;
3015 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003016 }
3017}
3018
3019 mStandby = false;
3020 } else {
3021 usleep(sleepTime);
3022 }
3023
Glenn Kasten58912562012-04-03 10:45:00 -07003024 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003025 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003026 // same lock. This will also mutate and push a new fast mixer state.
3027 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003028 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003029
Glenn Kastenfa26a852012-03-06 11:28:04 -08003030 // FIXME I don't understand the need for this here;
3031 // it was in the original code but maybe the
3032 // assignment in saveOutputTracks() makes this unnecessary?
3033 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003034
3035 // Effect chains will be actually deleted here if they were removed from
3036 // mEffectChains list during mixing or effects processing
3037 effectChains.clear();
3038
3039 // FIXME Note that the above .clear() is no longer necessary since effectChains
3040 // is now local to this block, but will keep it for now (at least until merge done).
3041 }
3042
Glenn Kasten9f34a362012-03-20 16:46:41 -07003043 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3044 if (mType == MIXER || mType == DIRECT) {
3045 // put output stream into standby mode
3046 if (!mStandby) {
3047 mOutput->stream->common.standby(&mOutput->stream->common);
3048 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003049 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003050
3051 releaseWakeLock();
3052
3053 ALOGV("Thread %p type %d exiting", this, mType);
3054 return false;
3055}
3056
Glenn Kasten58912562012-04-03 10:45:00 -07003057void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3058{
Glenn Kasten58912562012-04-03 10:45:00 -07003059 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3060}
3061
3062void AudioFlinger::MixerThread::threadLoop_write()
3063{
3064 // FIXME we should only do one push per cycle; confirm this is true
3065 // Start the fast mixer if it's not already running
3066 if (mFastMixer != NULL) {
3067 FastMixerStateQueue *sq = mFastMixer->sq();
3068 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003069 if (state->mCommand != FastMixerState::MIX_WRITE &&
3070 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003071 if (state->mCommand == FastMixerState::COLD_IDLE) {
3072 int32_t old = android_atomic_inc(&mFastMixerFutex);
3073 if (old == -1) {
3074 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3075 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003076#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003077 if (mAudioWatchdog != 0) {
3078 mAudioWatchdog->resume();
3079 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003080#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003081 }
3082 state->mCommand = FastMixerState::MIX_WRITE;
3083 sq->end();
3084 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003085 if (kUseFastMixer == FastMixer_Dynamic) {
3086 mNormalSink = mPipeSink;
3087 }
Glenn Kasten58912562012-04-03 10:45:00 -07003088 } else {
3089 sq->end(false /*didModify*/);
3090 }
3091 }
3092 PlaybackThread::threadLoop_write();
3093}
3094
Glenn Kasten000f0e32012-03-01 17:10:56 -08003095// shared by MIXER and DIRECT, overridden by DUPLICATING
3096void AudioFlinger::PlaybackThread::threadLoop_write()
3097{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003098 // FIXME rewrite to reduce number of system calls
3099 mLastWriteTime = systemTime();
3100 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003101 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003102
Eric Laurent67c0a582012-05-01 19:31:12 -07003103 // If an NBAIO sink is present, use it to write the normal mixer's submix
3104 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003105#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003106 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003107#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003108 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003109#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003110 // update the setpoint when gScreenState changes
3111 uint32_t screenState = gScreenState;
3112 if (screenState != mScreenState) {
3113 mScreenState = screenState;
3114 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3115 if (pipe != NULL) {
3116 pipe->setAvgFrames((mScreenState & 1) ?
3117 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3118 }
3119 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003120 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003121#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003122 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003123#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003124 if (framesWritten > 0) {
3125 bytesWritten = framesWritten << mBitShift;
3126 } else {
3127 bytesWritten = framesWritten;
3128 }
3129 // otherwise use the HAL / AudioStreamOut directly
3130 } else {
3131 // Direct output thread.
3132 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003133 }
3134
Eric Laurent67c0a582012-05-01 19:31:12 -07003135 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003136 mNumWrites++;
3137 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003138}
3139
Glenn Kasten58912562012-04-03 10:45:00 -07003140void AudioFlinger::MixerThread::threadLoop_standby()
3141{
3142 // Idle the fast mixer if it's currently running
3143 if (mFastMixer != NULL) {
3144 FastMixerStateQueue *sq = mFastMixer->sq();
3145 FastMixerState *state = sq->begin();
3146 if (!(state->mCommand & FastMixerState::IDLE)) {
3147 state->mCommand = FastMixerState::COLD_IDLE;
3148 state->mColdFutexAddr = &mFastMixerFutex;
3149 state->mColdGen++;
3150 mFastMixerFutex = 0;
3151 sq->end();
3152 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3153 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003154 if (kUseFastMixer == FastMixer_Dynamic) {
3155 mNormalSink = mOutputSink;
3156 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003157#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003158 if (mAudioWatchdog != 0) {
3159 mAudioWatchdog->pause();
3160 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003161#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003162 } else {
3163 sq->end(false /*didModify*/);
3164 }
3165 }
3166 PlaybackThread::threadLoop_standby();
3167}
3168
Glenn Kasten000f0e32012-03-01 17:10:56 -08003169// shared by MIXER and DIRECT, overridden by DUPLICATING
3170void AudioFlinger::PlaybackThread::threadLoop_standby()
3171{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003172 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003173 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003174}
3175
3176void AudioFlinger::MixerThread::threadLoop_mix()
3177{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003178 // obtain the presentation timestamp of the next output buffer
3179 int64_t pts;
3180 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003181
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003182#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003183 if (mNormalSink != 0) {
3184 status = mNormalSink->getNextWriteTimestamp(&pts);
3185 } else {
3186 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003187 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003188#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003189
Glenn Kasten952eeb22012-03-06 11:30:57 -08003190 if (status != NO_ERROR) {
3191 pts = AudioBufferProvider::kInvalidPTS;
3192 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003193
Glenn Kasten952eeb22012-03-06 11:30:57 -08003194 // mix buffers...
3195 mAudioMixer->process(pts);
3196 // increase sleep time progressively when application underrun condition clears.
3197 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3198 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3199 // such that we would underrun the audio HAL.
3200 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3201 sleepTimeShift--;
3202 }
3203 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003204 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003205 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003206}
3207
3208void AudioFlinger::MixerThread::threadLoop_sleepTime()
3209{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003210 // If no tracks are ready, sleep once for the duration of an output
3211 // buffer size, then write 0s to the output
3212 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003213 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003214 sleepTime = activeSleepTime >> sleepTimeShift;
3215 if (sleepTime < kMinThreadSleepTimeUs) {
3216 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003218 // reduce sleep time in case of consecutive application underruns to avoid
3219 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3220 // duration we would end up writing less data than needed by the audio HAL if
3221 // the condition persists.
3222 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3223 sleepTimeShift++;
3224 }
3225 } else {
3226 sleepTime = idleSleepTime;
3227 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003228 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003229 memset (mMixBuffer, 0, mixBufferSize);
3230 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003231 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003232 }
3233 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234}
3235
3236// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003237AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003238 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239{
3240
Glenn Kasten29c23c32012-01-26 13:37:52 -08003241 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003243 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 size_t mixedTracks = 0;
3245 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003246 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003247 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003248 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249
3250 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003251 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252
Eric Laurent571d49c2010-08-11 05:20:11 -07003253 if (masterMute) {
3254 masterVolume = 0;
3255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003257 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003259 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003260 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 masterVolume = (float)((v + (1 << 23)) >> 24);
3262 chain.clear();
3263 }
3264
Glenn Kasten288ed212012-04-25 17:52:27 -07003265 // prepare a new state to push
3266 FastMixerStateQueue *sq = NULL;
3267 FastMixerState *state = NULL;
3268 bool didModify = false;
3269 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3270 if (mFastMixer != NULL) {
3271 sq = mFastMixer->sq();
3272 state = sq->begin();
3273 }
3274
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003276 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 if (t == 0) continue;
3278
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003279 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003281
Glenn Kasten288ed212012-04-25 17:52:27 -07003282 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003283 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003284
3285 // It's theoretically possible (though unlikely) for a fast track to be created
3286 // and then removed within the same normal mix cycle. This is not a problem, as
3287 // the track never becomes active so it's fast mixer slot is never touched.
3288 // The converse, of removing an (active) track and then creating a new track
3289 // at the identical fast mixer slot within the same normal mix cycle,
3290 // is impossible because the slot isn't marked available until the end of each cycle.
3291 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003292 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3293 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003294 FastTrack *fastTrack = &state->mFastTracks[j];
3295
3296 // Determine whether the track is currently in underrun condition,
3297 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003298 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3299 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003300 uint32_t recentFull = (underruns.mBitFields.mFull -
3301 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3302 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3303 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3304 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3305 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3306 uint32_t recentUnderruns = recentPartial + recentEmpty;
3307 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003308 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003309 // or stopped which can occur when flush() is called while active
3310 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003311 track->mUnderrunCount += recentUnderruns;
3312 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003313
Glenn Kastend08f48c2012-05-01 18:14:02 -07003314 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003316 bool isActive = true;
3317 switch (track->mState) {
3318 case TrackBase::STOPPING_1:
3319 // track stays active in STOPPING_1 state until first underrun
3320 if (recentUnderruns > 0) {
3321 track->mState = TrackBase::STOPPING_2;
3322 }
3323 break;
3324 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003325 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003326 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003327 break;
3328 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003329 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003330 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003331 break;
3332 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003333 if (recentFull > 0 || recentPartial > 0) {
3334 // track has provided at least some frames recently: reset retry count
3335 track->mRetryCount = kMaxTrackRetries;
3336 }
3337 if (recentUnderruns == 0) {
3338 // no recent underruns: stay active
3339 break;
3340 }
3341 // there has recently been an underrun of some kind
3342 if (track->sharedBuffer() == 0) {
3343 // were any of the recent underruns "empty" (no frames available)?
3344 if (recentEmpty == 0) {
3345 // no, then ignore the partial underruns as they are allowed indefinitely
3346 break;
3347 }
3348 // there has recently been an "empty" underrun: decrement the retry counter
3349 if (--(track->mRetryCount) > 0) {
3350 break;
3351 }
3352 // indicate to client process that the track was disabled because of underrun;
3353 // it will then automatically call start() when data is available
3354 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3355 // remove from active list, but state remains ACTIVE [confusing but true]
3356 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003357 break;
3358 }
3359 // fall through
3360 case TrackBase::STOPPING_2:
3361 case TrackBase::PAUSED:
3362 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003363 case TrackBase::STOPPED:
3364 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003365 // Check for presentation complete if track is inactive
3366 // We have consumed all the buffers of this track.
3367 // This would be incomplete if we auto-paused on underrun
3368 {
3369 size_t audioHALFrames =
3370 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3371 size_t framesWritten =
3372 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003373 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003374 // track stays in active list until presentation is complete
3375 break;
3376 }
3377 }
3378 if (track->isStopping_2()) {
3379 track->mState = TrackBase::STOPPED;
3380 }
3381 if (track->isStopped()) {
3382 // Can't reset directly, as fast mixer is still polling this track
3383 // track->reset();
3384 // So instead mark this track as needing to be reset after push with ack
3385 resetMask |= 1 << i;
3386 }
3387 isActive = false;
3388 break;
3389 case TrackBase::IDLE:
3390 default:
3391 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003392 }
3393
3394 if (isActive) {
3395 // was it previously inactive?
3396 if (!(state->mTrackMask & (1 << j))) {
3397 ExtendedAudioBufferProvider *eabp = track;
3398 VolumeProvider *vp = track;
3399 fastTrack->mBufferProvider = eabp;
3400 fastTrack->mVolumeProvider = vp;
3401 fastTrack->mSampleRate = track->mSampleRate;
3402 fastTrack->mChannelMask = track->mChannelMask;
3403 fastTrack->mGeneration++;
3404 state->mTrackMask |= 1 << j;
3405 didModify = true;
3406 // no acknowledgement required for newly active tracks
3407 }
3408 // cache the combined master volume and stream type volume for fast mixer; this
3409 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3410 track->mCachedVolume = track->isMuted() ?
3411 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3412 ++fastTracks;
3413 } else {
3414 // was it previously active?
3415 if (state->mTrackMask & (1 << j)) {
3416 fastTrack->mBufferProvider = NULL;
3417 fastTrack->mGeneration++;
3418 state->mTrackMask &= ~(1 << j);
3419 didModify = true;
3420 // If any fast tracks were removed, we must wait for acknowledgement
3421 // because we're about to decrement the last sp<> on those tracks.
3422 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003423 } else {
3424 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003425 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003426 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003427 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003428 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003429 }
3430 continue;
3431 }
3432
3433 { // local variable scope to avoid goto warning
3434
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 audio_track_cblk_t* cblk = track->cblk();
3436
3437 // The first time a track is added we wait
3438 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003439 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003440 // make sure that we have enough frames to mix one full buffer.
3441 // enforce this condition only once to enable draining the buffer in case the client
3442 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003443 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003444 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003445 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003446 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003447 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003448 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003449 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003450 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003451 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003452 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003453 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003454 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003455 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3456 // the minimum track buffer size is normally twice the number of frames necessary
3457 // to fill one buffer and the resampler should not leave more than one buffer worth
3458 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003459 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003460 }
3461 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003462 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 !track->isPaused() && !track->isTerminated())
3464 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003465 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466
3467 mixedTracks++;
3468
3469 // track->mainBuffer() != mMixBuffer means there is an effect chain
3470 // connected to the track
3471 chain.clear();
3472 if (track->mainBuffer() != mMixBuffer) {
3473 chain = getEffectChain_l(track->sessionId());
3474 // Delegate volume control to effect in track effect chain if needed
3475 if (chain != 0) {
3476 tracksWithEffect++;
3477 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003478 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003479 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 }
3481 }
3482
3483
3484 int param = AudioMixer::VOLUME;
3485 if (track->mFillingUpStatus == Track::FS_FILLED) {
3486 // no ramp for the first volume setting
3487 track->mFillingUpStatus = Track::FS_ACTIVE;
3488 if (track->mState == TrackBase::RESUMING) {
3489 track->mState = TrackBase::ACTIVE;
3490 param = AudioMixer::RAMP_VOLUME;
3491 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003492 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 } else if (cblk->server != 0) {
3494 // If the track is stopped before the first frame was mixed,
3495 // do not apply ramp
3496 param = AudioMixer::RAMP_VOLUME;
3497 }
3498
3499 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003500 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003501 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003502 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003503 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 if (track->isPausing()) {
3505 track->setPaused();
3506 }
3507 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003508
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003510 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003512 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003513 vl = vlr & 0xFFFF;
3514 vr = vlr >> 16;
3515 // track volumes come from shared memory, so can't be trusted and must be clamped
3516 if (vl > MAX_GAIN_INT) {
3517 ALOGV("Track left volume out of range: %04X", vl);
3518 vl = MAX_GAIN_INT;
3519 }
3520 if (vr > MAX_GAIN_INT) {
3521 ALOGV("Track right volume out of range: %04X", vr);
3522 vr = MAX_GAIN_INT;
3523 }
3524 // now apply the master volume and stream type volume
3525 vl = (uint32_t)(v * vl) << 12;
3526 vr = (uint32_t)(v * vr) << 12;
3527 // assuming master volume and stream type volume each go up to 1.0,
3528 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529
Glenn Kasten05632a52012-01-03 14:22:33 -08003530 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3531 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003532 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003533 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003534 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003535 }
3536 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003538 // Delegate volume control to effect in track effect chain if needed
3539 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3540 // Do not ramp volume if volume is controlled by effect
3541 param = AudioMixer::VOLUME;
3542 track->mHasVolumeController = true;
3543 } else {
3544 // force no volume ramp when volume controller was just disabled or removed
3545 // from effect chain to avoid volume spike
3546 if (track->mHasVolumeController) {
3547 param = AudioMixer::VOLUME;
3548 }
3549 track->mHasVolumeController = false;
3550 }
3551
3552 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003553 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003554 vl = (vl + (1 << 11)) >> 12;
3555 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3556 vr = (vr + (1 << 11)) >> 12;
3557 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003558
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003559 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 -07003560
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003562 mAudioMixer->setBufferProvider(name, track);
3563 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003565 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3566 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3567 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
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::TRACK,
3571 AudioMixer::FORMAT, (void *)track->format());
3572 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003573 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003575 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003577 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 AudioMixer::RESAMPLE,
3579 AudioMixer::SAMPLE_RATE,
3580 (void *)(cblk->sampleRate));
3581 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003582 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 AudioMixer::TRACK,
3584 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3585 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003586 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 AudioMixer::TRACK,
3588 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3589
3590 // reset retry count
3591 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003592
Eric Laurent27741442012-01-17 19:20:12 -08003593 // If one track is ready, set the mixer ready if:
3594 // - the mixer was not ready during previous round OR
3595 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003596 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003597 mixerStatus != MIXER_TRACKS_ENABLED) {
3598 mixerStatus = MIXER_TRACKS_READY;
3599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003601 // clear effect chain input buffer if an active track underruns to avoid sending
3602 // previous audio buffer again to effects
3603 chain = getEffectChain_l(track->sessionId());
3604 if (chain != 0) {
3605 chain->clearInputBuffer();
3606 }
3607
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003608 //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 -07003609 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003610 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 // We have consumed all the buffers of this track.
3612 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003613 // TODO: use actual buffer filling status instead of latency when available from
3614 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003615 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003616 size_t framesWritten =
3617 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003618 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003619 if (track->isStopped()) {
3620 track->reset();
3621 }
Eric Laurenta011e352012-03-29 15:51:43 -07003622 tracksToRemove->add(track);
3623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003625 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626 // No buffers for this track. Give it a few chances to
3627 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003628 if (--(track->mRetryCount) <= 0) {
3629 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003631 // indicate to client process that the track was disabled because of underrun;
3632 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003633 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003634 // If one track is not ready, mark the mixer also not ready if:
3635 // - the mixer was ready during previous round OR
3636 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003637 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003638 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639 mixerStatus = MIXER_TRACKS_ENABLED;
3640 }
3641 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003642 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 }
Glenn Kasten58912562012-04-03 10:45:00 -07003644
3645 } // local variable scope to avoid goto warning
3646track_is_ready: ;
3647
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 }
3649
Glenn Kasten288ed212012-04-25 17:52:27 -07003650 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003651 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003652 if (didModify) {
3653 state->mFastTracksGen++;
3654 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3655 if (kUseFastMixer == FastMixer_Dynamic &&
3656 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3657 state->mCommand = FastMixerState::COLD_IDLE;
3658 state->mColdFutexAddr = &mFastMixerFutex;
3659 state->mColdGen++;
3660 mFastMixerFutex = 0;
3661 if (kUseFastMixer == FastMixer_Dynamic) {
3662 mNormalSink = mOutputSink;
3663 }
3664 // If we go into cold idle, need to wait for acknowledgement
3665 // so that fast mixer stops doing I/O.
3666 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003667 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003668 }
3669 sq->end();
3670 }
3671 if (sq != NULL) {
3672 sq->end(didModify);
3673 sq->push(block);
3674 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003675#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003676 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3677 mAudioWatchdog->pause();
3678 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003679#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003680
3681 // Now perform the deferred reset on fast tracks that have stopped
3682 while (resetMask != 0) {
3683 size_t i = __builtin_ctz(resetMask);
3684 ALOG_ASSERT(i < count);
3685 resetMask &= ~(1 << i);
3686 sp<Track> t = mActiveTracks[i].promote();
3687 if (t == 0) continue;
3688 Track* track = t.get();
3689 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3690 track->reset();
3691 }
Glenn Kasten58912562012-04-03 10:45:00 -07003692
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 // remove all the tracks that need to be...
3694 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003695 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 for (size_t i=0 ; i<count ; i++) {
3697 const sp<Track>& track = tracksToRemove->itemAt(i);
3698 mActiveTracks.remove(track);
3699 if (track->mainBuffer() != mMixBuffer) {
3700 chain = getEffectChain_l(track->sessionId());
3701 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003702 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003703 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704 }
3705 }
3706 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003707 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 }
3709 }
3710 }
3711
3712 // mix buffer must be cleared if all tracks are connected to an
3713 // effect chain as in this case the mixer will not write to
3714 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003715 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3716 // FIXME as a performance optimization, should remember previous zero status
3717 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 }
3719
Glenn Kasten58912562012-04-03 10:45:00 -07003720 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003721 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003722 if (fastTracks > 0) {
3723 mixerStatus = MIXER_TRACKS_READY;
3724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 return mixerStatus;
3726}
3727
Glenn Kasten66fcab92012-02-24 14:59:21 -08003728/*
3729The derived values that are cached:
3730 - mixBufferSize from frame count * frame size
3731 - activeSleepTime from activeSleepTimeUs()
3732 - idleSleepTime from idleSleepTimeUs()
3733 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3734 - maxPeriod from frame count and sample rate (MIXER only)
3735
3736The parameters that affect these derived values are:
3737 - frame count
3738 - frame size
3739 - sample rate
3740 - device type: A2DP or not
3741 - device latency
3742 - format: PCM or not
3743 - active sleep time
3744 - idle sleep time
3745*/
3746
3747void AudioFlinger::PlaybackThread::cacheParameters_l()
3748{
Glenn Kasten58912562012-04-03 10:45:00 -07003749 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003750 activeSleepTime = activeSleepTimeUs();
3751 idleSleepTime = idleSleepTimeUs();
3752}
3753
Eric Laurent22167852012-06-20 12:26:32 -07003754void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755{
Steve Block3856b092011-10-20 11:56:00 +01003756 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003757 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003759
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 size_t size = mTracks.size();
3761 for (size_t i = 0; i < size; i++) {
3762 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003763 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003764 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767 }
3768}
3769
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003771int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003773 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774}
3775
3776// deleteTrackName_l() must be called with ThreadBase::mLock held
3777void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3778{
Steve Block3856b092011-10-20 11:56:00 +01003779 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 mAudioMixer->deleteTrackName(name);
3781}
3782
3783// checkForNewParameters_l() must be called with ThreadBase::mLock held
3784bool AudioFlinger::MixerThread::checkForNewParameters_l()
3785{
Glenn Kasten58912562012-04-03 10:45:00 -07003786 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3787 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 bool reconfig = false;
3789
3790 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003791
3792 if (mFastMixer != NULL) {
3793 FastMixerStateQueue *sq = mFastMixer->sq();
3794 FastMixerState *state = sq->begin();
3795 if (!(state->mCommand & FastMixerState::IDLE)) {
3796 previousCommand = state->mCommand;
3797 state->mCommand = FastMixerState::HOT_IDLE;
3798 sq->end();
3799 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3800 } else {
3801 sq->end(false /*didModify*/);
3802 }
3803 }
3804
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 status_t status = NO_ERROR;
3806 String8 keyValuePair = mNewParameters[0];
3807 AudioParameter param = AudioParameter(keyValuePair);
3808 int value;
3809
3810 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3811 reconfig = true;
3812 }
3813 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003814 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815 status = BAD_VALUE;
3816 } else {
3817 reconfig = true;
3818 }
3819 }
3820 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003821 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 status = BAD_VALUE;
3823 } else {
3824 reconfig = true;
3825 }
3826 }
3827 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3828 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003829 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 // if frame count is changed after track creation
3831 if (!mTracks.isEmpty()) {
3832 status = INVALID_OPERATION;
3833 } else {
3834 reconfig = true;
3835 }
3836 }
3837 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003838#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003839 // when changing the audio output device, call addBatteryData to notify
3840 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003841 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003842 uint32_t params = 0;
3843 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003844 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003845 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3846 }
3847
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003848 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003849 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003850 // check if any other device (except speaker) is on
3851 if (value & deviceWithoutSpeaker ) {
3852 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3853 }
3854
3855 if (params != 0) {
3856 addBatteryData(params);
3857 }
3858 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003859#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003860
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 // forward device change to effects that have requested to be
3862 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003863 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003865 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866 }
3867 }
3868
3869 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003870 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003871 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003873 mOutput->stream->common.standby(&mOutput->stream->common);
3874 mStandby = true;
3875 mBytesWritten = 0;
3876 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003877 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003878 }
3879 if (status == NO_ERROR && reconfig) {
3880 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003881 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3882 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003884 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003886 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 if (name < 0) break;
3888 mTracks[i]->mName = name;
3889 // limit track sample rate to 2 x new output sample rate
3890 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3891 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3892 }
3893 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003894 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 }
3896 }
3897
3898 mNewParameters.removeAt(0);
3899
3900 mParamStatus = status;
3901 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003902 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3903 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003904 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 }
Glenn Kasten58912562012-04-03 10:45:00 -07003906
3907 if (!(previousCommand & FastMixerState::IDLE)) {
3908 ALOG_ASSERT(mFastMixer != NULL);
3909 FastMixerStateQueue *sq = mFastMixer->sq();
3910 FastMixerState *state = sq->begin();
3911 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3912 state->mCommand = previousCommand;
3913 sq->end();
3914 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3915 }
3916
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 return reconfig;
3918}
3919
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003920void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921{
3922 const size_t SIZE = 256;
3923 char buffer[SIZE];
3924 String8 result;
3925
3926 PlaybackThread::dumpInternals(fd, args);
3927
3928 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3929 result.append(buffer);
3930 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003931
3932 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3933 FastMixerDumpState copy = mFastMixerDumpState;
3934 copy.dump(fd);
3935
Glenn Kasten39993082012-05-31 13:40:27 -07003936#ifdef STATE_QUEUE_DUMP
3937 // Similar for state queue
3938 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3939 observerCopy.dump(fd);
3940 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3941 mutatorCopy.dump(fd);
3942#endif
3943
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003944 // Write the tee output to a .wav file
3945 NBAIO_Source *teeSource = mTeeSource.get();
3946 if (teeSource != NULL) {
3947 char teePath[64];
3948 struct timeval tv;
3949 gettimeofday(&tv, NULL);
3950 struct tm tm;
3951 localtime_r(&tv.tv_sec, &tm);
3952 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3953 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3954 if (teeFd >= 0) {
3955 char wavHeader[44];
3956 memcpy(wavHeader,
3957 "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",
3958 sizeof(wavHeader));
3959 NBAIO_Format format = teeSource->format();
3960 unsigned channelCount = Format_channelCount(format);
3961 ALOG_ASSERT(channelCount <= FCC_2);
3962 unsigned sampleRate = Format_sampleRate(format);
3963 wavHeader[22] = channelCount; // number of channels
3964 wavHeader[24] = sampleRate; // sample rate
3965 wavHeader[25] = sampleRate >> 8;
3966 wavHeader[32] = channelCount * 2; // block alignment
3967 write(teeFd, wavHeader, sizeof(wavHeader));
3968 size_t total = 0;
3969 bool firstRead = true;
3970 for (;;) {
3971#define TEE_SINK_READ 1024
3972 short buffer[TEE_SINK_READ * FCC_2];
3973 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003974 ssize_t actual = teeSource->read(buffer, count,
3975 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003976 bool wasFirstRead = firstRead;
3977 firstRead = false;
3978 if (actual <= 0) {
3979 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3980 continue;
3981 }
3982 break;
3983 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003984 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003985 write(teeFd, buffer, actual * channelCount * sizeof(short));
3986 total += actual;
3987 }
3988 lseek(teeFd, (off_t) 4, SEEK_SET);
3989 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3990 write(teeFd, &temp, sizeof(temp));
3991 lseek(teeFd, (off_t) 40, SEEK_SET);
3992 temp = total * channelCount * sizeof(short);
3993 write(teeFd, &temp, sizeof(temp));
3994 close(teeFd);
3995 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3996 } else {
3997 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3998 }
3999 }
4000
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004001#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07004002 if (mAudioWatchdog != 0) {
4003 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4004 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4005 wdCopy.dump(fd);
4006 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004007#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008}
4009
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004010uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011{
Glenn Kasten58912562012-04-03 10:45:00 -07004012 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013}
4014
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004015uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004016{
Glenn Kasten58912562012-04-03 10:45:00 -07004017 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004018}
4019
Glenn Kasten66fcab92012-02-24 14:59:21 -08004020void AudioFlinger::MixerThread::cacheParameters_l()
4021{
4022 PlaybackThread::cacheParameters_l();
4023
4024 // FIXME: Relaxed timing because of a certain device that can't meet latency
4025 // Should be reduced to 2x after the vendor fixes the driver issue
4026 // increase threshold again due to low power audio mode. The way this warning
4027 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004028 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004029}
4030
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004032AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004033 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004034 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004035 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037}
4038
4039AudioFlinger::DirectOutputThread::~DirectOutputThread()
4040{
4041}
4042
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004043AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4044 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004045)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004047 sp<Track> trackToRemove;
4048
Glenn Kastenfec279f2012-03-08 07:47:15 -08004049 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050
Glenn Kasten952eeb22012-03-06 11:30:57 -08004051 // find out which tracks need to be processed
4052 if (mActiveTracks.size() != 0) {
4053 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004054 // The track died recently
4055 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056
Glenn Kasten952eeb22012-03-06 11:30:57 -08004057 Track* const track = t.get();
4058 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059
Glenn Kasten952eeb22012-03-06 11:30:57 -08004060 // The first time a track is added we wait
4061 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004062 uint32_t minFrames;
4063 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4064 minFrames = mNormalFrameCount;
4065 } else {
4066 minFrames = 1;
4067 }
4068 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004069 !track->isPaused() && !track->isTerminated())
4070 {
4071 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072
Glenn Kasten952eeb22012-03-06 11:30:57 -08004073 if (track->mFillingUpStatus == Track::FS_FILLED) {
4074 track->mFillingUpStatus = Track::FS_ACTIVE;
4075 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004076 if (track->mState == TrackBase::RESUMING) {
4077 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004078 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004079 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004080
Glenn Kasten952eeb22012-03-06 11:30:57 -08004081 // compute volume for this track
4082 float left, right;
4083 if (track->isMuted() || mMasterMute || track->isPausing() ||
4084 mStreamTypes[track->streamType()].mute) {
4085 left = right = 0;
4086 if (track->isPausing()) {
4087 track->setPaused();
4088 }
4089 } else {
4090 float typeVolume = mStreamTypes[track->streamType()].volume;
4091 float v = mMasterVolume * typeVolume;
4092 uint32_t vlr = cblk->getVolumeLR();
4093 float v_clamped = v * (vlr & 0xFFFF);
4094 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4095 left = v_clamped/MAX_GAIN;
4096 v_clamped = v * (vlr >> 16);
4097 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4098 right = v_clamped/MAX_GAIN;
4099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100
Glenn Kasten952eeb22012-03-06 11:30:57 -08004101 if (left != mLeftVolFloat || right != mRightVolFloat) {
4102 mLeftVolFloat = left;
4103 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104
Glenn Kasten952eeb22012-03-06 11:30:57 -08004105 // Convert volumes from float to 8.24
4106 uint32_t vl = (uint32_t)(left * (1 << 24));
4107 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108
Glenn Kasten952eeb22012-03-06 11:30:57 -08004109 // Delegate volume control to effect in track effect chain if needed
4110 // only one effect chain can be present on DirectOutputThread, so if
4111 // there is one, the track is connected to it
4112 if (!mEffectChains.isEmpty()) {
4113 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004114 mEffectChains[0]->setVolume_l(&vl, &vr);
4115 left = (float)vl / (1 << 24);
4116 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004117 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004118 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004119 }
4120
4121 // reset retry count
4122 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004123 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004124 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004125 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004126 // clear effect chain input buffer if an active track underruns to avoid sending
4127 // previous audio buffer again to effects
4128 if (!mEffectChains.isEmpty()) {
4129 mEffectChains[0]->clearInputBuffer();
4130 }
4131
Glenn Kasten952eeb22012-03-06 11:30:57 -08004132 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004133 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004134 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004135 // We have consumed all the buffers of this track.
4136 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004137 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004138 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004139 size_t framesWritten =
4140 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004141 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004142 if (track->isStopped()) {
4143 track->reset();
4144 }
Eric Laurenta011e352012-03-29 15:51:43 -07004145 trackToRemove = track;
4146 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004147 } else {
4148 // No buffers for this track. Give it a few chances to
4149 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004150 if (--(track->mRetryCount) <= 0) {
4151 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004152 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004154 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 }
4156 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004157 }
4158 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004160 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004161 // remove all the tracks that need to be...
4162 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004163 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004164 mActiveTracks.remove(trackToRemove);
4165 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004166 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004167 trackToRemove->sessionId());
4168 mEffectChains[0]->decActiveTrackCnt();
4169 }
4170 if (trackToRemove->isTerminated()) {
4171 removeTrack_l(trackToRemove);
4172 }
4173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174
Glenn Kastenfec279f2012-03-08 07:47:15 -08004175 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004176}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177
Glenn Kasten000f0e32012-03-01 17:10:56 -08004178void AudioFlinger::DirectOutputThread::threadLoop_mix()
4179{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004180 AudioBufferProvider::Buffer buffer;
4181 size_t frameCount = mFrameCount;
4182 int8_t *curBuf = (int8_t *)mMixBuffer;
4183 // output audio to hardware
4184 while (frameCount) {
4185 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004186 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004187 if (CC_UNLIKELY(buffer.raw == NULL)) {
4188 memset(curBuf, 0, frameCount * mFrameSize);
4189 break;
4190 }
4191 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4192 frameCount -= buffer.frameCount;
4193 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004194 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004195 }
4196 sleepTime = 0;
4197 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004198 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004199
Glenn Kasten000f0e32012-03-01 17:10:56 -08004200}
4201
4202void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4203{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004204 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004205 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004206 sleepTime = activeSleepTime;
4207 } else {
4208 sleepTime = idleSleepTime;
4209 }
4210 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004211 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004212 sleepTime = 0;
4213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214}
4215
4216// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004217int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4218 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219{
4220 return 0;
4221}
4222
4223// deleteTrackName_l() must be called with ThreadBase::mLock held
4224void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4225{
4226}
4227
4228// checkForNewParameters_l() must be called with ThreadBase::mLock held
4229bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4230{
4231 bool reconfig = false;
4232
4233 while (!mNewParameters.isEmpty()) {
4234 status_t status = NO_ERROR;
4235 String8 keyValuePair = mNewParameters[0];
4236 AudioParameter param = AudioParameter(keyValuePair);
4237 int value;
4238
4239 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4240 // do not accept frame count changes if tracks are open as the track buffer
4241 // size depends on frame count and correct behavior would not be garantied
4242 // if frame count is changed after track creation
4243 if (!mTracks.isEmpty()) {
4244 status = INVALID_OPERATION;
4245 } else {
4246 reconfig = true;
4247 }
4248 }
4249 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004250 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004251 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004253 mOutput->stream->common.standby(&mOutput->stream->common);
4254 mStandby = true;
4255 mBytesWritten = 0;
4256 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004257 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 }
4259 if (status == NO_ERROR && reconfig) {
4260 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004261 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 }
4263 }
4264
4265 mNewParameters.removeAt(0);
4266
4267 mParamStatus = status;
4268 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004269 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4270 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004271 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 }
4273 return reconfig;
4274}
4275
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004276uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277{
4278 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004279 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004280 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 } else {
4282 time = 10000;
4283 }
4284 return time;
4285}
4286
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004287uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288{
4289 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004290 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004291 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 } else {
4293 time = 10000;
4294 }
4295 return time;
4296}
4297
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004298uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004299{
4300 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004301 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004302 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4303 } else {
4304 time = 10000;
4305 }
4306 return time;
4307}
4308
Glenn Kasten66fcab92012-02-24 14:59:21 -08004309void AudioFlinger::DirectOutputThread::cacheParameters_l()
4310{
4311 PlaybackThread::cacheParameters_l();
4312
4313 // use shorter standby delay as on normal output to release
4314 // hardware resources as soon as possible
4315 standbyDelay = microseconds(activeSleepTime*2);
4316}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004317
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318// ----------------------------------------------------------------------------
4319
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004320AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004321 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004322 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004323 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 addOutputTrack(mainThread);
4326}
4327
4328AudioFlinger::DuplicatingThread::~DuplicatingThread()
4329{
4330 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4331 mOutputTracks[i]->destroy();
4332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333}
4334
Glenn Kasten000f0e32012-03-01 17:10:56 -08004335void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004337 // mix buffers...
4338 if (outputsReady(outputTracks)) {
4339 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4340 } else {
4341 memset(mMixBuffer, 0, mixBufferSize);
4342 }
4343 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004344 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004345 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004346}
4347
4348void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4349{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004350 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004351 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004352 sleepTime = activeSleepTime;
4353 } else {
4354 sleepTime = idleSleepTime;
4355 }
4356 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004357 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4358 writeFrames = mNormalFrameCount;
4359 memset(mMixBuffer, 0, mixBufferSize);
4360 } else {
4361 // flush remaining overflow buffers in output tracks
4362 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004363 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004364 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004365 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004366}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367
Glenn Kasten000f0e32012-03-01 17:10:56 -08004368void AudioFlinger::DuplicatingThread::threadLoop_write()
4369{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004370 for (size_t i = 0; i < outputTracks.size(); i++) {
4371 outputTracks[i]->write(mMixBuffer, writeFrames);
4372 }
4373 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004374}
Glenn Kasten688a6402012-02-29 07:57:06 -08004375
Glenn Kasten000f0e32012-03-01 17:10:56 -08004376void AudioFlinger::DuplicatingThread::threadLoop_standby()
4377{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004378 // DuplicatingThread implements standby by stopping all tracks
4379 for (size_t i = 0; i < outputTracks.size(); i++) {
4380 outputTracks[i]->stop();
4381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382}
4383
Glenn Kastenfa26a852012-03-06 11:28:04 -08004384void AudioFlinger::DuplicatingThread::saveOutputTracks()
4385{
4386 outputTracks = mOutputTracks;
4387}
4388
4389void AudioFlinger::DuplicatingThread::clearOutputTracks()
4390{
4391 outputTracks.clear();
4392}
4393
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4395{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004396 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004397 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004398 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004399 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 this,
4401 mSampleRate,
4402 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004403 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 frameCount);
4405 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004406 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004408 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004409 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 }
4411}
4412
4413void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4414{
4415 Mutex::Autolock _l(mLock);
4416 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004417 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 mOutputTracks[i]->destroy();
4419 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004420 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 return;
4422 }
4423 }
Steve Block3856b092011-10-20 11:56:00 +01004424 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425}
4426
Glenn Kasten438b0362012-03-06 11:24:48 -08004427// caller must hold mLock
4428void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429{
4430 mWaitTimeMs = UINT_MAX;
4431 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4432 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004433 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4435 if (waitTimeMs < mWaitTimeMs) {
4436 mWaitTimeMs = waitTimeMs;
4437 }
4438 }
4439 }
4440}
4441
4442
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004443bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444{
4445 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004446 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004448 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 return false;
4450 }
4451 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004452 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004454 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 return false;
4456 }
4457 }
4458 return true;
4459}
4460
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004461uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462{
4463 return (mWaitTimeMs * 1000) / 2;
4464}
4465
Glenn Kasten66fcab92012-02-24 14:59:21 -08004466void AudioFlinger::DuplicatingThread::cacheParameters_l()
4467{
4468 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4469 updateWaitTime_l();
4470
4471 MixerThread::cacheParameters_l();
4472}
4473
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474// ----------------------------------------------------------------------------
4475
4476// TrackBase constructor must be called with AudioFlinger::mLock held
4477AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004478 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 const sp<Client>& client,
4480 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004481 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004482 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 const sp<IMemory>& sharedBuffer,
4485 int sessionId)
4486 : RefBase(),
4487 mThread(thread),
4488 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004489 mCblk(NULL),
4490 // mBuffer
4491 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 mFrameCount(0),
4493 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004494 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004496 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004498 // mChannelCount
4499 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500{
Steve Block3856b092011-10-20 11:56:00 +01004501 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502
Steve Blockb8a80522011-12-20 16:23:08 +00004503 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004504 size_t size = sizeof(audio_track_cblk_t);
4505 uint8_t channelCount = popcount(channelMask);
4506 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4507 if (sharedBuffer == 0) {
4508 size += bufferSize;
4509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004511 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 mCblkMemory = client->heap()->allocate(size);
4513 if (mCblkMemory != 0) {
4514 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004515 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 new(mCblk) audio_track_cblk_t();
4517 // clear all buffers
4518 mCblk->frameCount = frameCount;
4519 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004520// uncomment the following lines to quickly test 32-bit wraparound
4521// mCblk->user = 0xffff0000;
4522// mCblk->server = 0xffff0000;
4523// mCblk->userBase = 0xffff0000;
4524// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004525 mChannelCount = channelCount;
4526 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 if (sharedBuffer == 0) {
4528 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4529 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4530 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004531 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 mCblk->flags = CBLK_UNDERRUN_ON;
4533 } else {
4534 mBuffer = sharedBuffer->pointer();
4535 }
4536 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4537 }
4538 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004539 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 client->heap()->dump("AudioTrack");
4541 return;
4542 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004543 } else {
4544 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004545 // construct the shared structure in-place.
4546 new(mCblk) audio_track_cblk_t();
4547 // clear all buffers
4548 mCblk->frameCount = frameCount;
4549 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004550// uncomment the following lines to quickly test 32-bit wraparound
4551// mCblk->user = 0xffff0000;
4552// mCblk->server = 0xffff0000;
4553// mCblk->userBase = 0xffff0000;
4554// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004555 mChannelCount = channelCount;
4556 mChannelMask = channelMask;
4557 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4558 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4559 // Force underrun condition to avoid false underrun callback until first data is
4560 // written to buffer (other flags are cleared)
4561 mCblk->flags = CBLK_UNDERRUN_ON;
4562 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564}
4565
4566AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4567{
Glenn Kastena0d68332012-01-27 16:47:15 -08004568 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004569 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004571 } else {
4572 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 }
4574 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004575 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004576 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004577 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004579 // If the client's reference count drops to zero, the associated destructor
4580 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4581 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 mClient.clear();
4583 }
4584}
4585
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004586// AudioBufferProvider interface
4587// getNextBuffer() = 0;
4588// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4590{
Glenn Kastene0feee32011-12-13 11:53:26 -08004591 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004593 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004594 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 buffer->frameCount = 0;
4596}
4597
4598bool AudioFlinger::ThreadBase::TrackBase::step() {
4599 bool result;
4600 audio_track_cblk_t* cblk = this->cblk();
4601
4602 result = cblk->stepServer(mFrameCount);
4603 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004604 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004605 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 }
4607 return result;
4608}
4609
4610void AudioFlinger::ThreadBase::TrackBase::reset() {
4611 audio_track_cblk_t* cblk = this->cblk();
4612
4613 cblk->user = 0;
4614 cblk->server = 0;
4615 cblk->userBase = 0;
4616 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004617 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004618 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619}
4620
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4622 return (int)mCblk->sampleRate;
4623}
4624
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4626 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004627 size_t frameSize = cblk->frameSize;
4628 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4629 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630
4631 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004632 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4633 "TrackBase::getBuffer buffer out of range:\n"
4634 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4635 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004637 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638
4639 return bufferStart;
4640}
4641
Eric Laurenta011e352012-03-29 15:51:43 -07004642status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4643{
4644 mSyncEvents.add(event);
4645 return NO_ERROR;
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648// ----------------------------------------------------------------------------
4649
4650// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4651AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004652 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004654 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004656 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004657 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 int frameCount,
4659 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004660 int sessionId,
4661 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004662 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004663 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004664 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004665 // mRetryCount initialized later when needed
4666 mSharedBuffer(sharedBuffer),
4667 mStreamType(streamType),
4668 mName(-1), // see note below
4669 mMainBuffer(thread->mixBuffer()),
4670 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004671 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004672 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004673 mFlags(flags),
4674 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004675 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004676 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677{
4678 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4680 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004681 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004682 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004683 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004684 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004685 if (mName < 0) {
4686 ALOGE("no more track names available");
4687 return;
4688 }
4689 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004690 if (flags & IAudioFlinger::TRACK_FAST) {
4691 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4692 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4693 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004694 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004695 // FIXME This is too eager. We allocate a fast track index before the
4696 // fast track becomes active. Since fast tracks are a scarce resource,
4697 // this means we are potentially denying other more important fast tracks from
4698 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004699 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004700 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004701 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004702 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004703 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004704 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004706 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707}
4708
4709AudioFlinger::PlaybackThread::Track::~Track()
4710{
Steve Block3856b092011-10-20 11:56:00 +01004711 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004712}
4713
4714void AudioFlinger::PlaybackThread::Track::destroy()
4715{
4716 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4717 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004718 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 // we must acquire a strong reference on this Track before locking mLock
4720 // here so that the destructor is called only when exiting this function.
4721 // On the other hand, as long as Track::destroy() is only called by
4722 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4723 // this Track with its member mTrack.
4724 sp<Track> keep(this);
4725 { // scope for mLock
4726 sp<ThreadBase> thread = mThread.promote();
4727 if (thread != 0) {
4728 if (!isOutputTrack()) {
4729 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004730 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004731
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004732#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004733 // to track the speaker usage
4734 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004735#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 }
4737 AudioSystem::releaseOutput(thread->id());
4738 }
4739 Mutex::Autolock _l(thread->mLock);
4740 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4741 playbackThread->destroyTrack_l(this);
4742 }
4743 }
4744}
4745
Glenn Kasten288ed212012-04-25 17:52:27 -07004746/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4747{
Glenn Kastene213c862012-04-25 13:46:15 -07004748 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 -07004749 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004750}
4751
Mathias Agopian65ab4712010-07-14 17:59:35 -07004752void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4753{
Glenn Kasten83d86532012-01-17 14:39:34 -08004754 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004755 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004756 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004757 } else {
4758 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4759 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004760 track_state state = mState;
4761 char stateChar;
4762 switch (state) {
4763 case IDLE:
4764 stateChar = 'I';
4765 break;
4766 case TERMINATED:
4767 stateChar = 'T';
4768 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004769 case STOPPING_1:
4770 stateChar = 's';
4771 break;
4772 case STOPPING_2:
4773 stateChar = '5';
4774 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004775 case STOPPED:
4776 stateChar = 'S';
4777 break;
4778 case RESUMING:
4779 stateChar = 'R';
4780 break;
4781 case ACTIVE:
4782 stateChar = 'A';
4783 break;
4784 case PAUSING:
4785 stateChar = 'p';
4786 break;
4787 case PAUSED:
4788 stateChar = 'P';
4789 break;
Eric Laurent29864602012-05-08 18:57:51 -07004790 case FLUSHED:
4791 stateChar = 'F';
4792 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004793 default:
4794 stateChar = '?';
4795 break;
4796 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004797 char nowInUnderrun;
4798 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4799 case UNDERRUN_FULL:
4800 nowInUnderrun = ' ';
4801 break;
4802 case UNDERRUN_PARTIAL:
4803 nowInUnderrun = '<';
4804 break;
4805 case UNDERRUN_EMPTY:
4806 nowInUnderrun = '*';
4807 break;
4808 default:
4809 nowInUnderrun = '?';
4810 break;
4811 }
Glenn Kastene213c862012-04-25 13:46:15 -07004812 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4813 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004814 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815 mStreamType,
4816 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004817 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818 mSessionId,
4819 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004820 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004821 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822 mMute,
4823 mFillingUpStatus,
4824 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004825 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4826 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004827 mCblk->server,
4828 mCblk->user,
4829 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004830 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004831 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004832 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004833 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004834}
4835
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004836// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004837status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004838 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004840 audio_track_cblk_t* cblk = this->cblk();
4841 uint32_t framesReady;
4842 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004843
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004844 // Check if last stepServer failed, try to step now
4845 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004846 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4847 // Since the fast mixer is higher priority than client callback thread,
4848 // it does not result in priority inversion for client.
4849 // But a non-blocking solution would be preferable to avoid
4850 // fast mixer being unable to tryLock(), and
4851 // to avoid the extra context switches if the client wakes up,
4852 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004853 if (!step()) goto getNextBuffer_exit;
4854 ALOGV("stepServer recovered");
4855 mStepServerFailed = false;
4856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857
Glenn Kasten288ed212012-04-25 17:52:27 -07004858 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004859 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004861 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 uint32_t s = cblk->server;
4863 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4864
4865 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4866 if (framesReq > framesReady) {
4867 framesReq = framesReady;
4868 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004869 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 framesReq = bufferEnd - s;
4871 }
4872
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004873 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004874 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877
4878getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004879 buffer->raw = NULL;
4880 buffer->frameCount = 0;
4881 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4882 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883}
4884
Glenn Kasten288ed212012-04-25 17:52:27 -07004885// Note that framesReady() takes a mutex on the control block using tryLock().
4886// This could result in priority inversion if framesReady() is called by the normal mixer,
4887// as the normal mixer thread runs at lower
4888// priority than the client's callback thread: there is a short window within framesReady()
4889// during which the normal mixer could be preempted, and the client callback would block.
4890// Another problem can occur if framesReady() is called by the fast mixer:
4891// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4892// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4893size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004894 return mCblk->framesReady();
4895}
4896
Glenn Kasten288ed212012-04-25 17:52:27 -07004897// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004899 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900
John Grossman4ff14ba2012-02-08 16:37:41 -08004901 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004902 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4903 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004904 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 return true;
4906 }
4907 return false;
4908}
4909
Glenn Kasten3acbd052012-02-28 10:39:56 -08004910status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004911 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912{
4913 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004914 ALOGV("start(%d), calling pid %d session %d",
4915 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004916
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 sp<ThreadBase> thread = mThread.promote();
4918 if (thread != 0) {
4919 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004920 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 // here the track could be either new, or restarted
4922 // in both cases "unstop" the track
4923 if (mState == PAUSED) {
4924 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004925 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 } else {
4927 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004928 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 }
4930
4931 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4932 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004933 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004935
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004936#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004937 // to track the speaker usage
4938 if (status == NO_ERROR) {
4939 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4940 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004941#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 }
4943 if (status == NO_ERROR) {
4944 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4945 playbackThread->addTrack_l(this);
4946 } else {
4947 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004948 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 }
4950 } else {
4951 status = BAD_VALUE;
4952 }
4953 return status;
4954}
4955
4956void AudioFlinger::PlaybackThread::Track::stop()
4957{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004958 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 sp<ThreadBase> thread = mThread.promote();
4960 if (thread != 0) {
4961 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004962 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004963 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964 // If the track is not active (PAUSED and buffers full), flush buffers
4965 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4966 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4967 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004968 mState = STOPPED;
4969 } else if (!isFastTrack()) {
4970 mState = STOPPED;
4971 } else {
4972 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4973 // and then to STOPPED and reset() when presentation is complete
4974 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004976 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 }
4978 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4979 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004980 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004982
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004983#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004984 // to track the speaker usage
4985 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004986#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 }
4988 }
4989}
4990
4991void AudioFlinger::PlaybackThread::Track::pause()
4992{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004993 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 sp<ThreadBase> thread = mThread.promote();
4995 if (thread != 0) {
4996 Mutex::Autolock _l(thread->mLock);
4997 if (mState == ACTIVE || mState == RESUMING) {
4998 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004999 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000 if (!isOutputTrack()) {
5001 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005002 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005004
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005005#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005006 // to track the speaker usage
5007 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005008#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 }
5010 }
5011 }
5012}
5013
5014void AudioFlinger::PlaybackThread::Track::flush()
5015{
Steve Block3856b092011-10-20 11:56:00 +01005016 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 sp<ThreadBase> thread = mThread.promote();
5018 if (thread != 0) {
5019 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005020 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005021 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022 return;
5023 }
5024 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005025 // FLUSHED state
5026 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005027 // do not reset the track if it is still in the process of being stopped or paused.
5028 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005029 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005030 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005031 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5032 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5033 reset();
5034 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 }
5036}
5037
5038void AudioFlinger::PlaybackThread::Track::reset()
5039{
5040 // Do not reset twice to avoid discarding data written just after a flush and before
5041 // the audioflinger thread detects the track is stopped.
5042 if (!mResetDone) {
5043 TrackBase::reset();
5044 // Force underrun condition to avoid false underrun callback until first data is
5045 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005046 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5047 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 mFillingUpStatus = FS_FILLING;
5049 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005050 if (mState == FLUSHED) {
5051 mState = IDLE;
5052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053 }
5054}
5055
5056void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5057{
5058 mMute = muted;
5059}
5060
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5062{
5063 status_t status = DEAD_OBJECT;
5064 sp<ThreadBase> thread = mThread.promote();
5065 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005066 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005067 sp<AudioFlinger> af = mClient->audioFlinger();
5068
5069 Mutex::Autolock _l(af->mLock);
5070
5071 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005072
Eric Laurent109347d2012-07-02 12:31:03 -07005073 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005074 Mutex::Autolock _dl(playbackThread->mLock);
5075 Mutex::Autolock _sl(srcThread->mLock);
5076 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5077 if (chain == 0) {
5078 return INVALID_OPERATION;
5079 }
5080
5081 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5082 if (effect == 0) {
5083 return INVALID_OPERATION;
5084 }
5085 srcThread->removeEffect_l(effect);
5086 playbackThread->addEffect_l(effect);
5087 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5088 if (effect->state() == EffectModule::ACTIVE ||
5089 effect->state() == EffectModule::STOPPING) {
5090 effect->start();
5091 }
5092
5093 sp<EffectChain> dstChain = effect->chain().promote();
5094 if (dstChain == 0) {
5095 srcThread->addEffect_l(effect);
5096 return INVALID_OPERATION;
5097 }
5098 AudioSystem::unregisterEffect(effect->id());
5099 AudioSystem::registerEffect(&effect->desc(),
5100 srcThread->id(),
5101 dstChain->strategy(),
5102 AUDIO_SESSION_OUTPUT_MIX,
5103 effect->id());
5104 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005105 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 }
5107 return status;
5108}
5109
5110void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5111{
5112 mAuxEffectId = EffectId;
5113 mAuxBuffer = buffer;
5114}
5115
Eric Laurenta011e352012-03-29 15:51:43 -07005116bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5117 size_t audioHalFrames)
5118{
5119 // a track is considered presented when the total number of frames written to audio HAL
5120 // corresponds to the number of frames written when presentationComplete() is called for the
5121 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5122 if (mPresentationCompleteFrames == 0) {
5123 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5124 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5125 mPresentationCompleteFrames, audioHalFrames);
5126 }
5127 if (framesWritten >= mPresentationCompleteFrames) {
5128 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5129 mSessionId, framesWritten);
5130 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005131 return true;
5132 }
5133 return false;
5134}
5135
5136void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5137{
5138 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5139 if (mSyncEvents[i]->type() == type) {
5140 mSyncEvents[i]->trigger();
5141 mSyncEvents.removeAt(i);
5142 i--;
5143 }
5144 }
5145}
5146
Glenn Kasten58912562012-04-03 10:45:00 -07005147// implement VolumeBufferProvider interface
5148
5149uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5150{
5151 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5152 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5153 uint32_t vlr = mCblk->getVolumeLR();
5154 uint32_t vl = vlr & 0xFFFF;
5155 uint32_t vr = vlr >> 16;
5156 // track volumes come from shared memory, so can't be trusted and must be clamped
5157 if (vl > MAX_GAIN_INT) {
5158 vl = MAX_GAIN_INT;
5159 }
5160 if (vr > MAX_GAIN_INT) {
5161 vr = MAX_GAIN_INT;
5162 }
5163 // now apply the cached master volume and stream type volume;
5164 // this is trusted but lacks any synchronization or barrier so may be stale
5165 float v = mCachedVolume;
5166 vl *= v;
5167 vr *= v;
5168 // re-combine into U4.16
5169 vlr = (vr << 16) | (vl & 0xFFFF);
5170 // FIXME look at mute, pause, and stop flags
5171 return vlr;
5172}
Eric Laurenta011e352012-03-29 15:51:43 -07005173
Eric Laurent29864602012-05-08 18:57:51 -07005174status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5175{
5176 if (mState == TERMINATED || mState == PAUSED ||
5177 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5178 (mState == STOPPED)))) {
5179 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5180 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5181 event->cancel();
5182 return INVALID_OPERATION;
5183 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005184 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005185 return NO_ERROR;
5186}
5187
John Grossman4ff14ba2012-02-08 16:37:41 -08005188// timed audio tracks
5189
5190sp<AudioFlinger::PlaybackThread::TimedTrack>
5191AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005192 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005193 const sp<Client>& client,
5194 audio_stream_type_t streamType,
5195 uint32_t sampleRate,
5196 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005197 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005198 int frameCount,
5199 const sp<IMemory>& sharedBuffer,
5200 int sessionId) {
5201 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005202 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005203
Glenn Kastena0356762012-03-19 10:38:51 -07005204 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5206 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005207}
5208
5209AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005210 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005211 const sp<Client>& client,
5212 audio_stream_type_t streamType,
5213 uint32_t sampleRate,
5214 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005215 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 int frameCount,
5217 const sp<IMemory>& sharedBuffer,
5218 int sessionId)
5219 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005220 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005221 mQueueHeadInFlight(false),
5222 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005223 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005224 mTimedSilenceBuffer(NULL),
5225 mTimedSilenceBufferSize(0),
5226 mTimedAudioOutputOnTime(false),
5227 mMediaTimeTransformValid(false)
5228{
5229 LocalClock lc;
5230 mLocalTimeFreq = lc.getLocalFreq();
5231
5232 mLocalTimeToSampleTransform.a_zero = 0;
5233 mLocalTimeToSampleTransform.b_zero = 0;
5234 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5235 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5236 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5237 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005238
5239 mMediaTimeToSampleTransform.a_zero = 0;
5240 mMediaTimeToSampleTransform.b_zero = 0;
5241 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5242 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5243 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5244 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005245}
5246
5247AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5248 mClient->releaseTimedTrack();
5249 delete [] mTimedSilenceBuffer;
5250}
5251
5252status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5253 size_t size, sp<IMemory>* buffer) {
5254
5255 Mutex::Autolock _l(mTimedBufferQueueLock);
5256
5257 trimTimedBufferQueue_l();
5258
5259 // lazily initialize the shared memory heap for timed buffers
5260 if (mTimedMemoryDealer == NULL) {
5261 const int kTimedBufferHeapSize = 512 << 10;
5262
5263 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5264 "AudioFlingerTimed");
5265 if (mTimedMemoryDealer == NULL)
5266 return NO_MEMORY;
5267 }
5268
5269 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5270 if (newBuffer == NULL) {
5271 newBuffer = mTimedMemoryDealer->allocate(size);
5272 if (newBuffer == NULL)
5273 return NO_MEMORY;
5274 }
5275
5276 *buffer = newBuffer;
5277 return NO_ERROR;
5278}
5279
5280// caller must hold mTimedBufferQueueLock
5281void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5282 int64_t mediaTimeNow;
5283 {
5284 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5285 if (!mMediaTimeTransformValid)
5286 return;
5287
5288 int64_t targetTimeNow;
5289 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5290 ? mCCHelper.getCommonTime(&targetTimeNow)
5291 : mCCHelper.getLocalTime(&targetTimeNow);
5292
5293 if (OK != res)
5294 return;
5295
5296 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5297 &mediaTimeNow)) {
5298 return;
5299 }
5300 }
5301
John Grossman1c345192012-03-27 14:00:17 -07005302 size_t trimEnd;
5303 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005304 int64_t bufEnd;
5305
John Grossmanc95cfbb2012-04-12 11:53:11 -07005306 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5307 // We have a next buffer. Just use its PTS as the PTS of the frame
5308 // following the last frame in this buffer. If the stream is sparse
5309 // (ie, there are deliberate gaps left in the stream which should be
5310 // filled with silence by the TimedAudioTrack), then this can result
5311 // in one extra buffer being left un-trimmed when it could have
5312 // been. In general, this is not typical, and we would rather
5313 // optimized away the TS calculation below for the more common case
5314 // where PTSes are contiguous.
5315 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5316 } else {
5317 // We have no next buffer. Compute the PTS of the frame following
5318 // the last frame in this buffer by computing the duration of of
5319 // this frame in media time units and adding it to the PTS of the
5320 // buffer.
5321 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5322 / mCblk->frameSize;
5323
5324 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5325 &bufEnd)) {
5326 ALOGE("Failed to convert frame count of %lld to media time"
5327 " duration" " (scale factor %d/%u) in %s",
5328 frameCount,
5329 mMediaTimeToSampleTransform.a_to_b_numer,
5330 mMediaTimeToSampleTransform.a_to_b_denom,
5331 __PRETTY_FUNCTION__);
5332 break;
5333 }
5334 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005335 }
John Grossman9fbdee12012-03-26 17:51:46 -07005336
5337 if (bufEnd > mediaTimeNow)
5338 break;
5339
5340 // Is the buffer we want to use in the middle of a mix operation right
5341 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5342 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005343 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005344 mTrimQueueHeadOnRelease = true;
5345 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005346 }
5347
John Grossman9fbdee12012-03-26 17:51:46 -07005348 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005349 if (trimStart < trimEnd) {
5350 // Update the bookkeeping for framesReady()
5351 for (size_t i = trimStart; i < trimEnd; ++i) {
5352 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5353 }
5354
5355 // Now actually remove the buffers from the queue.
5356 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005357 }
5358}
5359
John Grossman1c345192012-03-27 14:00:17 -07005360void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5361 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005362 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5363 "%s called (reason \"%s\"), but timed buffer queue has no"
5364 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005365
5366 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5367 mTimedBufferQueue.removeAt(0);
5368}
5369
5370void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5371 const TimedBuffer& buf,
5372 const char* logTag) {
5373 uint32_t bufBytes = buf.buffer()->size();
5374 uint32_t consumedAlready = buf.position();
5375
Eric Laurentb388e532012-04-14 13:32:48 -07005376 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005377 "Bad bookkeeping while updating frames pending. Timed buffer is"
5378 " only %u bytes long, but claims to have consumed %u"
5379 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005380 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005381
5382 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005383 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5384 "Bad bookkeeping while updating frames pending. Should have at"
5385 " least %u queued frames, but we think we have only %u. (update"
5386 " reason: \"%s\")",
5387 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005388
5389 mFramesPendingInQueue -= bufFrames;
5390}
5391
John Grossman4ff14ba2012-02-08 16:37:41 -08005392status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5393 const sp<IMemory>& buffer, int64_t pts) {
5394
5395 {
5396 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5397 if (!mMediaTimeTransformValid)
5398 return INVALID_OPERATION;
5399 }
5400
5401 Mutex::Autolock _l(mTimedBufferQueueLock);
5402
John Grossman1c345192012-03-27 14:00:17 -07005403 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5404 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005405 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5406
5407 return NO_ERROR;
5408}
5409
5410status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5411 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5412
John Grossman1c345192012-03-27 14:00:17 -07005413 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5414 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5415 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005416
5417 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5418 target == TimedAudioTrack::COMMON_TIME)) {
5419 return BAD_VALUE;
5420 }
5421
5422 Mutex::Autolock lock(mMediaTimeTransformLock);
5423 mMediaTimeTransform = xform;
5424 mMediaTimeTransformTarget = target;
5425 mMediaTimeTransformValid = true;
5426
5427 return NO_ERROR;
5428}
5429
5430#define min(a, b) ((a) < (b) ? (a) : (b))
5431
5432// implementation of getNextBuffer for tracks whose buffers have timestamps
5433status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5434 AudioBufferProvider::Buffer* buffer, int64_t pts)
5435{
5436 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005437 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005438 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005439 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005440 return INVALID_OPERATION;
5441 }
5442
John Grossman4ff14ba2012-02-08 16:37:41 -08005443 Mutex::Autolock _l(mTimedBufferQueueLock);
5444
John Grossman9fbdee12012-03-26 17:51:46 -07005445 ALOG_ASSERT(!mQueueHeadInFlight,
5446 "getNextBuffer called without releaseBuffer!");
5447
John Grossman4ff14ba2012-02-08 16:37:41 -08005448 while (true) {
5449
5450 // if we have no timed buffers, then fail
5451 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005452 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005453 buffer->frameCount = 0;
5454 return NOT_ENOUGH_DATA;
5455 }
5456
5457 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5458
5459 // calculate the PTS of the head of the timed buffer queue expressed in
5460 // local time
5461 int64_t headLocalPTS;
5462 {
5463 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5464
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005465 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005466
5467 if (mMediaTimeTransform.a_to_b_denom == 0) {
5468 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005469 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005470 return NO_ERROR;
5471 }
5472
5473 int64_t transformedPTS;
5474 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5475 &transformedPTS)) {
5476 // the transform failed. this shouldn't happen, but if it does
5477 // then just drop this buffer
5478 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005479 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005480 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005481 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005482 return NO_ERROR;
5483 }
5484
5485 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5486 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5487 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005488 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005489 buffer->frameCount = 0;
5490 return INVALID_OPERATION;
5491 }
5492 } else {
5493 headLocalPTS = transformedPTS;
5494 }
5495 }
5496
5497 // adjust the head buffer's PTS to reflect the portion of the head buffer
5498 // that has already been consumed
5499 int64_t effectivePTS = headLocalPTS +
5500 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5501
5502 // Calculate the delta in samples between the head of the input buffer
5503 // queue and the start of the next output buffer that will be written.
5504 // If the transformation fails because of over or underflow, it means
5505 // that the sample's position in the output stream is so far out of
5506 // whack that it should just be dropped.
5507 int64_t sampleDelta;
5508 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5509 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005510 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5511 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005512 continue;
5513 }
5514 if (!mLocalTimeToSampleTransform.doForwardTransform(
5515 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005516 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005517 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005518 continue;
5519 }
5520
John Grossman1c345192012-03-27 14:00:17 -07005521 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5522 " sampleDelta=[%d.%08x]",
5523 head.pts(), head.position(), pts,
5524 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5525 + (sampleDelta >> 32)),
5526 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005527
5528 // if the delta between the ideal placement for the next input sample and
5529 // the current output position is within this threshold, then we will
5530 // concatenate the next input samples to the previous output
5531 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005532 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005533
5534 // if this is the first buffer of audio that we're emitting from this track
5535 // then it should be almost exactly on time.
5536 const int64_t kSampleStartupThreshold = 1LL << 32;
5537
5538 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005539 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005540 // the next input is close enough to being on time, so concatenate it
5541 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005542 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005543
John Grossman1c345192012-03-27 14:00:17 -07005544 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5545 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005546 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005547 }
5548
5549 // Looks like our output is not on time. Reset our on timed status.
5550 // Next time we mix samples from our input queue, then should be within
5551 // the StartupThreshold.
5552 mTimedAudioOutputOnTime = false;
5553 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005554 // the gap between the current output position and the proper start of
5555 // the next input sample is too big, so fill it with silence
5556 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5557
John Grossman9fbdee12012-03-26 17:51:46 -07005558 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005559 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5560 return NO_ERROR;
5561 } else {
5562 // the next input sample is late
5563 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5564 size_t onTimeSamplePosition =
5565 head.position() + lateFrames * mCblk->frameSize;
5566
5567 if (onTimeSamplePosition > head.buffer()->size()) {
5568 // all the remaining samples in the head are too late, so
5569 // drop it and move on
5570 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005571 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005572 continue;
5573 } else {
5574 // skip over the late samples
5575 head.setPosition(onTimeSamplePosition);
5576
5577 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005578 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005579
5580 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5581 return NO_ERROR;
5582 }
5583 }
5584 }
5585}
5586
5587// Yield samples from the timed buffer queue head up to the given output
5588// buffer's capacity.
5589//
5590// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005591void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005592 AudioBufferProvider::Buffer* buffer) {
5593
5594 const TimedBuffer& head = mTimedBufferQueue[0];
5595
5596 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5597 head.position());
5598
5599 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5600 mCblk->frameSize);
5601 size_t framesRequested = buffer->frameCount;
5602 buffer->frameCount = min(framesLeftInHead, framesRequested);
5603
John Grossman9fbdee12012-03-26 17:51:46 -07005604 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005605 mTimedAudioOutputOnTime = true;
5606}
5607
5608// Yield samples of silence up to the given output buffer's capacity
5609//
5610// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005611void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005612 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5613
5614 // lazily allocate a buffer filled with silence
5615 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5616 delete [] mTimedSilenceBuffer;
5617 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5618 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5619 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5620 }
5621
5622 buffer->raw = mTimedSilenceBuffer;
5623 size_t framesRequested = buffer->frameCount;
5624 buffer->frameCount = min(numFrames, framesRequested);
5625
5626 mTimedAudioOutputOnTime = false;
5627}
5628
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005629// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005630void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5631 AudioBufferProvider::Buffer* buffer) {
5632
5633 Mutex::Autolock _l(mTimedBufferQueueLock);
5634
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005635 // If the buffer which was just released is part of the buffer at the head
5636 // of the queue, be sure to update the amt of the buffer which has been
5637 // consumed. If the buffer being returned is not part of the head of the
5638 // queue, its either because the buffer is part of the silence buffer, or
5639 // because the head of the timed queue was trimmed after the mixer called
5640 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005641 if (buffer->raw == mTimedSilenceBuffer) {
5642 ALOG_ASSERT(!mQueueHeadInFlight,
5643 "Queue head in flight during release of silence buffer!");
5644 goto done;
5645 }
5646
5647 ALOG_ASSERT(mQueueHeadInFlight,
5648 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5649 " head in flight.");
5650
5651 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005652 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005653
5654 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005655 void* end = reinterpret_cast<void*>(
5656 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5657 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005658
John Grossman9fbdee12012-03-26 17:51:46 -07005659 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5660 "released buffer not within the head of the timed buffer"
5661 " queue; qHead = [%p, %p], released buffer = %p",
5662 start, end, buffer->raw);
5663
5664 head.setPosition(head.position() +
5665 (buffer->frameCount * mCblk->frameSize));
5666 mQueueHeadInFlight = false;
5667
John Grossman1c345192012-03-27 14:00:17 -07005668 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5669 "Bad bookkeeping during releaseBuffer! Should have at"
5670 " least %u queued frames, but we think we have only %u",
5671 buffer->frameCount, mFramesPendingInQueue);
5672
5673 mFramesPendingInQueue -= buffer->frameCount;
5674
John Grossman9fbdee12012-03-26 17:51:46 -07005675 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5676 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005677 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005678 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005679 }
John Grossman9fbdee12012-03-26 17:51:46 -07005680 } else {
5681 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5682 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005683 }
5684
John Grossman9fbdee12012-03-26 17:51:46 -07005685done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005686 buffer->raw = 0;
5687 buffer->frameCount = 0;
5688}
5689
Glenn Kasten288ed212012-04-25 17:52:27 -07005690size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005691 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005692 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005693}
5694
5695AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5696 : mPTS(0), mPosition(0) {}
5697
5698AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5699 const sp<IMemory>& buffer, int64_t pts)
5700 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5701
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702// ----------------------------------------------------------------------------
5703
5704// RecordTrack constructor must be called with AudioFlinger::mLock held
5705AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005706 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 const sp<Client>& client,
5708 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005709 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005710 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 int sessionId)
5713 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005714 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 mOverflow(false)
5716{
5717 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005718 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5719 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5720 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5721 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5722 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5723 } else {
5724 mCblk->frameSize = sizeof(int8_t);
5725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 }
5727}
5728
5729AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5730{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005731 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005734// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005735status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736{
5737 audio_track_cblk_t* cblk = this->cblk();
5738 uint32_t framesAvail;
5739 uint32_t framesReq = buffer->frameCount;
5740
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005741 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005742 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005744 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005745 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 }
5747
5748 framesAvail = cblk->framesAvailable_l();
5749
Glenn Kastenf6b16782011-12-15 09:51:17 -08005750 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751 uint32_t s = cblk->server;
5752 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5753
5754 if (framesReq > framesAvail) {
5755 framesReq = framesAvail;
5756 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005757 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 framesReq = bufferEnd - s;
5759 }
5760
5761 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 buffer->frameCount = framesReq;
5763 return NO_ERROR;
5764 }
5765
5766getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005767 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768 buffer->frameCount = 0;
5769 return NOT_ENOUGH_DATA;
5770}
5771
Glenn Kasten3acbd052012-02-28 10:39:56 -08005772status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005773 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774{
5775 sp<ThreadBase> thread = mThread.promote();
5776 if (thread != 0) {
5777 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005778 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 } else {
5780 return BAD_VALUE;
5781 }
5782}
5783
5784void AudioFlinger::RecordThread::RecordTrack::stop()
5785{
5786 sp<ThreadBase> thread = mThread.promote();
5787 if (thread != 0) {
5788 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005789 recordThread->mLock.lock();
5790 bool doStop = recordThread->stop_l(this);
5791 if (doStop) {
5792 TrackBase::reset();
5793 // Force overrun condition to avoid false overrun callback until first data is
5794 // read from buffer
5795 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5796 }
5797 recordThread->mLock.unlock();
5798 if (doStop) {
5799 AudioSystem::stopInput(recordThread->id());
5800 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 }
5802}
5803
Glenn Kasten510a3d62012-07-16 14:24:34 -07005804/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5805{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005806 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005807}
5808
Mathias Agopian65ab4712010-07-14 17:59:35 -07005809void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5810{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005811 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005812 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005814 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 mSessionId,
5816 mFrameCount,
5817 mState,
5818 mCblk->sampleRate,
5819 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005820 mCblk->user,
5821 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822}
5823
5824
5825// ----------------------------------------------------------------------------
5826
5827AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005828 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 DuplicatingThread *sourceThread,
5830 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005831 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005832 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005834 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5835 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 mActive(false), mSourceThread(sourceThread)
5837{
5838
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 if (mCblk != NULL) {
5840 mCblk->flags |= CBLK_DIRECTION_OUT;
5841 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 mOutBuffer.frameCount = 0;
5843 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005844 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005845 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5846 mCblk, mBuffer, mCblk->buffers,
5847 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005849 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 }
5851}
5852
5853AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5854{
5855 clearBufferQueue();
5856}
5857
Glenn Kasten3acbd052012-02-28 10:39:56 -08005858status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005859 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005861 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 if (status != NO_ERROR) {
5863 return status;
5864 }
5865
5866 mActive = true;
5867 mRetryCount = 127;
5868 return status;
5869}
5870
5871void AudioFlinger::PlaybackThread::OutputTrack::stop()
5872{
5873 Track::stop();
5874 clearBufferQueue();
5875 mOutBuffer.frameCount = 0;
5876 mActive = false;
5877}
5878
5879bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5880{
5881 Buffer *pInBuffer;
5882 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005883 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 bool outputBufferFull = false;
5885 inBuffer.frameCount = frames;
5886 inBuffer.i16 = data;
5887
5888 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5889
5890 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005891 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 sp<ThreadBase> thread = mThread.promote();
5893 if (thread != 0) {
5894 MixerThread *mixerThread = (MixerThread *)thread.get();
5895 if (mCblk->frameCount > frames){
5896 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5897 uint32_t startFrames = (mCblk->frameCount - frames);
5898 pInBuffer = new Buffer;
5899 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5900 pInBuffer->frameCount = startFrames;
5901 pInBuffer->i16 = pInBuffer->mBuffer;
5902 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5903 mBufferQueue.add(pInBuffer);
5904 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005905 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 }
5907 }
5908 }
5909 }
5910
5911 while (waitTimeLeftMs) {
5912 // First write pending buffers, then new data
5913 if (mBufferQueue.size()) {
5914 pInBuffer = mBufferQueue.itemAt(0);
5915 } else {
5916 pInBuffer = &inBuffer;
5917 }
5918
5919 if (pInBuffer->frameCount == 0) {
5920 break;
5921 }
5922
5923 if (mOutBuffer.frameCount == 0) {
5924 mOutBuffer.frameCount = pInBuffer->frameCount;
5925 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005926 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005927 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 outputBufferFull = true;
5929 break;
5930 }
5931 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5932 if (waitTimeLeftMs >= waitTimeMs) {
5933 waitTimeLeftMs -= waitTimeMs;
5934 } else {
5935 waitTimeLeftMs = 0;
5936 }
5937 }
5938
5939 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5940 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5941 mCblk->stepUser(outFrames);
5942 pInBuffer->frameCount -= outFrames;
5943 pInBuffer->i16 += outFrames * channelCount;
5944 mOutBuffer.frameCount -= outFrames;
5945 mOutBuffer.i16 += outFrames * channelCount;
5946
5947 if (pInBuffer->frameCount == 0) {
5948 if (mBufferQueue.size()) {
5949 mBufferQueue.removeAt(0);
5950 delete [] pInBuffer->mBuffer;
5951 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005952 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 } else {
5954 break;
5955 }
5956 }
5957 }
5958
5959 // If we could not write all frames, allocate a buffer and queue it for next time.
5960 if (inBuffer.frameCount) {
5961 sp<ThreadBase> thread = mThread.promote();
5962 if (thread != 0 && !thread->standby()) {
5963 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5964 pInBuffer = new Buffer;
5965 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5966 pInBuffer->frameCount = inBuffer.frameCount;
5967 pInBuffer->i16 = pInBuffer->mBuffer;
5968 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5969 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005970 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005972 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 }
5974 }
5975 }
5976
5977 // Calling write() with a 0 length buffer, means that no more data will be written:
5978 // If no more buffers are pending, fill output track buffer to make sure it is started
5979 // by output mixer.
5980 if (frames == 0 && mBufferQueue.size() == 0) {
5981 if (mCblk->user < mCblk->frameCount) {
5982 frames = mCblk->frameCount - mCblk->user;
5983 pInBuffer = new Buffer;
5984 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5985 pInBuffer->frameCount = frames;
5986 pInBuffer->i16 = pInBuffer->mBuffer;
5987 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5988 mBufferQueue.add(pInBuffer);
5989 } else if (mActive) {
5990 stop();
5991 }
5992 }
5993
5994 return outputBufferFull;
5995}
5996
5997status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5998{
5999 int active;
6000 status_t result;
6001 audio_track_cblk_t* cblk = mCblk;
6002 uint32_t framesReq = buffer->frameCount;
6003
Steve Block3856b092011-10-20 11:56:00 +01006004// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 buffer->frameCount = 0;
6006
6007 uint32_t framesAvail = cblk->framesAvailable();
6008
6009
6010 if (framesAvail == 0) {
6011 Mutex::Autolock _l(cblk->lock);
6012 goto start_loop_here;
6013 while (framesAvail == 0) {
6014 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006015 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006016 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006017 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 }
6019 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6020 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006021 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022 }
6023 // read the server count again
6024 start_loop_here:
6025 framesAvail = cblk->framesAvailable_l();
6026 }
6027 }
6028
6029// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006030// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031// }
6032
6033 if (framesReq > framesAvail) {
6034 framesReq = framesAvail;
6035 }
6036
6037 uint32_t u = cblk->user;
6038 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6039
Marco Nelissena1472d92012-03-30 14:36:54 -07006040 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 framesReq = bufferEnd - u;
6042 }
6043
6044 buffer->frameCount = framesReq;
6045 buffer->raw = (void *)cblk->buffer(u);
6046 return NO_ERROR;
6047}
6048
6049
6050void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6051{
6052 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053
6054 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006055 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 delete [] pBuffer->mBuffer;
6057 delete pBuffer;
6058 }
6059 mBufferQueue.clear();
6060}
6061
6062// ----------------------------------------------------------------------------
6063
6064AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6065 : RefBase(),
6066 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006067 // 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 -07006068 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006069 mPid(pid),
6070 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071{
6072 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6073}
6074
6075// Client destructor must be called with AudioFlinger::mLock held
6076AudioFlinger::Client::~Client()
6077{
6078 mAudioFlinger->removeClient_l(mPid);
6079}
6080
Glenn Kasten435dbe62012-01-30 10:15:48 -08006081sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082{
6083 return mMemoryDealer;
6084}
6085
John Grossman4ff14ba2012-02-08 16:37:41 -08006086// Reserve one of the limited slots for a timed audio track associated
6087// with this client
6088bool AudioFlinger::Client::reserveTimedTrack()
6089{
6090 const int kMaxTimedTracksPerClient = 4;
6091
6092 Mutex::Autolock _l(mTimedTrackLock);
6093
6094 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6095 ALOGW("can not create timed track - pid %d has exceeded the limit",
6096 mPid);
6097 return false;
6098 }
6099
6100 mTimedTrackCount++;
6101 return true;
6102}
6103
6104// Release a slot for a timed audio track
6105void AudioFlinger::Client::releaseTimedTrack()
6106{
6107 Mutex::Autolock _l(mTimedTrackLock);
6108 mTimedTrackCount--;
6109}
6110
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111// ----------------------------------------------------------------------------
6112
6113AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6114 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006115 sp<IBinder> binder)
6116 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117{
6118}
6119
6120AudioFlinger::NotificationClient::~NotificationClient()
6121{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122}
6123
6124void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6125{
6126 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006127 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128}
6129
6130// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006131#ifdef QCOM_HARDWARE
6132AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6133 int output, AudioSessionDescriptor *outputDesc,
6134 IDirectTrackClient* client, audio_output_flags_t outflag)
6135 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6136 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6137{
6138 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6139 createEffectThread();
6140
6141 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6142 mAudioFlinger->registerClient(mAudioFlingerClient);
6143
6144 allocateBufPool();
6145 }
6146 mDeathRecipient = new PMDeathRecipient(this);
6147 acquireWakeLock();
6148}
6149
6150AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6151 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6152 requestAndWaitForEffectsThreadExit();
6153 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6154 mAudioFlinger->deleteEffectSession();
6155 deallocateBufPool();
6156 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006157 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006158 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006159
Mingming Yin9b3dd172013-01-10 18:42:38 -08006160 {
6161 Mutex::Autolock _l(pmLock);
6162 if (mPowerManager != 0) {
6163 sp<IBinder> binder = mPowerManager->asBinder();
6164 binder->unlinkToDeath(mDeathRecipient);
6165 }
vivek mehta2192bc92012-12-04 11:46:08 -08006166 }
vivek mehta2192bc92012-12-04 11:46:08 -08006167}
6168
6169status_t AudioFlinger::DirectAudioTrack::start() {
6170 if(mIsPaused) {
6171 mIsPaused = false;
6172 mOutputDesc->stream->start(mOutputDesc->stream);
6173 }
6174 mOutputDesc->mActive = true;
6175 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6176 return NO_ERROR;
6177}
6178
6179void AudioFlinger::DirectAudioTrack::stop() {
6180 mOutputDesc->mActive = false;
6181 mOutputDesc->stream->stop(mOutputDesc->stream);
6182 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6183}
6184
6185void AudioFlinger::DirectAudioTrack::pause() {
6186 if(!mIsPaused) {
6187 mIsPaused = true;
6188 mOutputDesc->stream->pause(mOutputDesc->stream);
6189 mOutputDesc->mActive = false;
6190 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6191 }
6192}
6193
6194ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6195 ALOGV("Writing to AudioSessionOut");
6196 int isAvail = 0;
6197 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6198 if (!isAvail) {
6199 return 0;
6200 }
6201
6202 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6203 mEffectLock.lock();
6204 List<BufferInfo>::iterator it = mEffectsPool.begin();
6205 BufferInfo buf = *it;
6206 mEffectsPool.erase(it);
6207 memcpy((char *) buf.localBuf, (char *)buffer, size);
6208 buf.bytesToWrite = size;
6209 mEffectsPool.push_back(buf);
6210 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6211 mEffectLock.unlock();
6212 }
6213 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6214}
6215
6216void AudioFlinger::DirectAudioTrack::flush() {
6217 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6218 mEffectsPool.clear();
6219 mEffectsPool = mBufPool;
6220 }
6221 mOutputDesc->stream->flush(mOutputDesc->stream);
6222}
6223
6224void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6225}
6226
6227void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
Mingming Yin9b3dd172013-01-10 18:42:38 -08006228 mOutputDesc->mVolumeLeft = left;
6229 mOutputDesc->mVolumeRight = right;
vivek mehta2192bc92012-12-04 11:46:08 -08006230}
6231
6232int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6233 int64_t time;
6234 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6235 ALOGV("Timestamp %lld",time);
6236 return time;
6237}
6238
6239void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
6240 ALOGV("Notify Audio Track of EOS event");
6241 mClient->notify(DIRECT_TRACK_EOS);
6242}
6243
6244void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6245 void *dsp_buf = NULL;
6246 void *local_buf = NULL;
6247
6248 //1. get the ion buffer information
6249 struct buf_info* buf = NULL;
6250 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6251 ALOGV("get buffer info %p",buf);
6252 if (!buf) {
6253 ALOGV("buffer is NULL");
6254 return;
6255 }
6256 int nSize = buf->bufsize;
6257 int bufferCount = buf->nBufs;
6258
6259 //2. allocate the buffer pool, allocate local buffers
6260 for (int i = 0; i < bufferCount; i++) {
6261 dsp_buf = (void *)buf->buffers[i];
6262 local_buf = malloc(nSize);
6263 memset(local_buf, 0, nSize);
6264 // Store this information for internal mapping / maintanence
6265 BufferInfo buf(local_buf, dsp_buf, nSize);
6266 buf.bytesToWrite = 0;
6267 mBufPool.push_back(buf);
6268 mEffectsPool.push_back(buf);
6269
6270 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6271 }
6272 free(buf);
6273}
6274
6275void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6276
6277 //1. Deallocate the local memory
6278 //2. Remove all the buffers from bufpool
6279 while (!mBufPool.empty()) {
6280 List<BufferInfo>::iterator it = mBufPool.begin();
6281 BufferInfo &memBuffer = *it;
6282 // free the local buffer corresponding to mem buffer
6283 if (memBuffer.localBuf) {
6284 free(memBuffer.localBuf);
6285 memBuffer.localBuf = NULL;
6286 }
6287 ALOGV("Removing from bufpool");
6288 mBufPool.erase(it);
6289 }
6290}
6291
6292status_t AudioFlinger::DirectAudioTrack::onTransact(
6293 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6294{
6295 return BnDirectTrack::onTransact(code, data, reply, flags);
6296}
6297
6298void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6299 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6300 return NULL;
6301}
6302
6303void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6304 while(1) {
6305 mEffectLock.lock();
6306 if (!mEffectConfigChanged && !mKillEffectsThread) {
6307 mEffectCv.wait(mEffectLock);
6308 }
6309
6310 if(mKillEffectsThread) {
6311 mEffectLock.unlock();
6312 break;
6313 }
6314
6315 if (mEffectConfigChanged) {
6316 mEffectConfigChanged = false;
6317 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6318 it != mEffectsPool.end(); it++) {
6319 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6320 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6321 (int16_t *)it->localBuf,
6322 (int16_t *)it->dspBuf,
6323 it->bytesToWrite);
6324 if (mEffectConfigChanged) {
6325 break;
6326 }
6327 }
6328
6329 }
6330 mEffectLock.unlock();
6331 }
6332 ALOGV("Effects thread is dead");
6333 mEffectsThreadAlive = false;
6334}
6335
6336void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6337 if (!mEffectsThreadAlive)
6338 return;
6339 mKillEffectsThread = true;
6340 mEffectCv.signal();
6341 pthread_join(mEffectsThread,NULL);
6342 ALOGV("effects thread killed");
6343}
6344
6345void AudioFlinger::DirectAudioTrack::createEffectThread() {
6346 //Create the effects thread
6347 pthread_attr_t attr;
6348 pthread_attr_init(&attr);
6349 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6350 mEffectsThreadAlive = true;
6351 ALOGV("Creating Effects Thread");
6352 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6353}
6354AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6355{
6356 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6357 pBaseClass = (DirectAudioTrack*)obj;
6358}
6359
6360void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6361 pBaseClass->mAudioFlinger.clear();
6362 ALOGW("AudioFlinger server died!");
6363}
6364
6365void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6366 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6367 ALOGV("ioConfigChanged() event %d", event);
6368 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6369 ALOGV("Received notification for change in effect module");
6370 // Seek to current media time - flush the decoded buffers with the driver
6371 pBaseClass->mEffectConfigChanged = true;
6372 // Signal effects thread to re-apply effects
6373 ALOGV("Signalling Effects Thread");
6374 pBaseClass->mEffectCv.signal();
6375
6376 }
6377 ALOGV("ioConfigChanged Out");
6378}
6379
6380void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6381{
6382 Mutex::Autolock _l(pmLock);
6383
6384 if (mPowerManager == 0) {
6385 // use checkService() to avoid blocking if power service is not up yet
6386 sp<IBinder> binder =
6387 defaultServiceManager()->checkService(String16("power"));
6388 if (binder == 0) {
6389 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6390 } else {
6391 mPowerManager = interface_cast<IPowerManager>(binder);
6392 binder->linkToDeath(mDeathRecipient);
6393 }
6394 }
6395 if (mPowerManager != 0 && mWakeLockToken == 0) {
6396 sp<IBinder> binder = new BBinder();
6397 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6398 binder,
6399 String16(lockName));
6400 if (status == NO_ERROR) {
6401 mWakeLockToken = binder;
6402 }
6403 ALOGV("acquireWakeLock() status %d", status);
6404 }
6405}
6406
6407void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6408{
6409 Mutex::Autolock _l(pmLock);
6410
6411 if (mWakeLockToken != 0) {
6412 ALOGV("releaseWakeLock()");
6413 if (mPowerManager != 0) {
6414 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6415 }
6416 mWakeLockToken.clear();
6417 }
6418}
6419
6420void AudioFlinger::DirectAudioTrack::clearPowerManager()
6421{
vivek mehta2192bc92012-12-04 11:46:08 -08006422 releaseWakeLock();
Mingming Yin9b3dd172013-01-10 18:42:38 -08006423 Mutex::Autolock _l(pmLock);
vivek mehta2192bc92012-12-04 11:46:08 -08006424 mPowerManager.clear();
6425}
6426
6427void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6428{
6429 parentClass->clearPowerManager();
6430 ALOGW("power manager service died !!!");
6431}
6432#endif
6433
6434// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435
6436AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6437 : BnAudioTrack(),
6438 mTrack(track)
6439{
6440}
6441
6442AudioFlinger::TrackHandle::~TrackHandle() {
6443 // just stop the track on deletion, associated resources
6444 // will be freed from the main thread once all pending buffers have
6445 // been played. Unless it's not in the active track list, in which
6446 // case we free everything now...
6447 mTrack->destroy();
6448}
6449
Glenn Kasten90716c52012-01-26 13:40:12 -08006450sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6451 return mTrack->getCblk();
6452}
6453
Glenn Kasten3acbd052012-02-28 10:39:56 -08006454status_t AudioFlinger::TrackHandle::start() {
6455 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456}
6457
6458void AudioFlinger::TrackHandle::stop() {
6459 mTrack->stop();
6460}
6461
6462void AudioFlinger::TrackHandle::flush() {
6463 mTrack->flush();
6464}
6465
6466void AudioFlinger::TrackHandle::mute(bool e) {
6467 mTrack->mute(e);
6468}
6469
6470void AudioFlinger::TrackHandle::pause() {
6471 mTrack->pause();
6472}
6473
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6475{
6476 return mTrack->attachAuxEffect(EffectId);
6477}
6478
John Grossman4ff14ba2012-02-08 16:37:41 -08006479status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6480 sp<IMemory>* buffer) {
6481 if (!mTrack->isTimedTrack())
6482 return INVALID_OPERATION;
6483
6484 PlaybackThread::TimedTrack* tt =
6485 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6486 return tt->allocateTimedBuffer(size, buffer);
6487}
6488
6489status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6490 int64_t pts) {
6491 if (!mTrack->isTimedTrack())
6492 return INVALID_OPERATION;
6493
6494 PlaybackThread::TimedTrack* tt =
6495 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6496 return tt->queueTimedBuffer(buffer, pts);
6497}
6498
6499status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6500 const LinearTransform& xform, int target) {
6501
6502 if (!mTrack->isTimedTrack())
6503 return INVALID_OPERATION;
6504
6505 PlaybackThread::TimedTrack* tt =
6506 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6507 return tt->setMediaTimeTransform(
6508 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6509}
6510
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511status_t AudioFlinger::TrackHandle::onTransact(
6512 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6513{
6514 return BnAudioTrack::onTransact(code, data, reply, flags);
6515}
6516
6517// ----------------------------------------------------------------------------
6518
6519sp<IAudioRecord> AudioFlinger::openRecord(
6520 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006521 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006523 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006524 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006526 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006527 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 int *sessionId,
6529 status_t *status)
6530{
6531 sp<RecordThread::RecordTrack> recordTrack;
6532 sp<RecordHandle> recordHandle;
6533 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 status_t lStatus;
6535 RecordThread *thread;
6536 size_t inFrameCount;
6537 int lSessionId;
6538
6539 // check calling permissions
6540 if (!recordingAllowed()) {
6541 lStatus = PERMISSION_DENIED;
6542 goto Exit;
6543 }
6544
6545 // add client to list
6546 { // scope for mLock
6547 Mutex::Autolock _l(mLock);
6548 thread = checkRecordThread_l(input);
6549 if (thread == NULL) {
6550 lStatus = BAD_VALUE;
6551 goto Exit;
6552 }
6553
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006554 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555
6556 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006557 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 lSessionId = *sessionId;
6559 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006560 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561 if (sessionId != NULL) {
6562 *sessionId = lSessionId;
6563 }
6564 }
6565 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006566 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6567 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006569 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6571 // destructor is called by the TrackBase destructor with mLock held
6572 client.clear();
6573 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574 goto Exit;
6575 }
6576
6577 // return to handle to client
6578 recordHandle = new RecordHandle(recordTrack);
6579 lStatus = NO_ERROR;
6580
6581Exit:
6582 if (status) {
6583 *status = lStatus;
6584 }
6585 return recordHandle;
6586}
6587
6588// ----------------------------------------------------------------------------
6589
6590AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6591 : BnAudioRecord(),
6592 mRecordTrack(recordTrack)
6593{
6594}
6595
6596AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006597 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006598 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599}
6600
Glenn Kasten90716c52012-01-26 13:40:12 -08006601sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6602 return mRecordTrack->getCblk();
6603}
6604
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006605status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006606 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006607 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608}
6609
6610void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006611 stop_nonvirtual();
6612}
6613
6614void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006615 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 mRecordTrack->stop();
6617}
6618
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619status_t AudioFlinger::RecordHandle::onTransact(
6620 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6621{
6622 return BnAudioRecord::onTransact(code, data, reply, flags);
6623}
6624
6625// ----------------------------------------------------------------------------
6626
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006627AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6628 AudioStreamIn *input,
6629 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006630 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006631 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006632 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006633 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006634 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006635 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006636 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006637 mReqSampleRate(sampleRate)
6638 // mBytesRead is only meaningful while active, and so is cleared in start()
6639 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640{
Glenn Kasten480b4682012-02-28 12:30:08 -08006641 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006642
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 readInputParameters();
6644}
6645
6646
6647AudioFlinger::RecordThread::~RecordThread()
6648{
6649 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006650 delete mResampler;
6651 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652}
6653
6654void AudioFlinger::RecordThread::onFirstRef()
6655{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006656 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657}
6658
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006659status_t AudioFlinger::RecordThread::readyToRun()
6660{
6661 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006662 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006663 return status;
6664}
6665
Mathias Agopian65ab4712010-07-14 17:59:35 -07006666bool AudioFlinger::RecordThread::threadLoop()
6667{
6668 AudioBufferProvider::Buffer buffer;
6669 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006670 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671
Eric Laurent44d98482010-09-30 16:12:31 -07006672 nsecs_t lastWarning = 0;
6673
Glenn Kastene4e2a372012-07-23 12:55:09 -07006674 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006675 acquireWakeLock();
6676
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006677 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006678 bool readOnce = false;
6679
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680 // start recording
6681 while (!exitPending()) {
6682
6683 processConfigEvents();
6684
6685 { // scope for mLock
6686 Mutex::Autolock _l(mLock);
6687 checkForNewParameters_l();
6688 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006689 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690
6691 if (exitPending()) break;
6692
Eric Laurentfeb0db62011-07-22 09:04:31 -07006693 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006694 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006695 // go to sleep
6696 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006697 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006698 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 continue;
6700 }
6701 if (mActiveTrack != 0) {
6702 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006703 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704 mActiveTrack.clear();
6705 mStartStopCond.broadcast();
6706 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6707 if (mReqChannelCount != mActiveTrack->channelCount()) {
6708 mActiveTrack.clear();
6709 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006710 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 // record start succeeds only if first read from audio input
6712 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006713 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714 mActiveTrack->mState = TrackBase::ACTIVE;
6715 } else {
6716 mActiveTrack.clear();
6717 }
6718 mStartStopCond.broadcast();
6719 }
6720 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006721 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6722 removeTrack_l(mActiveTrack);
6723 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724 }
6725 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006726 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727 }
6728
6729 if (mActiveTrack != 0) {
6730 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6731 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006732 unlockEffectChains(effectChains);
6733 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 continue;
6735 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006736 for (size_t i = 0; i < effectChains.size(); i ++) {
6737 effectChains[i]->process_l();
6738 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006739
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006741 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006742 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006744 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 // no resampling
6746 while (framesOut) {
6747 size_t framesIn = mFrameCount - mRsmpInIndex;
6748 if (framesIn) {
6749 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6750 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6751 if (framesIn > framesOut)
6752 framesIn = framesOut;
6753 mRsmpInIndex += framesIn;
6754 framesOut -= framesIn;
6755 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006756 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 memcpy(dst, src, framesIn * mFrameSize);
6758 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006760 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6761 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006763 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6764 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 }
6766 }
6767 }
6768 if (framesOut && mFrameCount == mRsmpInIndex) {
6769 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006770 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006771 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 framesOut = 0;
6773 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006774 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 mRsmpInIndex = 0;
6776 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006777 if (mBytesRead <= 0) {
6778 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6779 {
6780 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 // Force input into standby so that it tries to
6782 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006783 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006784 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 }
6786 mRsmpInIndex = mFrameCount;
6787 framesOut = 0;
6788 buffer.frameCount = 0;
6789 }
6790 }
6791 }
6792 } else {
6793 // resampling
6794
6795 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6796 // alter output frame count as if we were expecting stereo samples
6797 if (mChannelCount == 1 && mReqChannelCount == 1) {
6798 framesOut >>= 1;
6799 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006800 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6802 // are 32 bit aligned which should be always true.
6803 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006804 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006806 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6807 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006809 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 }
6811
6812 }
Eric Laurenta011e352012-03-29 15:51:43 -07006813 if (mFramestoDrop == 0) {
6814 mActiveTrack->releaseBuffer(&buffer);
6815 } else {
6816 if (mFramestoDrop > 0) {
6817 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006818 if (mFramestoDrop <= 0) {
6819 clearSyncStartEvent();
6820 }
6821 } else {
6822 mFramestoDrop += buffer.frameCount;
6823 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6824 mSyncStartEvent->isCancelled()) {
6825 ALOGW("Synced record %s, session %d, trigger session %d",
6826 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6827 mActiveTrack->sessionId(),
6828 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6829 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006830 }
6831 }
6832 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006833 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834 }
6835 // client isn't retrieving buffers fast enough
6836 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006837 if (!mActiveTrack->setOverflow()) {
6838 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006839 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006840 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006841 lastWarning = now;
6842 }
6843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 // Release the processor for a while before asking for a new buffer.
6845 // This will give the application more chance to read from the buffer and
6846 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006847 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 }
6849 }
Eric Laurentec437d82011-07-26 20:54:46 -07006850 // enable changes in effect chain
6851 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006852 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 }
6854
Glenn Kastene4e2a372012-07-23 12:55:09 -07006855 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856
Glenn Kasten33e6e352012-07-16 15:56:57 -07006857 {
6858 Mutex::Autolock _l(mLock);
6859 mActiveTrack.clear();
6860 mStartStopCond.broadcast();
6861 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862
Eric Laurentfeb0db62011-07-22 09:04:31 -07006863 releaseWakeLock();
6864
Steve Block3856b092011-10-20 11:56:00 +01006865 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 return false;
6867}
6868
Glenn Kastene4e2a372012-07-23 12:55:09 -07006869void AudioFlinger::RecordThread::standby()
6870{
6871 if (!mStandby) {
6872 inputStandBy();
6873 mStandby = true;
6874 }
6875}
6876
6877void AudioFlinger::RecordThread::inputStandBy()
6878{
6879 mInput->stream->common.standby(&mInput->stream->common);
6880}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006881
6882sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6883 const sp<AudioFlinger::Client>& client,
6884 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006885 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006886 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006887 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006888 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006889 IAudioFlinger::track_flags_t flags,
6890 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006891 status_t *status)
6892{
6893 sp<RecordTrack> track;
6894 status_t lStatus;
6895
6896 lStatus = initCheck();
6897 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006898 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006899 goto Exit;
6900 }
6901
Glenn Kasten1879fff2012-07-11 15:36:59 -07006902 // FIXME use flags and tid similar to createTrack_l()
6903
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006904 { // scope for mLock
6905 Mutex::Autolock _l(mLock);
6906
6907 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006908 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006909
Glenn Kasten7378ca52012-01-20 13:44:40 -08006910 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006911 lStatus = NO_MEMORY;
6912 goto Exit;
6913 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006914 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006915
Eric Laurent59bd0da2011-08-01 09:52:20 -07006916 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006917 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006918 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006919 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6920 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006921 }
6922 lStatus = NO_ERROR;
6923
6924Exit:
6925 if (status) {
6926 *status = lStatus;
6927 }
6928 return track;
6929}
6930
Eric Laurenta011e352012-03-29 15:51:43 -07006931status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006932 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006933 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934{
Glenn Kasten58912562012-04-03 10:45:00 -07006935 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006936 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006938
6939 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006940 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006941 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6942 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6943 triggerSession,
6944 recordTrack->sessionId(),
6945 syncStartEventCallback,
6946 this);
Eric Laurent29864602012-05-08 18:57:51 -07006947 // Sync event can be cancelled by the trigger session if the track is not in a
6948 // compatible state in which case we start record immediately
6949 if (mSyncStartEvent->isCancelled()) {
6950 clearSyncStartEvent();
6951 } else {
6952 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6953 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6954 }
Eric Laurenta011e352012-03-29 15:51:43 -07006955 }
6956
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006958 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 if (mActiveTrack != 0) {
6960 if (recordTrack != mActiveTrack.get()) {
6961 status = -EBUSY;
6962 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6963 mActiveTrack->mState = TrackBase::ACTIVE;
6964 }
6965 return status;
6966 }
6967
6968 recordTrack->mState = TrackBase::IDLE;
6969 mActiveTrack = recordTrack;
6970 mLock.unlock();
6971 status_t status = AudioSystem::startInput(mId);
6972 mLock.lock();
6973 if (status != NO_ERROR) {
6974 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006975 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 return status;
6977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 mRsmpInIndex = mFrameCount;
6979 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006980 if (mResampler != NULL) {
6981 mResampler->reset();
6982 }
6983 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006985 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006986 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006988 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 mActiveTrack.clear();
6990 status = INVALID_OPERATION;
6991 goto startError;
6992 }
6993 mStartStopCond.wait(mLock);
6994 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006995 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 status = BAD_VALUE;
6997 goto startError;
6998 }
Steve Block3856b092011-10-20 11:56:00 +01006999 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000 return status;
7001 }
7002startError:
7003 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07007004 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 return status;
7006}
7007
Eric Laurenta011e352012-03-29 15:51:43 -07007008void AudioFlinger::RecordThread::clearSyncStartEvent()
7009{
7010 if (mSyncStartEvent != 0) {
7011 mSyncStartEvent->cancel();
7012 }
7013 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007014 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007015}
7016
7017void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7018{
7019 sp<SyncEvent> strongEvent = event.promote();
7020
7021 if (strongEvent != 0) {
7022 RecordThread *me = (RecordThread *)strongEvent->cookie();
7023 me->handleSyncStartEvent(strongEvent);
7024 }
7025}
7026
7027void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7028{
Eric Laurent29864602012-05-08 18:57:51 -07007029 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007030 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7031 // from audio HAL
7032 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007033 }
7034}
7035
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007036bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007037 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007038 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7039 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007041 recordTrack->mState = TrackBase::PAUSING;
7042 // do not wait for mStartStopCond if exiting
7043 if (exitPending()) {
7044 return true;
7045 }
7046 mStartStopCond.wait(mLock);
7047 // if we have been restarted, recordTrack == mActiveTrack.get() here
7048 if (exitPending() || recordTrack != mActiveTrack.get()) {
7049 ALOGV("Record stopped OK");
7050 return true;
7051 }
7052 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053}
7054
Glenn Kasten106e8a42012-08-02 13:37:12 -07007055bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007056{
7057 return false;
7058}
7059
7060status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7061{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007062#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 -07007063 if (!isValidSyncEvent(event)) {
7064 return BAD_VALUE;
7065 }
7066
Glenn Kasten510a3d62012-07-16 14:24:34 -07007067 int eventSession = event->triggerSession();
7068 status_t ret = NAME_NOT_FOUND;
7069
Eric Laurenta011e352012-03-29 15:51:43 -07007070 Mutex::Autolock _l(mLock);
7071
Glenn Kasten510a3d62012-07-16 14:24:34 -07007072 for (size_t i = 0; i < mTracks.size(); i++) {
7073 sp<RecordTrack> track = mTracks[i];
7074 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007075 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007076 ret = NO_ERROR;
7077 }
Eric Laurenta011e352012-03-29 15:51:43 -07007078 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007079 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007080#else
7081 return BAD_VALUE;
7082#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007083}
7084
7085void AudioFlinger::RecordThread::RecordTrack::destroy()
7086{
7087 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7088 sp<RecordTrack> keep(this);
7089 {
7090 sp<ThreadBase> thread = mThread.promote();
7091 if (thread != 0) {
7092 if (mState == ACTIVE || mState == RESUMING) {
7093 AudioSystem::stopInput(thread->id());
7094 }
7095 AudioSystem::releaseInput(thread->id());
7096 Mutex::Autolock _l(thread->mLock);
7097 RecordThread *recordThread = (RecordThread *) thread.get();
7098 recordThread->destroyTrack_l(this);
7099 }
7100 }
7101}
7102
7103// destroyTrack_l() must be called with ThreadBase::mLock held
7104void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7105{
7106 track->mState = TrackBase::TERMINATED;
7107 // active tracks are removed by threadLoop()
7108 if (mActiveTrack != track) {
7109 removeTrack_l(track);
7110 }
7111}
7112
7113void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7114{
7115 mTracks.remove(track);
7116 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007117}
7118
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007119void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007121 dumpInternals(fd, args);
7122 dumpTracks(fd, args);
7123 dumpEffectChains(fd, args);
7124}
7125
7126void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7127{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128 const size_t SIZE = 256;
7129 char buffer[SIZE];
7130 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131
7132 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7133 result.append(buffer);
7134
7135 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7137 result.append(buffer);
7138 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7139 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007140 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007141 result.append(buffer);
7142 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7143 result.append(buffer);
7144 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7145 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007147 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007149
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150 write(fd, result.string(), result.size());
7151
7152 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007153}
7154
7155void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7156{
7157 const size_t SIZE = 256;
7158 char buffer[SIZE];
7159 String8 result;
7160
7161 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7162 result.append(buffer);
7163 RecordTrack::appendDumpHeader(result);
7164 for (size_t i = 0; i < mTracks.size(); ++i) {
7165 sp<RecordTrack> track = mTracks[i];
7166 if (track != 0) {
7167 track->dump(buffer, SIZE);
7168 result.append(buffer);
7169 }
7170 }
7171
7172 if (mActiveTrack != 0) {
7173 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7174 result.append(buffer);
7175 RecordTrack::appendDumpHeader(result);
7176 mActiveTrack->dump(buffer, SIZE);
7177 result.append(buffer);
7178
7179 }
7180 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181}
7182
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007183// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007184status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185{
7186 size_t framesReq = buffer->frameCount;
7187 size_t framesReady = mFrameCount - mRsmpInIndex;
7188 int channelCount;
7189
7190 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007191 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007192 if (mBytesRead <= 0) {
7193 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7194 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195 // Force input into standby so that it tries to
7196 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007197 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007198 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007200 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201 buffer->frameCount = 0;
7202 return NOT_ENOUGH_DATA;
7203 }
7204 mRsmpInIndex = 0;
7205 framesReady = mFrameCount;
7206 }
7207
7208 if (framesReq > framesReady) {
7209 framesReq = framesReady;
7210 }
7211
7212 if (mChannelCount == 1 && mReqChannelCount == 2) {
7213 channelCount = 1;
7214 } else {
7215 channelCount = 2;
7216 }
7217 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7218 buffer->frameCount = framesReq;
7219 return NO_ERROR;
7220}
7221
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007222// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007223void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7224{
7225 mRsmpInIndex += buffer->frameCount;
7226 buffer->frameCount = 0;
7227}
7228
7229bool AudioFlinger::RecordThread::checkForNewParameters_l()
7230{
7231 bool reconfig = false;
7232
7233 while (!mNewParameters.isEmpty()) {
7234 status_t status = NO_ERROR;
7235 String8 keyValuePair = mNewParameters[0];
7236 AudioParameter param = AudioParameter(keyValuePair);
7237 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007238 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007239 int reqSamplingRate = mReqSampleRate;
7240 int reqChannelCount = mReqChannelCount;
7241
7242 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7243 reqSamplingRate = value;
7244 reconfig = true;
7245 }
7246 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007247 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248 reconfig = true;
7249 }
7250 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007251 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252 reconfig = true;
7253 }
7254 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7255 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007256 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257 // if frame count is changed after track creation
7258 if (mActiveTrack != 0) {
7259 status = INVALID_OPERATION;
7260 } else {
7261 reconfig = true;
7262 }
7263 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007264 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7265 // forward device change to effects that have requested to be
7266 // aware of attached audio device.
7267 for (size_t i = 0; i < mEffectChains.size(); i++) {
7268 mEffectChains[i]->setDevice_l(value);
7269 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007270
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007271 // store input device and output device but do not forward output device to audio HAL.
7272 // Note that status is ignored by the caller for output device
7273 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007274 if (audio_is_output_devices(value)) {
7275 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007276 status = BAD_VALUE;
7277 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007278 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007279 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007280 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007281 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7282 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007283 for (size_t i = 0; i < mTracks.size(); i++) {
7284 sp<RecordTrack> track = mTracks[i];
7285 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7286 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7287 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007288 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007289 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007290 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007291 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7292 mAudioSource != (audio_source_t)value) {
7293 // forward device change to effects that have requested to be
7294 // aware of attached audio device.
7295 for (size_t i = 0; i < mEffectChains.size(); i++) {
7296 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7297 }
7298 mAudioSource = (audio_source_t)value;
7299 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007301 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007303 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007304 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7305 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306 }
7307 if (reconfig) {
7308 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007309 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007310 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007311 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007312 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007313 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 status = NO_ERROR;
7315 }
7316 if (status == NO_ERROR) {
7317 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007318 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 }
7320 }
7321 }
7322
7323 mNewParameters.removeAt(0);
7324
7325 mParamStatus = status;
7326 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007327 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7328 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007329 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 }
7331 return reconfig;
7332}
7333
7334String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7335{
Dima Zavinfce7a472011-04-19 22:30:36 -07007336 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007337 String8 out_s8 = String8();
7338
7339 Mutex::Autolock _l(mLock);
7340 if (initCheck() != NO_ERROR) {
7341 return out_s8;
7342 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007343
Dima Zavin799a70e2011-04-18 16:57:27 -07007344 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007345 out_s8 = String8(s);
7346 free(s);
7347 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348}
7349
7350void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7351 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007352 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353
7354 switch (event) {
7355 case AudioSystem::INPUT_OPENED:
7356 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007357 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 desc.samplingRate = mSampleRate;
7359 desc.format = mFormat;
7360 desc.frameCount = mFrameCount;
7361 desc.latency = 0;
7362 param2 = &desc;
7363 break;
7364
7365 case AudioSystem::INPUT_CLOSED:
7366 default:
7367 break;
7368 }
7369 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7370}
7371
7372void AudioFlinger::RecordThread::readInputParameters()
7373{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007374 delete mRsmpInBuffer;
7375 // mRsmpInBuffer is always assigned a new[] below
7376 delete mRsmpOutBuffer;
7377 mRsmpOutBuffer = NULL;
7378 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007379 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380
Dima Zavin799a70e2011-04-18 16:57:27 -07007381 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007382 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007383 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007384 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007385 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007386 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007388 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7390
Glenn Kasten53d76db2012-03-08 12:32:47 -08007391 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 {
7393 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007394 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7395 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396 if (mChannelCount == 1 && mReqChannelCount == 2) {
7397 channelCount = 1;
7398 } else {
7399 channelCount = 2;
7400 }
7401 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7402 mResampler->setSampleRate(mSampleRate);
7403 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7404 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7405
7406 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7407 if (mChannelCount == 1 && mReqChannelCount == 1) {
7408 mFrameCount >>= 1;
7409 }
7410
7411 }
7412 mRsmpInIndex = mFrameCount;
7413}
7414
7415unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7416{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007417 Mutex::Autolock _l(mLock);
7418 if (initCheck() != NO_ERROR) {
7419 return 0;
7420 }
7421
Dima Zavin799a70e2011-04-18 16:57:27 -07007422 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007423}
7424
Glenn Kasten106e8a42012-08-02 13:37:12 -07007425uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426{
7427 Mutex::Autolock _l(mLock);
7428 uint32_t result = 0;
7429 if (getEffectChain_l(sessionId) != 0) {
7430 result = EFFECT_SESSION;
7431 }
7432
Glenn Kasten510a3d62012-07-16 14:24:34 -07007433 for (size_t i = 0; i < mTracks.size(); ++i) {
7434 if (sessionId == mTracks[i]->sessionId()) {
7435 result |= TRACK_SESSION;
7436 break;
7437 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007438 }
7439
7440 return result;
7441}
7442
Glenn Kasten106e8a42012-08-02 13:37:12 -07007443KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007444{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007445 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007446 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007447 for (size_t j = 0; j < mTracks.size(); ++j) {
7448 sp<RecordThread::RecordTrack> track = mTracks[j];
7449 int sessionId = track->sessionId();
7450 if (ids.indexOfKey(sessionId) < 0) {
7451 ids.add(sessionId, true);
7452 }
7453 }
7454 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007455}
7456
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007457AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7458{
7459 Mutex::Autolock _l(mLock);
7460 AudioStreamIn *input = mInput;
7461 mInput = NULL;
7462 return input;
7463}
7464
7465// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007466audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007467{
7468 if (mInput == NULL) {
7469 return NULL;
7470 }
7471 return &mInput->stream->common;
7472}
7473
7474
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475// ----------------------------------------------------------------------------
7476
Eric Laurenta4c5a552012-03-29 10:12:40 -07007477audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7478{
7479 if (!settingsAllowed()) {
7480 return 0;
7481 }
7482 Mutex::Autolock _l(mLock);
7483 return loadHwModule_l(name);
7484}
7485
7486// loadHwModule_l() must be called with AudioFlinger::mLock held
7487audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7488{
7489 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7490 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7491 ALOGW("loadHwModule() module %s already loaded", name);
7492 return mAudioHwDevs.keyAt(i);
7493 }
7494 }
7495
Eric Laurenta4c5a552012-03-29 10:12:40 -07007496 audio_hw_device_t *dev;
7497
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007498 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007499 if (rc) {
7500 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7501 return 0;
7502 }
7503
7504 mHardwareStatus = AUDIO_HW_INIT;
7505 rc = dev->init_check(dev);
7506 mHardwareStatus = AUDIO_HW_IDLE;
7507 if (rc) {
7508 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7509 return 0;
7510 }
7511
John Grossmanee578c02012-07-23 17:05:46 -07007512 // Check and cache this HAL's level of support for master mute and master
7513 // volume. If this is the first HAL opened, and it supports the get
7514 // methods, use the initial values provided by the HAL as the current
7515 // master mute and volume settings.
7516
7517 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7518 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007519 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007520
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007521#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007522 if (0 == mAudioHwDevs.size()) {
7523 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7524 if (NULL != dev->get_master_volume) {
7525 float mv;
7526 if (OK == dev->get_master_volume(dev, &mv)) {
7527 mMasterVolume = mv;
7528 }
7529 }
7530
7531 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7532 if (NULL != dev->get_master_mute) {
7533 bool mm;
7534 if (OK == dev->get_master_mute(dev, &mm)) {
7535 mMasterMute = mm;
7536 }
7537 }
7538 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007539#endif
John Grossmanee578c02012-07-23 17:05:46 -07007540
Eric Laurenta4c5a552012-03-29 10:12:40 -07007541 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007542 if ((NULL != dev->set_master_volume) &&
7543 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7544 flags = static_cast<AudioHwDevice::Flags>(flags |
7545 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7546 }
7547
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007548#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007549 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7550 if ((NULL != dev->set_master_mute) &&
7551 (OK == dev->set_master_mute(dev, mMasterMute))) {
7552 flags = static_cast<AudioHwDevice::Flags>(flags |
7553 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7554 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007555#endif
John Grossmanee578c02012-07-23 17:05:46 -07007556
Eric Laurenta4c5a552012-03-29 10:12:40 -07007557 mHardwareStatus = AUDIO_HW_IDLE;
7558 }
7559
7560 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007561 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007562
7563 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007564 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007565
7566 return handle;
7567
7568}
7569
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007570// ----------------------------------------------------------------------------
7571
7572int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7573{
7574 Mutex::Autolock _l(mLock);
7575 PlaybackThread *thread = primaryPlaybackThread_l();
7576 return thread != NULL ? thread->sampleRate() : 0;
7577}
7578
7579int32_t AudioFlinger::getPrimaryOutputFrameCount()
7580{
7581 Mutex::Autolock _l(mLock);
7582 PlaybackThread *thread = primaryPlaybackThread_l();
7583 return thread != NULL ? thread->frameCountHAL() : 0;
7584}
7585
7586// ----------------------------------------------------------------------------
7587
Eric Laurenta4c5a552012-03-29 10:12:40 -07007588audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7589 audio_devices_t *pDevices,
7590 uint32_t *pSamplingRate,
7591 audio_format_t *pFormat,
7592 audio_channel_mask_t *pChannelMask,
7593 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007594 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595{
7596 status_t status;
7597 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007598 struct audio_config config = {
7599 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7600 channel_mask: pChannelMask ? *pChannelMask : 0,
7601 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7602 };
7603 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007604 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605
Eric Laurenta4c5a552012-03-29 10:12:40 -07007606 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7607 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007608 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007609 config.sample_rate,
7610 config.format,
7611 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007612 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613
7614 if (pDevices == NULL || *pDevices == 0) {
7615 return 0;
7616 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007617
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618 Mutex::Autolock _l(mLock);
7619
Eric Laurenta4c5a552012-03-29 10:12:40 -07007620 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007621 if (outHwDev == NULL)
7622 return 0;
7623
John Grossmanee578c02012-07-23 17:05:46 -07007624 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007625 audio_io_handle_t id = nextUniqueId();
7626
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007627 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007628
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007629#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007630 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007631 id,
7632 *pDevices,
7633 (audio_output_flags_t)flags,
7634 &config,
7635 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007636#else
7637 status = hwDevHal->open_output_stream(hwDevHal,
7638 *pDevices,
7639 (int *)&config.format,
7640 &config.channel_mask,
7641 &config.sample_rate,
7642 &outStream);
7643 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7644 flags = (audio_output_flags_t)newflags;
7645#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007646
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007647 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007648 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007649 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007650 config.sample_rate,
7651 config.format,
7652 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653 status);
7654
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007655 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007656 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007657#ifdef QCOM_HARDWARE
7658 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7659 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7660 desc->mActive = true;
7661 //TODO: no stream type
7662 //desc->mStreamType = streamType;
7663 desc->mVolumeLeft = 1.0;
7664 desc->mVolumeRight = 1.0;
7665 desc->device = *pDevices;
7666 mDirectAudioTracks.add(id, desc);
7667 } else
7668#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007669 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007670 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7671 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674 } else {
7675 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007676 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677 }
vivek mehta2192bc92012-12-04 11:46:08 -08007678#ifdef QCOM_HARDWARE
7679 if (thread != NULL)
7680#endif
7681 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007683 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7684 if (pFormat != NULL) *pFormat = config.format;
7685 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007686#ifdef QCOM_HARDWARE
7687 if (thread != NULL) {
7688#endif
7689 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7690 // notify client processes of the new output creation
7691 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7692#ifdef QCOM_HARDWARE
7693 }
7694 else {
7695 *pLatencyMs = 0;
7696 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7697 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7698 *pLatencyMs = desc->stream->get_latency(desc->stream);
7699 }
7700 }
7701#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007702 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007703 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007704 ALOGI("Using module %d has the primary audio interface", module);
7705 mPrimaryHardwareDev = outHwDev;
7706
7707 AutoMutex lock(mHardwareLock);
7708 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007709 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007710 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007711 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712 return id;
7713 }
7714
7715 return 0;
7716}
7717
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007718audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7719 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720{
7721 Mutex::Autolock _l(mLock);
7722 MixerThread *thread1 = checkMixerThread_l(output1);
7723 MixerThread *thread2 = checkMixerThread_l(output2);
7724
7725 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007726 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 return 0;
7728 }
7729
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007730 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7732 thread->addOutputTrack(thread2);
7733 mPlaybackThreads.add(id, thread);
7734 // notify client processes of the new output creation
7735 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7736 return id;
7737}
7738
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007739status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740{
Glenn Kastend96c5722012-04-25 13:44:49 -07007741 return closeOutput_nonvirtual(output);
7742}
7743
7744status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7745{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746 // keep strong reference on the playback thread so that
7747 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007748#ifdef QCOM_HARDWARE
7749 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7750 if (desc) {
7751 ALOGV("Closing DirectTrack output %d", output);
7752 desc->mActive = false;
7753 desc->stream->common.standby(&desc->stream->common);
7754 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7755 desc->trackRefPtr = NULL;
7756 mDirectAudioTracks.removeItem(output);
7757 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7758 delete desc;
7759 return NO_ERROR;
7760 }
7761#endif
7762
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007763 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 {
7765 Mutex::Autolock _l(mLock);
7766 thread = checkPlaybackThread_l(output);
7767 if (thread == NULL) {
7768 return BAD_VALUE;
7769 }
7770
Steve Block3856b092011-10-20 11:56:00 +01007771 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007773 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007775 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7777 dupThread->removeOutputTrack((MixerThread *)thread.get());
7778 }
7779 }
7780 }
Glenn Kastena1117922012-01-26 10:53:32 -08007781 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 mPlaybackThreads.removeItem(output);
7783 }
7784 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007785 // The thread entity (active unit of execution) is no longer running here,
7786 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007788 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007789 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007790 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007791 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007792 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007793 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 }
7795 return NO_ERROR;
7796}
7797
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007798status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799{
7800 Mutex::Autolock _l(mLock);
7801 PlaybackThread *thread = checkPlaybackThread_l(output);
7802
7803 if (thread == NULL) {
7804 return BAD_VALUE;
7805 }
7806
Steve Block3856b092011-10-20 11:56:00 +01007807 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007808 thread->suspend();
7809
7810 return NO_ERROR;
7811}
7812
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007813status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814{
7815 Mutex::Autolock _l(mLock);
7816 PlaybackThread *thread = checkPlaybackThread_l(output);
7817
7818 if (thread == NULL) {
7819 return BAD_VALUE;
7820 }
7821
Steve Block3856b092011-10-20 11:56:00 +01007822 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823
7824 thread->restore();
7825
7826 return NO_ERROR;
7827}
7828
Eric Laurenta4c5a552012-03-29 10:12:40 -07007829audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7830 audio_devices_t *pDevices,
7831 uint32_t *pSamplingRate,
7832 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007833 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834{
7835 status_t status;
7836 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007837 struct audio_config config = {
7838 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7839 channel_mask: pChannelMask ? *pChannelMask : 0,
7840 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7841 };
7842 uint32_t reqSamplingRate = config.sample_rate;
7843 audio_format_t reqFormat = config.format;
7844 audio_channel_mask_t reqChannels = config.channel_mask;
7845 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007846 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847
7848 if (pDevices == NULL || *pDevices == 0) {
7849 return 0;
7850 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007851
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 Mutex::Autolock _l(mLock);
7853
Eric Laurenta4c5a552012-03-29 10:12:40 -07007854 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007855 if (inHwDev == NULL)
7856 return 0;
7857
John Grossmanee578c02012-07-23 17:05:46 -07007858 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007859 audio_io_handle_t id = nextUniqueId();
7860
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007861#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007862 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007863 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007864#else
7865 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7866 (int *)&config.format,
7867 &config.channel_mask,
7868 &config.sample_rate, (audio_in_acoustics_t)0,
7869 &inStream);
7870#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007871 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007872 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007873 config.sample_rate,
7874 config.format,
7875 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 status);
7877
7878 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7879 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7880 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007881 if (status == BAD_VALUE &&
7882 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7883 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007884 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007885 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007886 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007887#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007888 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007889#else
7890 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7891 (int *)&config.format,
7892 &config.channel_mask,
7893 &config.sample_rate, (audio_in_acoustics_t)0,
7894 &inStream);
7895#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 }
7897
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007898 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007899 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7900
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007901 // Start record thread
7902 // RecorThread require both input and output device indication to forward to audio
7903 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007904 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007905 thread = new RecordThread(this,
7906 input,
7907 reqSamplingRate,
7908 reqChannels,
7909 id,
7910 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007912 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007913 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007914 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007915 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917 // notify client processes of the new input creation
7918 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7919 return id;
7920 }
7921
7922 return 0;
7923}
7924
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007925status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007926{
Glenn Kastend96c5722012-04-25 13:44:49 -07007927 return closeInput_nonvirtual(input);
7928}
7929
7930status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7931{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 // keep strong reference on the record thread so that
7933 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007934 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 {
7936 Mutex::Autolock _l(mLock);
7937 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007938 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939 return BAD_VALUE;
7940 }
7941
Steve Block3856b092011-10-20 11:56:00 +01007942 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007943 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 mRecordThreads.removeItem(input);
7945 }
7946 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007947 // The thread entity (active unit of execution) is no longer running here,
7948 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007950 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007951 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007952 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007953 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007954 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955
7956 return NO_ERROR;
7957}
7958
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007959status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960{
7961 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007962 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007963
7964 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7965 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007966 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968
7969 return NO_ERROR;
7970}
7971
7972
7973int AudioFlinger::newAudioSessionId()
7974{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007975 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976}
7977
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007978void AudioFlinger::acquireAudioSessionId(int audioSession)
7979{
7980 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007981 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007982 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007983 size_t num = mAudioSessionRefs.size();
7984 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007985 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007986 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7987 ref->mCnt++;
7988 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007989 return;
7990 }
7991 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007992 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7993 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007994}
7995
7996void AudioFlinger::releaseAudioSessionId(int audioSession)
7997{
7998 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007999 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008000 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008001 size_t num = mAudioSessionRefs.size();
8002 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008003 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008004 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8005 ref->mCnt--;
8006 ALOGV(" decremented refcount to %d", ref->mCnt);
8007 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008008 mAudioSessionRefs.removeAt(i);
8009 delete ref;
8010 purgeStaleEffects_l();
8011 }
8012 return;
8013 }
8014 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008015 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008016}
8017
8018void AudioFlinger::purgeStaleEffects_l() {
8019
Steve Block3856b092011-10-20 11:56:00 +01008020 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008021
8022 Vector< sp<EffectChain> > chains;
8023
8024 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8025 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8026 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8027 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008028 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8029 chains.push(ec);
8030 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008031 }
8032 }
8033 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8034 sp<RecordThread> t = mRecordThreads.valueAt(i);
8035 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8036 sp<EffectChain> ec = t->mEffectChains[j];
8037 chains.push(ec);
8038 }
8039 }
8040
8041 for (size_t i = 0; i < chains.size(); i++) {
8042 sp<EffectChain> ec = chains[i];
8043 int sessionid = ec->sessionId();
8044 sp<ThreadBase> t = ec->mThread.promote();
8045 if (t == 0) {
8046 continue;
8047 }
8048 size_t numsessionrefs = mAudioSessionRefs.size();
8049 bool found = false;
8050 for (size_t k = 0; k < numsessionrefs; k++) {
8051 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008052 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008053 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008054 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008055 found = true;
8056 break;
8057 }
8058 }
8059 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008060 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008061 // remove all effects from the chain
8062 while (ec->mEffects.size()) {
8063 sp<EffectModule> effect = ec->mEffects[0];
8064 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008065 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008066 if (effect->purgeHandles()) {
8067 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008068 }
8069 AudioSystem::unregisterEffect(effect->id());
8070 }
8071 }
8072 }
8073 return;
8074}
8075
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008077AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078{
Glenn Kastena1117922012-01-26 10:53:32 -08008079 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080}
8081
8082// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008083AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084{
8085 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008086 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087}
8088
8089// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008090AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091{
Glenn Kastena1117922012-01-26 10:53:32 -08008092 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093}
8094
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008095uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008097 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098}
8099
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008100AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008101{
8102 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8103 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008104 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008105 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008106 return thread;
8107 }
8108 }
8109 return NULL;
8110}
8111
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008112audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008113{
8114 PlaybackThread *thread = primaryPlaybackThread_l();
8115
8116 if (thread == NULL) {
8117 return 0;
8118 }
8119
Eric Laurentf1c04f92012-08-28 14:26:53 -07008120 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008121}
8122
Eric Laurenta011e352012-03-29 15:51:43 -07008123sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8124 int triggerSession,
8125 int listenerSession,
8126 sync_event_callback_t callBack,
8127 void *cookie)
8128{
8129 Mutex::Autolock _l(mLock);
8130
8131 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8132 status_t playStatus = NAME_NOT_FOUND;
8133 status_t recStatus = NAME_NOT_FOUND;
8134 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8135 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8136 if (playStatus == NO_ERROR) {
8137 return event;
8138 }
8139 }
8140 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8141 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8142 if (recStatus == NO_ERROR) {
8143 return event;
8144 }
8145 }
8146 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8147 mPendingSyncEvents.add(event);
8148 } else {
8149 ALOGV("createSyncEvent() invalid event %d", event->type());
8150 event.clear();
8151 }
8152 return event;
8153}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008154
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155// ----------------------------------------------------------------------------
8156// Effect management
8157// ----------------------------------------------------------------------------
8158
8159
Glenn Kastenf587ba52012-01-26 16:25:10 -08008160status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161{
8162 Mutex::Autolock _l(mLock);
8163 return EffectQueryNumberEffects(numEffects);
8164}
8165
Glenn Kastenf587ba52012-01-26 16:25:10 -08008166status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167{
8168 Mutex::Autolock _l(mLock);
8169 return EffectQueryEffect(index, descriptor);
8170}
8171
Glenn Kasten5e92a782012-01-30 07:40:52 -08008172status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008173 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174{
8175 Mutex::Autolock _l(mLock);
8176 return EffectGetDescriptor(pUuid, descriptor);
8177}
8178
8179
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8181 effect_descriptor_t *pDesc,
8182 const sp<IEffectClient>& effectClient,
8183 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008184 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 int sessionId,
8186 status_t *status,
8187 int *id,
8188 int *enabled)
8189{
8190 status_t lStatus = NO_ERROR;
8191 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008192 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008193
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008194 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008195 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196
8197 if (pDesc == NULL) {
8198 lStatus = BAD_VALUE;
8199 goto Exit;
8200 }
8201
Eric Laurent84e9a102010-09-23 16:10:16 -07008202 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008203 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008204 lStatus = PERMISSION_DENIED;
8205 goto Exit;
8206 }
8207
Dima Zavinfce7a472011-04-19 22:30:36 -07008208 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008209 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008210 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008211 lStatus = PERMISSION_DENIED;
8212 goto Exit;
8213 }
8214
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008215 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008216 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008217 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008218 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008219 lStatus = BAD_VALUE;
8220 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008221 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008222 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008223 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008224 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008225 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008226 }
8227 }
8228
Mathias Agopian65ab4712010-07-14 17:59:35 -07008229 {
8230 Mutex::Autolock _l(mLock);
8231
Mathias Agopian65ab4712010-07-14 17:59:35 -07008232
8233 if (!EffectIsNullUuid(&pDesc->uuid)) {
8234 // if uuid is specified, request effect descriptor
8235 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8236 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008237 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008238 goto Exit;
8239 }
8240 } else {
8241 // if uuid is not specified, look for an available implementation
8242 // of the required type in effect factory
8243 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008244 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 lStatus = BAD_VALUE;
8246 goto Exit;
8247 }
8248 uint32_t numEffects = 0;
8249 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008250 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008251 bool found = false;
8252
8253 lStatus = EffectQueryNumberEffects(&numEffects);
8254 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008255 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 goto Exit;
8257 }
8258 for (uint32_t i = 0; i < numEffects; i++) {
8259 lStatus = EffectQueryEffect(i, &desc);
8260 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008261 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 continue;
8263 }
8264 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8265 // If matching type found save effect descriptor. If the session is
8266 // 0 and the effect is not auxiliary, continue enumeration in case
8267 // an auxiliary version of this effect type is available
8268 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008269 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008270 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8272 break;
8273 }
8274 }
8275 }
8276 if (!found) {
8277 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008278 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008279 goto Exit;
8280 }
8281 // For same effect type, chose auxiliary version over insert version if
8282 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008283 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008284 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008285 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286 }
8287 }
8288
8289 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008290 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8292 lStatus = INVALID_OPERATION;
8293 goto Exit;
8294 }
8295
Eric Laurent59255e42011-07-27 19:49:51 -07008296 // check recording permission for visualizer
8297 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8298 !recordingAllowed()) {
8299 lStatus = PERMISSION_DENIED;
8300 goto Exit;
8301 }
8302
Mathias Agopian65ab4712010-07-14 17:59:35 -07008303 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008304 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008305
8306 // If output is not specified try to find a matching audio session ID in one of the
8307 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008308 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8309 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008310 // Note: io is never 0 when creating an effect on an input
8311 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008312 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008313 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8314 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008315 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008316 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008319 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008320 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8321 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8322 io = mRecordThreads.keyAt(i);
8323 break;
8324 }
8325 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008326 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008327 // If no output thread contains the requested session ID, default to
8328 // first output. The effect chain will be moved to the correct output
8329 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008330 if (io == 0 && mPlaybackThreads.size()) {
8331 io = mPlaybackThreads.keyAt(0);
8332 }
Steve Block3856b092011-10-20 11:56:00 +01008333 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008334 }
8335 ThreadBase *thread = checkRecordThread_l(io);
8336 if (thread == NULL) {
8337 thread = checkPlaybackThread_l(io);
8338 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008339 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008340 lStatus = BAD_VALUE;
8341 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008342 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008343 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008344
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008345 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008347 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008348 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8349 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 if (handle != 0 && id != NULL) {
8351 *id = handle->id();
8352 }
8353 }
8354
8355Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008356 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 *status = lStatus;
8358 }
8359 return handle;
8360}
8361
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008362status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8363 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008364{
Steve Block3856b092011-10-20 11:56:00 +01008365 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008366 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008367 Mutex::Autolock _l(mLock);
8368 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008369 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008370 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371 }
Eric Laurentde070132010-07-13 04:45:46 -07008372 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8373 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008374 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008375 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 }
Eric Laurentde070132010-07-13 04:45:46 -07008377 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8378 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008379 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008380 return BAD_VALUE;
8381 }
8382
8383 Mutex::Autolock _dl(dstThread->mLock);
8384 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008385 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008386
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 return NO_ERROR;
8388}
8389
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008390// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008391status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008392 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008393 AudioFlinger::PlaybackThread *dstThread,
8394 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008395{
Steve Block3856b092011-10-20 11:56:00 +01008396 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008397 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008398
Eric Laurent59255e42011-07-27 19:49:51 -07008399 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008400 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008401 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008402 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008403 return INVALID_OPERATION;
8404 }
8405
Eric Laurent39e94f82010-07-28 01:32:47 -07008406 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008407 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008408 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008409 // removed.
8410 srcThread->removeEffectChain_l(chain);
8411
8412 // transfer all effects one by one so that new effect chain is created on new thread with
8413 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008414 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008415 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008416 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008417 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8418 while (effect != 0) {
8419 srcThread->removeEffect_l(effect);
8420 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008421 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8422 if (effect->state() == EffectModule::ACTIVE ||
8423 effect->state() == EffectModule::STOPPING) {
8424 effect->start();
8425 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008426 // if the move request is not received from audio policy manager, the effect must be
8427 // re-registered with the new strategy and output
8428 if (dstChain == 0) {
8429 dstChain = effect->chain().promote();
8430 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008431 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008432 srcThread->addEffect_l(effect);
8433 return NO_INIT;
8434 }
8435 strategy = dstChain->strategy();
8436 }
8437 if (reRegister) {
8438 AudioSystem::unregisterEffect(effect->id());
8439 AudioSystem::registerEffect(&effect->desc(),
8440 dstOutput,
8441 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008442 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008443 effect->id());
8444 }
Eric Laurentde070132010-07-13 04:45:46 -07008445 effect = chain->getEffectFromId_l(0);
8446 }
8447
8448 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008449}
8450
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008451
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008453sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454 const sp<AudioFlinger::Client>& client,
8455 const sp<IEffectClient>& effectClient,
8456 int32_t priority,
8457 int sessionId,
8458 effect_descriptor_t *desc,
8459 int *enabled,
8460 status_t *status
8461 )
8462{
8463 sp<EffectModule> effect;
8464 sp<EffectHandle> handle;
8465 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008467 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008468 bool effectCreated = false;
8469 bool effectRegistered = false;
8470
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008471 lStatus = initCheck();
8472 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008473 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008474 goto Exit;
8475 }
8476
8477 // Do not allow effects with session ID 0 on direct output or duplicating threads
8478 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008479 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008480 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008481 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008482 lStatus = BAD_VALUE;
8483 goto Exit;
8484 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008485 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008486 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008487 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008488 desc->name, desc->flags, mType);
8489 lStatus = BAD_VALUE;
8490 goto Exit;
8491 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492
Steve Block3856b092011-10-20 11:56:00 +01008493 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008494
8495 { // scope for mLock
8496 Mutex::Autolock _l(mLock);
8497
8498 // check for existing effect chain with the requested audio session
8499 chain = getEffectChain_l(sessionId);
8500 if (chain == 0) {
8501 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008502 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503 chain = new EffectChain(this, sessionId);
8504 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008505 chain->setStrategy(getStrategyForSession_l(sessionId));
8506 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008507#ifdef QCOM_HARDWARE
8508 if(sessionId == mAudioFlinger->mLPASessionId) {
8509 // Clear reference to previous effect chain if any
8510 if(mAudioFlinger->mLPAEffectChain.get()) {
8511 mAudioFlinger->mLPAEffectChain.clear();
8512 }
8513 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8514 mAudioFlinger->mLPAEffectChain = chain;
8515 chain->setLPAFlag(true);
8516 // For LPA, the volume will be applied in DSP. No need for volume
8517 // control in the Effect chain, so setting it to unity.
8518 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8519 chain->setVolume_l(&volume,&volume);
8520 }
8521#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008523 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524 }
8525
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008526 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008527
8528 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008529 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008531 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 if (lStatus != NO_ERROR) {
8533 goto Exit;
8534 }
8535 effectRegistered = true;
8536 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008537 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 lStatus = effect->status();
8539 if (lStatus != NO_ERROR) {
8540 goto Exit;
8541 }
Eric Laurentcab11242010-07-15 12:50:15 -07008542 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543 if (lStatus != NO_ERROR) {
8544 goto Exit;
8545 }
8546 effectCreated = true;
8547
Eric Laurentf1c04f92012-08-28 14:26:53 -07008548 effect->setDevice(mOutDevice);
8549 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008551 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008552#ifdef QCOM_HARDWARE
8553 if(chain == mAudioFlinger->mLPAEffectChain) {
8554 effect->setLPAFlag(true);
8555 }
8556#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557 }
8558 // create effect handle and connect it to effect module
8559 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008560 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008561 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008562 *enabled = (int)effect->isEnabled();
8563 }
8564 }
8565
8566Exit:
8567 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008568 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008570 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 }
8572 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008573 AudioSystem::unregisterEffect(effect->id());
8574 }
8575 if (chainCreated) {
8576 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577 }
8578 handle.clear();
8579 }
8580
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008581 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582 *status = lStatus;
8583 }
8584 return handle;
8585}
8586
Eric Laurent717e1282012-06-29 16:36:52 -07008587sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8588{
8589 Mutex::Autolock _l(mLock);
8590 return getEffect_l(sessionId, effectId);
8591}
8592
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008593sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8594{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008595 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008596 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008597}
8598
Eric Laurentde070132010-07-13 04:45:46 -07008599// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8600// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008601status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008602{
8603 // check for existing effect chain with the requested audio session
8604 int sessionId = effect->sessionId();
8605 sp<EffectChain> chain = getEffectChain_l(sessionId);
8606 bool chainCreated = false;
8607
8608 if (chain == 0) {
8609 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008610 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008611 chain = new EffectChain(this, sessionId);
8612 addEffectChain_l(chain);
8613 chain->setStrategy(getStrategyForSession_l(sessionId));
8614 chainCreated = true;
8615 }
Steve Block3856b092011-10-20 11:56:00 +01008616 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008617
8618 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008619 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008620 this, effect->desc().name, chain.get());
8621 return BAD_VALUE;
8622 }
8623
8624 status_t status = chain->addEffect_l(effect);
8625 if (status != NO_ERROR) {
8626 if (chainCreated) {
8627 removeEffectChain_l(chain);
8628 }
8629 return status;
8630 }
8631
Eric Laurentf1c04f92012-08-28 14:26:53 -07008632 effect->setDevice(mOutDevice);
8633 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008634 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008635 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008636 return NO_ERROR;
8637}
8638
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008639void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008640
Steve Block3856b092011-10-20 11:56:00 +01008641 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008643 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8644 detachAuxEffect_l(effect->id());
8645 }
8646
8647 sp<EffectChain> chain = effect->chain().promote();
8648 if (chain != 0) {
8649 // remove effect chain if removing last effect
8650 if (chain->removeEffect_l(effect) == 0) {
8651 removeEffectChain_l(chain);
8652 }
8653 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008654 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008655 }
8656}
8657
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008658void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008659 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008660{
8661 effectChains = mEffectChains;
8662 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008663#ifdef QCOM_HARDWARE
8664 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8665#endif
8666 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008667 }
8668}
8669
8670void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008671 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008672{
8673 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008674#ifdef QCOM_HARDWARE
8675 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8676#endif
8677 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008678 }
8679}
8680
8681sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8682{
8683 Mutex::Autolock _l(mLock);
8684 return getEffectChain_l(sessionId);
8685}
8686
Glenn Kasten106e8a42012-08-02 13:37:12 -07008687sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008688{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008689 size_t size = mEffectChains.size();
8690 for (size_t i = 0; i < size; i++) {
8691 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008692 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008693 }
8694 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008695 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008696}
8697
Glenn Kastenf78aee72012-01-04 11:00:47 -08008698void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008699{
8700 Mutex::Autolock _l(mLock);
8701 size_t size = mEffectChains.size();
8702 for (size_t i = 0; i < size; i++) {
8703 mEffectChains[i]->setMode_l(mode);
8704 }
8705}
8706
8707void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008708 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008709 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008710
Mathias Agopian65ab4712010-07-14 17:59:35 -07008711 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008712 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008713 // delete the effect module if removing last handle on it
8714 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008715 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008716 removeEffect_l(effect);
8717 AudioSystem::unregisterEffect(effect->id());
8718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719 }
8720}
8721
8722status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8723{
8724 int session = chain->sessionId();
8725 int16_t *buffer = mMixBuffer;
8726 bool ownsBuffer = false;
8727
Steve Block3856b092011-10-20 11:56:00 +01008728 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729 if (session > 0) {
8730 // Only one effect chain can be present in direct output thread and it uses
8731 // the mix buffer as input
8732 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008733 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008734 buffer = new int16_t[numSamples];
8735 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008736 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737 ownsBuffer = true;
8738 }
8739
8740 // Attach all tracks with same session ID to this chain.
8741 for (size_t i = 0; i < mTracks.size(); ++i) {
8742 sp<Track> track = mTracks[i];
8743 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008744 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008745 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008746 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747 }
8748 }
8749
8750 // indicate all active tracks in the chain
8751 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8752 sp<Track> track = mActiveTracks[i].promote();
8753 if (track == 0) continue;
8754 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008755 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008756 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757 }
8758 }
8759 }
8760
8761 chain->setInBuffer(buffer, ownsBuffer);
8762 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008763 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008764 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008765 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8766 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008768 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8769 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008770 // Effect chain for other sessions are inserted at beginning of effect
8771 // chains list to be processed before output mix effects. Relative order between other
8772 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008773 size_t size = mEffectChains.size();
8774 size_t i = 0;
8775 for (i = 0; i < size; i++) {
8776 if (mEffectChains[i]->sessionId() < session) break;
8777 }
8778 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008779 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780
8781 return NO_ERROR;
8782}
8783
8784size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8785{
8786 int session = chain->sessionId();
8787
Steve Block3856b092011-10-20 11:56:00 +01008788 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008789
8790 for (size_t i = 0; i < mEffectChains.size(); i++) {
8791 if (chain == mEffectChains[i]) {
8792 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008793 // detach all active tracks from the chain
8794 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8795 sp<Track> track = mActiveTracks[i].promote();
8796 if (track == 0) continue;
8797 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008798 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008799 chain.get(), session);
8800 chain->decActiveTrackCnt();
8801 }
8802 }
8803
Mathias Agopian65ab4712010-07-14 17:59:35 -07008804 // detach all tracks with same session ID from this chain
8805 for (size_t i = 0; i < mTracks.size(); ++i) {
8806 sp<Track> track = mTracks[i];
8807 if (session == track->sessionId()) {
8808 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008809 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 }
8811 }
Eric Laurentde070132010-07-13 04:45:46 -07008812 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 }
8814 }
8815 return mEffectChains.size();
8816}
8817
Eric Laurentde070132010-07-13 04:45:46 -07008818status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8819 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008820{
8821 Mutex::Autolock _l(mLock);
8822 return attachAuxEffect_l(track, EffectId);
8823}
8824
Eric Laurentde070132010-07-13 04:45:46 -07008825status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8826 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008827{
8828 status_t status = NO_ERROR;
8829
8830 if (EffectId == 0) {
8831 track->setAuxBuffer(0, NULL);
8832 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008833 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8834 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 if (effect != 0) {
8836 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8837 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8838 } else {
8839 status = INVALID_OPERATION;
8840 }
8841 } else {
8842 status = BAD_VALUE;
8843 }
8844 }
8845 return status;
8846}
8847
8848void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8849{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008850 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008851 sp<Track> track = mTracks[i];
8852 if (track->auxEffectId() == effectId) {
8853 attachAuxEffect_l(track, 0);
8854 }
8855 }
8856}
8857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008858status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8859{
8860 // only one chain per input thread
8861 if (mEffectChains.size() != 0) {
8862 return INVALID_OPERATION;
8863 }
Steve Block3856b092011-10-20 11:56:00 +01008864 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008865
8866 chain->setInBuffer(NULL);
8867 chain->setOutBuffer(NULL);
8868
Eric Laurent59255e42011-07-27 19:49:51 -07008869 checkSuspendOnAddEffectChain_l(chain);
8870
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008871 mEffectChains.add(chain);
8872
8873 return NO_ERROR;
8874}
8875
8876size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8877{
Steve Block3856b092011-10-20 11:56:00 +01008878 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008879 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008880 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8881 chain.get(), mEffectChains.size(), this);
8882 if (mEffectChains.size() == 1) {
8883 mEffectChains.removeAt(0);
8884 }
8885 return 0;
8886}
8887
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888// ----------------------------------------------------------------------------
8889// EffectModule implementation
8890// ----------------------------------------------------------------------------
8891
8892#undef LOG_TAG
8893#define LOG_TAG "AudioFlinger::EffectModule"
8894
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008895AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008896 const wp<AudioFlinger::EffectChain>& chain,
8897 effect_descriptor_t *desc,
8898 int id,
8899 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008900 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8901 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008902 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008903 // mConfig is set by configure() and not used before then
8904 mEffectInterface(NULL),
8905 mStatus(NO_INIT), mState(IDLE),
8906 // mMaxDisableWaitCnt is set by configure() and not used before then
8907 // mDisableWaitCnt is set by process() and updateState() and not used before then
8908 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08008909#ifdef QCOM_HARDWARE
8910 ,mIsForLPA(false)
8911#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912{
Steve Block3856b092011-10-20 11:56:00 +01008913 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008915
8916 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008917 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918
8919 if (mStatus != NO_ERROR) {
8920 return;
8921 }
8922 lStatus = init();
8923 if (lStatus < 0) {
8924 mStatus = lStatus;
8925 goto Error;
8926 }
8927
Steve Block3856b092011-10-20 11:56:00 +01008928 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929 return;
8930Error:
8931 EffectRelease(mEffectInterface);
8932 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008933 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934}
8935
8936AudioFlinger::EffectModule::~EffectModule()
8937{
Steve Block3856b092011-10-20 11:56:00 +01008938 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008940 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8941 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8942 sp<ThreadBase> thread = mThread.promote();
8943 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008944 audio_stream_t *stream = thread->stream();
8945 if (stream != NULL) {
8946 stream->remove_audio_effect(stream, mEffectInterface);
8947 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008948 }
8949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008950 // release effect engine
8951 EffectRelease(mEffectInterface);
8952 }
8953}
8954
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008955status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008956{
8957 status_t status;
8958
8959 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008960 int priority = handle->priority();
8961 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008962 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963 size_t i;
8964 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008965 EffectHandle *h = mHandles[i];
8966 if (h == NULL || h->destroyed_l()) continue;
8967 // first non destroyed handle is considered in control
8968 if (controlHandle == NULL)
8969 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970 if (h->priority() <= priority) break;
8971 }
8972 // if inserted in first place, move effect control from previous owner to this handle
8973 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008974 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008975 if (controlHandle != NULL) {
8976 enabled = controlHandle->enabled();
8977 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978 }
Eric Laurent59255e42011-07-27 19:49:51 -07008979 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 status = NO_ERROR;
8981 } else {
8982 status = ALREADY_EXISTS;
8983 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008984 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008985 mHandles.insertAt(handle, i);
8986 return status;
8987}
8988
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008989size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008990{
8991 Mutex::Autolock _l(mLock);
8992 size_t size = mHandles.size();
8993 size_t i;
8994 for (i = 0; i < size; i++) {
8995 if (mHandles[i] == handle) break;
8996 }
8997 if (i == size) {
8998 return size;
8999 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009000 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07009001
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009004 if (i == 0) {
9005 EffectHandle *h = controlHandle_l();
9006 if (h != NULL) {
9007 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 }
9009 }
9010
Eric Laurentec437d82011-07-26 20:54:46 -07009011 // Prevent calls to process() and other functions on effect interface from now on.
9012 // The effect engine will be released by the destructor when the last strong reference on
9013 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009014 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009015 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009016 }
9017
Eric Laurente65c8912012-07-20 15:57:23 -07009018 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019}
9020
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009021// must be called with EffectModule::mLock held
9022AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009023{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009024 // the first valid handle in the list has control over the module
9025 for (size_t i = 0; i < mHandles.size(); i++) {
9026 EffectHandle *h = mHandles[i];
9027 if (h != NULL && !h->destroyed_l()) {
9028 return h;
9029 }
9030 }
9031
9032 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009033}
9034
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009035size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009036{
vivek mehta2192bc92012-12-04 11:46:08 -08009037#ifdef QCOM_HARDWARE
9038 setEnabled(false);
9039#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009040 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009041 // keep a strong reference on this EffectModule to avoid calling the
9042 // destructor before we exit
9043 sp<EffectModule> keep(this);
9044 {
9045 sp<ThreadBase> thread = mThread.promote();
9046 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009047 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009048 }
9049 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009050 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051}
9052
9053void AudioFlinger::EffectModule::updateState() {
9054 Mutex::Autolock _l(mLock);
9055
9056 switch (mState) {
9057 case RESTART:
9058 reset_l();
9059 // FALL THROUGH
9060
9061 case STARTING:
9062 // clear auxiliary effect input buffer for next accumulation
9063 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9064 memset(mConfig.inputCfg.buffer.raw,
9065 0,
9066 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9067 }
9068 start_l();
9069 mState = ACTIVE;
9070 break;
9071 case STOPPING:
9072 stop_l();
9073 mDisableWaitCnt = mMaxDisableWaitCnt;
9074 mState = STOPPED;
9075 break;
9076 case STOPPED:
9077 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9078 // turn off sequence.
9079 if (--mDisableWaitCnt == 0) {
9080 reset_l();
9081 mState = IDLE;
9082 }
9083 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009084 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009085 break;
9086 }
9087}
9088
9089void AudioFlinger::EffectModule::process()
9090{
9091 Mutex::Autolock _l(mLock);
9092
Eric Laurentec437d82011-07-26 20:54:46 -07009093 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 mConfig.inputCfg.buffer.raw == NULL ||
9095 mConfig.outputCfg.buffer.raw == NULL) {
9096 return;
9097 }
9098
Eric Laurent8f45bd72010-08-31 13:50:07 -07009099 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009100 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9101 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009102 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009104 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009105 }
9106
9107 // do the actual processing in the effect engine
9108 int ret = (*mEffectInterface)->process(mEffectInterface,
9109 &mConfig.inputCfg.buffer,
9110 &mConfig.outputCfg.buffer);
9111
9112 // force transition to IDLE state when engine is ready
9113 if (mState == STOPPED && ret == -ENODATA) {
9114 mDisableWaitCnt = 1;
9115 }
9116
9117 // clear auxiliary effect input buffer for next accumulation
9118 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009119 memset(mConfig.inputCfg.buffer.raw, 0,
9120 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009121 }
9122 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009123 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9124 // If an insert effect is idle and input buffer is different from output buffer,
9125 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009126 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009127 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009128 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9129 int16_t *in = mConfig.inputCfg.buffer.s16;
9130 int16_t *out = mConfig.outputCfg.buffer.s16;
9131 for (size_t i = 0; i < frameCnt; i++) {
9132 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 }
9135 }
9136}
9137
9138void AudioFlinger::EffectModule::reset_l()
9139{
9140 if (mEffectInterface == NULL) {
9141 return;
9142 }
9143 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9144}
9145
vivek mehta2192bc92012-12-04 11:46:08 -08009146#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009147status_t AudioFlinger::EffectModule::configure()
9148{
vivek mehta2192bc92012-12-04 11:46:08 -08009149#else
9150status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9151{
9152 uint32_t channels;
9153
9154 // Acquire lock here to make sure that any other thread does not delete
9155 // the effect handle and release the effect module.
9156 Mutex::Autolock _l(mLock);
9157#endif
9158
Mathias Agopian65ab4712010-07-14 17:59:35 -07009159 if (mEffectInterface == NULL) {
9160 return NO_INIT;
9161 }
9162
9163 sp<ThreadBase> thread = mThread.promote();
9164 if (thread == 0) {
9165 return DEAD_OBJECT;
9166 }
9167
9168 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009169 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009170#ifdef QCOM_HARDWARE
9171 mIsForLPA = isForLPA;
9172 if(isForLPA) {
9173 if (channelCount == 1) {
9174 channels = AUDIO_CHANNEL_OUT_MONO;
9175 } else {
9176 channels = AUDIO_CHANNEL_OUT_STEREO;
9177 }
9178 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9179 } else {
9180 if (thread->channelCount() == 1) {
9181 channels = AUDIO_CHANNEL_OUT_MONO;
9182 } else {
9183 channels = AUDIO_CHANNEL_OUT_STEREO;
9184 }
9185 }
9186#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009187
9188 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009189 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009190 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009191 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192 }
Glenn Kasten254af182012-07-03 14:59:05 -07009193 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009194 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9195 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009196#ifdef QCOM_HARDWARE
9197 if(isForLPA){
9198 mConfig.inputCfg.samplingRate = sampleRate;
9199 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9200 } else
9201#endif
9202 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009203 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9204 mConfig.inputCfg.bufferProvider.cookie = NULL;
9205 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9206 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9207 mConfig.outputCfg.bufferProvider.cookie = NULL;
9208 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9209 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9210 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9211 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009212 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009213 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009214 // - in other sessions:
9215 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9216 // other effect: overwrites output buffer: input buffer == output buffer
9217 // Auxiliary effect:
9218 // accumulates in output buffer: input buffer != output buffer
9219 // Therefore: accumulate <=> input buffer != output buffer
9220 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9221 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9222 } else {
9223 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9224 }
9225 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9226 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009227#ifdef QCOM_HARDWARE
9228 if(isForLPA) {
9229 mConfig.inputCfg.buffer.frameCount = frameCount;
9230 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9231 } else
9232#endif
9233 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9235
Steve Block3856b092011-10-20 11:56:00 +01009236 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009237 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9238
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009240 uint32_t size = sizeof(int);
9241 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009242 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009243 sizeof(effect_config_t),
9244 &mConfig,
9245 &size,
9246 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009247 if (status == 0) {
9248 status = cmdStatus;
9249 }
9250
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009251 if (status == 0 &&
9252 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9253 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9254 effect_param_t *p = (effect_param_t *)buf32;
9255
9256 p->psize = sizeof(uint32_t);
9257 p->vsize = sizeof(uint32_t);
9258 size = sizeof(int);
9259 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9260
9261 uint32_t latency = 0;
9262 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9263 if (pbt != NULL) {
9264 latency = pbt->latency_l();
9265 }
9266
9267 *((int32_t *)p->data + 1)= latency;
9268 (*mEffectInterface)->command(mEffectInterface,
9269 EFFECT_CMD_SET_PARAM,
9270 sizeof(effect_param_t) + 8,
9271 &buf32,
9272 &size,
9273 &cmdStatus);
9274 }
9275
Mathias Agopian65ab4712010-07-14 17:59:35 -07009276 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9277 (1000 * mConfig.outputCfg.buffer.frameCount);
9278
9279 return status;
9280}
9281
9282status_t AudioFlinger::EffectModule::init()
9283{
9284 Mutex::Autolock _l(mLock);
9285 if (mEffectInterface == NULL) {
9286 return NO_INIT;
9287 }
9288 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009289 uint32_t size = sizeof(status_t);
9290 status_t status = (*mEffectInterface)->command(mEffectInterface,
9291 EFFECT_CMD_INIT,
9292 0,
9293 NULL,
9294 &size,
9295 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009296 if (status == 0) {
9297 status = cmdStatus;
9298 }
9299 return status;
9300}
9301
Eric Laurentec35a142011-10-05 17:42:25 -07009302status_t AudioFlinger::EffectModule::start()
9303{
9304 Mutex::Autolock _l(mLock);
9305 return start_l();
9306}
9307
Mathias Agopian65ab4712010-07-14 17:59:35 -07009308status_t AudioFlinger::EffectModule::start_l()
9309{
9310 if (mEffectInterface == NULL) {
9311 return NO_INIT;
9312 }
9313 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009314 uint32_t size = sizeof(status_t);
9315 status_t status = (*mEffectInterface)->command(mEffectInterface,
9316 EFFECT_CMD_ENABLE,
9317 0,
9318 NULL,
9319 &size,
9320 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009321 if (status == 0) {
9322 status = cmdStatus;
9323 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009324 if (status == 0 &&
9325 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9326 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9327 sp<ThreadBase> thread = mThread.promote();
9328 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009329 audio_stream_t *stream = thread->stream();
9330 if (stream != NULL) {
9331 stream->add_audio_effect(stream, mEffectInterface);
9332 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009333 }
9334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009335 return status;
9336}
9337
Eric Laurentec437d82011-07-26 20:54:46 -07009338status_t AudioFlinger::EffectModule::stop()
9339{
9340 Mutex::Autolock _l(mLock);
9341 return stop_l();
9342}
9343
Mathias Agopian65ab4712010-07-14 17:59:35 -07009344status_t AudioFlinger::EffectModule::stop_l()
9345{
9346 if (mEffectInterface == NULL) {
9347 return NO_INIT;
9348 }
9349 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009350 uint32_t size = sizeof(status_t);
9351 status_t status = (*mEffectInterface)->command(mEffectInterface,
9352 EFFECT_CMD_DISABLE,
9353 0,
9354 NULL,
9355 &size,
9356 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009357 if (status == 0) {
9358 status = cmdStatus;
9359 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009360 if (status == 0 &&
9361 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9362 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9363 sp<ThreadBase> thread = mThread.promote();
9364 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009365 audio_stream_t *stream = thread->stream();
9366 if (stream != NULL) {
9367 stream->remove_audio_effect(stream, mEffectInterface);
9368 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009369 }
9370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009371 return status;
9372}
9373
Eric Laurent25f43952010-07-28 05:40:18 -07009374status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9375 uint32_t cmdSize,
9376 void *pCmdData,
9377 uint32_t *replySize,
9378 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009379{
9380 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009381// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009382
Eric Laurentec437d82011-07-26 20:54:46 -07009383 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009384 return NO_INIT;
9385 }
Eric Laurent25f43952010-07-28 05:40:18 -07009386 status_t status = (*mEffectInterface)->command(mEffectInterface,
9387 cmdCode,
9388 cmdSize,
9389 pCmdData,
9390 replySize,
9391 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009392 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009393 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009394 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009395 EffectHandle *h = mHandles[i];
9396 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009397 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9398 }
9399 }
9400 }
9401 return status;
9402}
9403
9404status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9405{
9406 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009407 return setEnabled_l(enabled);
9408}
9409
9410// must be called with EffectModule::mLock held
9411status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9412{
vivek mehta2192bc92012-12-04 11:46:08 -08009413#ifdef QCOM_HARDWARE
9414 bool effectStateChanged = false;
9415#endif
Steve Block3856b092011-10-20 11:56:00 +01009416 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009417
9418 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009419#ifdef QCOM_HARDWARE
9420 effectStateChanged = true;
9421#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009422 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9423 if (enabled && status != NO_ERROR) {
9424 return status;
9425 }
9426
Mathias Agopian65ab4712010-07-14 17:59:35 -07009427 switch (mState) {
9428 // going from disabled to enabled
9429 case IDLE:
9430 mState = STARTING;
9431 break;
9432 case STOPPED:
9433 mState = RESTART;
9434 break;
9435 case STOPPING:
9436 mState = ACTIVE;
9437 break;
9438
9439 // going from enabled to disabled
9440 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009441 mState = STOPPED;
9442 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009443 case STARTING:
9444 mState = IDLE;
9445 break;
9446 case ACTIVE:
9447 mState = STOPPING;
9448 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009449 case DESTROYED:
9450 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009451 }
9452 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009453 EffectHandle *h = mHandles[i];
9454 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009455 h->setEnabled(enabled);
9456 }
9457 }
9458 }
vivek mehta2192bc92012-12-04 11:46:08 -08009459#ifdef QCOM_HARDWARE
9460 /*
9461 Send notification event to LPA Player when an effect for
9462 LPA output is enabled or disabled.
9463 */
9464 if (effectStateChanged && mIsForLPA) {
9465 sp<ThreadBase> thread = mThread.promote();
9466 thread->effectConfigChanged();
9467 }
9468#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009469 return NO_ERROR;
9470}
9471
Glenn Kastenc59c0042012-02-02 14:06:11 -08009472bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009473{
9474 switch (mState) {
9475 case RESTART:
9476 case STARTING:
9477 case ACTIVE:
9478 return true;
9479 case IDLE:
9480 case STOPPING:
9481 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009482 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009483 default:
9484 return false;
9485 }
9486}
9487
Glenn Kastenc59c0042012-02-02 14:06:11 -08009488bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009489{
9490 switch (mState) {
9491 case RESTART:
9492 case ACTIVE:
9493 case STOPPING:
9494 case STOPPED:
9495 return true;
9496 case IDLE:
9497 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009498 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009499 default:
9500 return false;
9501 }
9502}
9503
Mathias Agopian65ab4712010-07-14 17:59:35 -07009504status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9505{
9506 Mutex::Autolock _l(mLock);
9507 status_t status = NO_ERROR;
9508
9509 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9510 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009511 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009512 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9513 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009514 status_t cmdStatus;
9515 uint32_t volume[2];
9516 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009517 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009518 volume[0] = *left;
9519 volume[1] = *right;
9520 if (controller) {
9521 pVolume = volume;
9522 }
Eric Laurent25f43952010-07-28 05:40:18 -07009523 status = (*mEffectInterface)->command(mEffectInterface,
9524 EFFECT_CMD_SET_VOLUME,
9525 size,
9526 volume,
9527 &size,
9528 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009529 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9530 *left = volume[0];
9531 *right = volume[1];
9532 }
9533 }
9534 return status;
9535}
9536
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009537status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009538{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009539 if (device == AUDIO_DEVICE_NONE) {
9540 return NO_ERROR;
9541 }
9542
Mathias Agopian65ab4712010-07-14 17:59:35 -07009543 Mutex::Autolock _l(mLock);
9544 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009545 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009546 status_t cmdStatus;
9547 uint32_t size = sizeof(status_t);
9548 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9549 EFFECT_CMD_SET_INPUT_DEVICE;
9550 status = (*mEffectInterface)->command(mEffectInterface,
9551 cmd,
9552 sizeof(uint32_t),
9553 &device,
9554 &size,
9555 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009556 }
9557 return status;
9558}
9559
Glenn Kastenf78aee72012-01-04 11:00:47 -08009560status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009561{
9562 Mutex::Autolock _l(mLock);
9563 status_t status = NO_ERROR;
9564 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009566 uint32_t size = sizeof(status_t);
9567 status = (*mEffectInterface)->command(mEffectInterface,
9568 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009569 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009570 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009571 &size,
9572 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009573 if (status == NO_ERROR) {
9574 status = cmdStatus;
9575 }
9576 }
9577 return status;
9578}
9579
Eric Laurent57b2dd12012-08-31 17:44:06 -07009580status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9581{
9582 Mutex::Autolock _l(mLock);
9583 status_t status = NO_ERROR;
9584 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9585 uint32_t size = 0;
9586 status = (*mEffectInterface)->command(mEffectInterface,
9587 EFFECT_CMD_SET_AUDIO_SOURCE,
9588 sizeof(audio_source_t),
9589 &source,
9590 &size,
9591 NULL);
9592 }
9593 return status;
9594}
9595
Eric Laurent59255e42011-07-27 19:49:51 -07009596void AudioFlinger::EffectModule::setSuspended(bool suspended)
9597{
9598 Mutex::Autolock _l(mLock);
9599 mSuspended = suspended;
9600}
Glenn Kastena3a85482012-01-04 11:01:11 -08009601
9602bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009603{
9604 Mutex::Autolock _l(mLock);
9605 return mSuspended;
9606}
9607
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009608bool AudioFlinger::EffectModule::purgeHandles()
9609{
9610 bool enabled = false;
9611 Mutex::Autolock _l(mLock);
9612 for (size_t i = 0; i < mHandles.size(); i++) {
9613 EffectHandle *handle = mHandles[i];
9614 if (handle != NULL && !handle->destroyed_l()) {
9615 handle->effect().clear();
9616 if (handle->hasControl()) {
9617 enabled = handle->enabled();
9618 }
9619 }
9620 }
9621 return enabled;
9622}
9623
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009624void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009625{
9626 const size_t SIZE = 256;
9627 char buffer[SIZE];
9628 String8 result;
9629
9630 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9631 result.append(buffer);
9632
9633 bool locked = tryLock(mLock);
9634 // failed to lock - AudioFlinger is probably deadlocked
9635 if (!locked) {
9636 result.append("\t\tCould not lock Fx mutex:\n");
9637 }
9638
9639 result.append("\t\tSession Status State Engine:\n");
9640 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9641 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9642 result.append(buffer);
9643
9644 result.append("\t\tDescriptor:\n");
9645 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9646 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9647 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9648 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9649 result.append(buffer);
9650 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9651 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9652 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9653 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9654 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009655 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009656 mDescriptor.apiVersion,
9657 mDescriptor.flags);
9658 result.append(buffer);
9659 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9660 mDescriptor.name);
9661 result.append(buffer);
9662 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9663 mDescriptor.implementor);
9664 result.append(buffer);
9665
9666 result.append("\t\t- Input configuration:\n");
9667 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9668 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9669 (uint32_t)mConfig.inputCfg.buffer.raw,
9670 mConfig.inputCfg.buffer.frameCount,
9671 mConfig.inputCfg.samplingRate,
9672 mConfig.inputCfg.channels,
9673 mConfig.inputCfg.format);
9674 result.append(buffer);
9675
9676 result.append("\t\t- Output configuration:\n");
9677 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9678 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9679 (uint32_t)mConfig.outputCfg.buffer.raw,
9680 mConfig.outputCfg.buffer.frameCount,
9681 mConfig.outputCfg.samplingRate,
9682 mConfig.outputCfg.channels,
9683 mConfig.outputCfg.format);
9684 result.append(buffer);
9685
9686 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9687 result.append(buffer);
9688 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9689 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009690 EffectHandle *handle = mHandles[i];
9691 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009692 handle->dump(buffer, SIZE);
9693 result.append(buffer);
9694 }
9695 }
9696
9697 result.append("\n");
9698
9699 write(fd, result.string(), result.length());
9700
9701 if (locked) {
9702 mLock.unlock();
9703 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009704}
9705
9706// ----------------------------------------------------------------------------
9707// EffectHandle implementation
9708// ----------------------------------------------------------------------------
9709
9710#undef LOG_TAG
9711#define LOG_TAG "AudioFlinger::EffectHandle"
9712
9713AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9714 const sp<AudioFlinger::Client>& client,
9715 const sp<IEffectClient>& effectClient,
9716 int32_t priority)
9717 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009718 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009719 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009720{
Steve Block3856b092011-10-20 11:56:00 +01009721 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009722
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009723 if (client == 0) {
9724 return;
9725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009726 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9727 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9728 if (mCblkMemory != 0) {
9729 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9730
Glenn Kastena0d68332012-01-27 16:47:15 -08009731 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009732 new(mCblk) effect_param_cblk_t();
9733 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009735 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009736 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009737 return;
9738 }
9739}
9740
9741AudioFlinger::EffectHandle::~EffectHandle()
9742{
Steve Block3856b092011-10-20 11:56:00 +01009743 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009744
9745 if (mEffect == 0) {
9746 mDestroyed = true;
9747 return;
9748 }
9749 mEffect->lock();
9750 mDestroyed = true;
9751 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009752 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009753}
9754
9755status_t AudioFlinger::EffectHandle::enable()
9756{
Steve Block3856b092011-10-20 11:56:00 +01009757 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009758 if (!mHasControl) return INVALID_OPERATION;
9759 if (mEffect == 0) return DEAD_OBJECT;
9760
Eric Laurentdb7c0792011-08-10 10:37:50 -07009761 if (mEnabled) {
9762 return NO_ERROR;
9763 }
9764
Eric Laurent59255e42011-07-27 19:49:51 -07009765 mEnabled = true;
9766
9767 sp<ThreadBase> thread = mEffect->thread().promote();
9768 if (thread != 0) {
9769 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9770 }
9771
9772 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9773 if (mEffect->suspended()) {
9774 return NO_ERROR;
9775 }
9776
Eric Laurentdb7c0792011-08-10 10:37:50 -07009777 status_t status = mEffect->setEnabled(true);
9778 if (status != NO_ERROR) {
9779 if (thread != 0) {
9780 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9781 }
9782 mEnabled = false;
9783 }
9784 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009785}
9786
9787status_t AudioFlinger::EffectHandle::disable()
9788{
Steve Block3856b092011-10-20 11:56:00 +01009789 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009790 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009791 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009792
Eric Laurentdb7c0792011-08-10 10:37:50 -07009793 if (!mEnabled) {
9794 return NO_ERROR;
9795 }
Eric Laurent59255e42011-07-27 19:49:51 -07009796 mEnabled = false;
9797
9798 if (mEffect->suspended()) {
9799 return NO_ERROR;
9800 }
9801
9802 status_t status = mEffect->setEnabled(false);
9803
9804 sp<ThreadBase> thread = mEffect->thread().promote();
9805 if (thread != 0) {
9806 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9807 }
9808
9809 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009810}
9811
9812void AudioFlinger::EffectHandle::disconnect()
9813{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009814 disconnect(true);
9815}
9816
Glenn Kasten58123c32012-02-03 10:32:24 -08009817void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009818{
Glenn Kasten58123c32012-02-03 10:32:24 -08009819 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009820 if (mEffect == 0) {
9821 return;
9822 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009823 // restore suspended effects if the disconnected handle was enabled and the last one.
9824 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009825 sp<ThreadBase> thread = mEffect->thread().promote();
9826 if (thread != 0) {
9827 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9828 }
Eric Laurent59255e42011-07-27 19:49:51 -07009829 }
9830
Mathias Agopian65ab4712010-07-14 17:59:35 -07009831 // release sp on module => module destructor can be called now
9832 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009833 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009834 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009835 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009836 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9837 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009838 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009839 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009840 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9841 mClient.clear();
9842 }
9843}
9844
Eric Laurent25f43952010-07-28 05:40:18 -07009845status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9846 uint32_t cmdSize,
9847 void *pCmdData,
9848 uint32_t *replySize,
9849 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009850{
Steve Block3856b092011-10-20 11:56:00 +01009851// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009852// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009853
9854 // only get parameter command is permitted for applications not controlling the effect
9855 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9856 return INVALID_OPERATION;
9857 }
9858 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009859 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009860
9861 // handle commands that are not forwarded transparently to effect engine
9862 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9863 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9864 // no risk to block the whole media server process or mixer threads is we are stuck here
9865 Mutex::Autolock _l(mCblk->lock);
9866 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9867 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9868 mCblk->serverIndex = 0;
9869 mCblk->clientIndex = 0;
9870 return BAD_VALUE;
9871 }
9872 status_t status = NO_ERROR;
9873 while (mCblk->serverIndex < mCblk->clientIndex) {
9874 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009875 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009876 int *p = (int *)(mBuffer + mCblk->serverIndex);
9877 int size = *p++;
9878 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009879 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009880 break;
9881 }
9882 effect_param_t *param = (effect_param_t *)p;
9883 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009884 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009885 mCblk->serverIndex += size;
9886 continue;
9887 }
Eric Laurent25f43952010-07-28 05:40:18 -07009888 uint32_t psize = sizeof(effect_param_t) +
9889 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9890 param->vsize;
9891 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9892 psize,
9893 p,
9894 &rsize,
9895 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009896 // stop at first error encountered
9897 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009898 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009899 *(int *)pReplyData = reply;
9900 break;
9901 } else if (reply != NO_ERROR) {
9902 *(int *)pReplyData = reply;
9903 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009904 }
9905 mCblk->serverIndex += size;
9906 }
9907 mCblk->serverIndex = 0;
9908 mCblk->clientIndex = 0;
9909 return status;
9910 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009911 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009912 return enable();
9913 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009914 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009915 return disable();
9916 }
9917
vivek mehta2192bc92012-12-04 11:46:08 -08009918#ifdef QCOM_HARDWARE
9919 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
9920 if(mEffect->isOnLPA() &&
9921 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
9922 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
9923 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
9924 // Notify Direct track for the change in Effect module
9925 // TODO: check if it is required to send mLPAHandle
9926 ALOGV("Notifying Direct Track for the change in effect config");
9927 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
9928 }
9929#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009930 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9931}
9932
Eric Laurent59255e42011-07-27 19:49:51 -07009933void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009934{
Steve Block3856b092011-10-20 11:56:00 +01009935 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009936
9937 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009938 mEnabled = enabled;
9939
Mathias Agopian65ab4712010-07-14 17:59:35 -07009940 if (signal && mEffectClient != 0) {
9941 mEffectClient->controlStatusChanged(hasControl);
9942 }
9943}
9944
Eric Laurent25f43952010-07-28 05:40:18 -07009945void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9946 uint32_t cmdSize,
9947 void *pCmdData,
9948 uint32_t replySize,
9949 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009950{
9951 if (mEffectClient != 0) {
9952 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9953 }
9954}
9955
9956
9957
9958void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9959{
9960 if (mEffectClient != 0) {
9961 mEffectClient->enableStatusChanged(enabled);
9962 }
9963}
9964
9965status_t AudioFlinger::EffectHandle::onTransact(
9966 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9967{
9968 return BnEffect::onTransact(code, data, reply, flags);
9969}
9970
9971
9972void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9973{
Glenn Kastena0d68332012-01-27 16:47:15 -08009974 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009975
9976 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009977 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009978 mPriority,
9979 mHasControl,
9980 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009981 mCblk ? mCblk->clientIndex : 0,
9982 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009983 );
9984
9985 if (locked) {
9986 mCblk->lock.unlock();
9987 }
9988}
9989
9990#undef LOG_TAG
9991#define LOG_TAG "AudioFlinger::EffectChain"
9992
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009993AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009994 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009995 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009996 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9997 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -08009998#ifdef QCOM_HARDWARE
9999 ,mIsForLPATrack(false)
10000#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010001{
Dima Zavinfce7a472011-04-19 22:30:36 -070010002 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010003 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010004 return;
10005 }
10006 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
10007 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010008}
10009
10010AudioFlinger::EffectChain::~EffectChain()
10011{
10012 if (mOwnInBuffer) {
10013 delete mInBuffer;
10014 }
10015
10016}
10017
Eric Laurent59255e42011-07-27 19:49:51 -070010018// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010019sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010020{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010021 size_t size = mEffects.size();
10022
10023 for (size_t i = 0; i < size; i++) {
10024 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010025 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010026 }
10027 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010028 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010029}
10030
Eric Laurent59255e42011-07-27 19:49:51 -070010031// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010032sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010033{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010034 size_t size = mEffects.size();
10035
10036 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010037 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10038 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010039 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010040 }
10041 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010042 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010043}
10044
vivek mehta2192bc92012-12-04 11:46:08 -080010045#ifdef QCOM_HARDWARE
10046sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10047{
10048 sp<EffectModule> effect = NULL;
10049 if(idx < 0 || idx >= mEffects.size()) {
10050 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10051 }
10052 if(mEffects.size() > 0){
10053 effect = mEffects[idx];
10054 }
10055 return effect;
10056}
10057#endif
10058
Eric Laurent59255e42011-07-27 19:49:51 -070010059// getEffectFromType_l() must be called with ThreadBase::mLock held
10060sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10061 const effect_uuid_t *type)
10062{
Eric Laurent59255e42011-07-27 19:49:51 -070010063 size_t size = mEffects.size();
10064
10065 for (size_t i = 0; i < size; i++) {
10066 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010067 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010068 }
10069 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010070 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010071}
10072
Eric Laurent91b14c42012-05-30 12:30:29 -070010073void AudioFlinger::EffectChain::clearInputBuffer()
10074{
10075 Mutex::Autolock _l(mLock);
10076 sp<ThreadBase> thread = mThread.promote();
10077 if (thread == 0) {
10078 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10079 return;
10080 }
10081 clearInputBuffer_l(thread);
10082}
10083
10084// Must be called with EffectChain::mLock locked
10085void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10086{
10087 size_t numSamples = thread->frameCount() * thread->channelCount();
10088 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10089
10090}
10091
Mathias Agopian65ab4712010-07-14 17:59:35 -070010092// Must be called with EffectChain::mLock locked
10093void AudioFlinger::EffectChain::process_l()
10094{
Eric Laurentdac69112010-09-28 14:09:57 -070010095 sp<ThreadBase> thread = mThread.promote();
10096 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010097 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010098 return;
10099 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010100 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10101 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010102 // always process effects unless no more tracks are on the session and the effect tail
10103 // has been rendered
10104 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010105 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010106 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010107
Eric Laurent544fe9b2011-11-11 15:42:52 -080010108 if (!tracksOnSession && mTailBufferCount == 0) {
10109 doProcess = false;
10110 }
10111
10112 if (activeTrackCnt() == 0) {
10113 // if no track is active and the effect tail has not been rendered,
10114 // the input buffer must be cleared here as the mixer process will not do it
10115 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010116 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010117 if (mTailBufferCount > 0) {
10118 mTailBufferCount--;
10119 }
10120 }
10121 }
Eric Laurentdac69112010-09-28 14:09:57 -070010122 }
10123
Mathias Agopian65ab4712010-07-14 17:59:35 -070010124 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010125#ifdef QCOM_HARDWARE
10126 if (doProcess || isForLPATrack()) {
10127#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010128 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010129#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010130 for (size_t i = 0; i < size; i++) {
10131 mEffects[i]->process();
10132 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010133 }
10134 for (size_t i = 0; i < size; i++) {
10135 mEffects[i]->updateState();
10136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010137}
10138
Eric Laurentcab11242010-07-15 12:50:15 -070010139// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010140status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010141{
10142 effect_descriptor_t desc = effect->desc();
10143 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10144
10145 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010146 effect->setChain(this);
10147 sp<ThreadBase> thread = mThread.promote();
10148 if (thread == 0) {
10149 return NO_INIT;
10150 }
10151 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010152
10153 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10154 // Auxiliary effects are inserted at the beginning of mEffects vector as
10155 // they are processed first and accumulated in chain input buffer
10156 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010157
Mathias Agopian65ab4712010-07-14 17:59:35 -070010158 // the input buffer for auxiliary effect contains mono samples in
10159 // 32 bit format. This is to avoid saturation in AudoMixer
10160 // accumulation stage. Saturation is done in EffectModule::process() before
10161 // calling the process in effect engine
10162 size_t numSamples = thread->frameCount();
10163 int32_t *buffer = new int32_t[numSamples];
10164 memset(buffer, 0, numSamples * sizeof(int32_t));
10165 effect->setInBuffer((int16_t *)buffer);
10166 // auxiliary effects output samples to chain input buffer for further processing
10167 // by insert effects
10168 effect->setOutBuffer(mInBuffer);
10169 } else {
10170 // Insert effects are inserted at the end of mEffects vector as they are processed
10171 // after track and auxiliary effects.
10172 // Insert effect order as a function of indicated preference:
10173 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10174 // another effect is present
10175 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10176 // last effect claiming first position
10177 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10178 // first effect claiming last position
10179 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10180 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10181 // already present
10182
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010183 size_t size = mEffects.size();
10184 size_t idx_insert = size;
10185 ssize_t idx_insert_first = -1;
10186 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010187
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010188 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010189 effect_descriptor_t d = mEffects[i]->desc();
10190 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10191 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10192 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10193 // check invalid effect chaining combinations
10194 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10195 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010196 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010197 return INVALID_OPERATION;
10198 }
10199 // remember position of first insert effect and by default
10200 // select this as insert position for new effect
10201 if (idx_insert == size) {
10202 idx_insert = i;
10203 }
10204 // remember position of last insert effect claiming
10205 // first position
10206 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10207 idx_insert_first = i;
10208 }
10209 // remember position of first insert effect claiming
10210 // last position
10211 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10212 idx_insert_last == -1) {
10213 idx_insert_last = i;
10214 }
10215 }
10216 }
10217
10218 // modify idx_insert from first position if needed
10219 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10220 if (idx_insert_last != -1) {
10221 idx_insert = idx_insert_last;
10222 } else {
10223 idx_insert = size;
10224 }
10225 } else {
10226 if (idx_insert_first != -1) {
10227 idx_insert = idx_insert_first + 1;
10228 }
10229 }
10230
10231 // always read samples from chain input buffer
10232 effect->setInBuffer(mInBuffer);
10233
10234 // if last effect in the chain, output samples to chain
10235 // output buffer, otherwise to chain input buffer
10236 if (idx_insert == size) {
10237 if (idx_insert != 0) {
10238 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10239 mEffects[idx_insert-1]->configure();
10240 }
10241 effect->setOutBuffer(mOutBuffer);
10242 } else {
10243 effect->setOutBuffer(mInBuffer);
10244 }
10245 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010246
Steve Block3856b092011-10-20 11:56:00 +010010247 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010248 }
10249 effect->configure();
10250 return NO_ERROR;
10251}
10252
Eric Laurentcab11242010-07-15 12:50:15 -070010253// removeEffect_l() must be called with PlaybackThread::mLock held
10254size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010255{
10256 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010257 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010258 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10259
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010260 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010261 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010262 // calling stop here will remove pre-processing effect from the audio HAL.
10263 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10264 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010265 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10266 mEffects[i]->state() == EffectModule::STOPPING) {
10267 mEffects[i]->stop();
10268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010269 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10270 delete[] effect->inBuffer();
10271 } else {
10272 if (i == size - 1 && i != 0) {
10273 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10274 mEffects[i - 1]->configure();
10275 }
10276 }
10277 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010278 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010279 break;
10280 }
10281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010282
10283 return mEffects.size();
10284}
10285
Eric Laurentcab11242010-07-15 12:50:15 -070010286// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010287void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010288{
10289 size_t size = mEffects.size();
10290 for (size_t i = 0; i < size; i++) {
10291 mEffects[i]->setDevice(device);
10292 }
10293}
10294
Eric Laurentcab11242010-07-15 12:50:15 -070010295// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010296void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010297{
10298 size_t size = mEffects.size();
10299 for (size_t i = 0; i < size; i++) {
10300 mEffects[i]->setMode(mode);
10301 }
10302}
10303
Eric Laurent57b2dd12012-08-31 17:44:06 -070010304// setAudioSource_l() must be called with PlaybackThread::mLock held
10305void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10306{
10307 size_t size = mEffects.size();
10308 for (size_t i = 0; i < size; i++) {
10309 mEffects[i]->setAudioSource(source);
10310 }
10311}
10312
Eric Laurentcab11242010-07-15 12:50:15 -070010313// setVolume_l() must be called with PlaybackThread::mLock held
10314bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010315{
10316 uint32_t newLeft = *left;
10317 uint32_t newRight = *right;
10318 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010319 int ctrlIdx = -1;
10320 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010321
Eric Laurentcab11242010-07-15 12:50:15 -070010322 // first update volume controller
10323 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010324 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010325 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10326 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010327 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010328 break;
10329 }
10330 }
10331
10332 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010333 if (hasControl) {
10334 *left = mNewLeftVolume;
10335 *right = mNewRightVolume;
10336 }
10337 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010338 }
10339
10340 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010341 mLeftVolume = newLeft;
10342 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010343
10344 // second get volume update from volume controller
10345 if (ctrlIdx >= 0) {
10346 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010347 mNewLeftVolume = newLeft;
10348 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010349 }
10350 // then indicate volume to all other effects in chain.
10351 // Pass altered volume to effects before volume controller
10352 // and requested volume to effects after controller
10353 uint32_t lVol = newLeft;
10354 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010355
Mathias Agopian65ab4712010-07-14 17:59:35 -070010356 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010357 if ((int)i == ctrlIdx) continue;
10358 // this also works for ctrlIdx == -1 when there is no volume controller
10359 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010360 lVol = *left;
10361 rVol = *right;
10362 }
10363 mEffects[i]->setVolume(&lVol, &rVol, false);
10364 }
10365 *left = newLeft;
10366 *right = newRight;
10367
10368 return hasControl;
10369}
10370
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010371void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010372{
10373 const size_t SIZE = 256;
10374 char buffer[SIZE];
10375 String8 result;
10376
10377 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10378 result.append(buffer);
10379
10380 bool locked = tryLock(mLock);
10381 // failed to lock - AudioFlinger is probably deadlocked
10382 if (!locked) {
10383 result.append("\tCould not lock mutex:\n");
10384 }
10385
Eric Laurentcab11242010-07-15 12:50:15 -070010386 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10387 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010388 mEffects.size(),
10389 (uint32_t)mInBuffer,
10390 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010391 mActiveTrackCnt);
10392 result.append(buffer);
10393 write(fd, result.string(), result.size());
10394
10395 for (size_t i = 0; i < mEffects.size(); ++i) {
10396 sp<EffectModule> effect = mEffects[i];
10397 if (effect != 0) {
10398 effect->dump(fd, args);
10399 }
10400 }
10401
10402 if (locked) {
10403 mLock.unlock();
10404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010405}
10406
Eric Laurent59255e42011-07-27 19:49:51 -070010407// must be called with ThreadBase::mLock held
10408void AudioFlinger::EffectChain::setEffectSuspended_l(
10409 const effect_uuid_t *type, bool suspend)
10410{
10411 sp<SuspendedEffectDesc> desc;
10412 // use effect type UUID timelow as key as there is no real risk of identical
10413 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010414 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010415 if (suspend) {
10416 if (index >= 0) {
10417 desc = mSuspendedEffects.valueAt(index);
10418 } else {
10419 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010420 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010421 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010422 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010423 }
10424 if (desc->mRefCount++ == 0) {
10425 sp<EffectModule> effect = getEffectIfEnabled(type);
10426 if (effect != 0) {
10427 desc->mEffect = effect;
10428 effect->setSuspended(true);
10429 effect->setEnabled(false);
10430 }
10431 }
10432 } else {
10433 if (index < 0) {
10434 return;
10435 }
10436 desc = mSuspendedEffects.valueAt(index);
10437 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010438 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010439 desc->mRefCount = 1;
10440 }
10441 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010442 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010443 if (desc->mEffect != 0) {
10444 sp<EffectModule> effect = desc->mEffect.promote();
10445 if (effect != 0) {
10446 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010447 effect->lock();
10448 EffectHandle *handle = effect->controlHandle_l();
10449 if (handle != NULL && !handle->destroyed_l()) {
10450 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010451 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010452 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010453 }
10454 desc->mEffect.clear();
10455 }
10456 mSuspendedEffects.removeItemsAt(index);
10457 }
10458 }
10459}
10460
10461// must be called with ThreadBase::mLock held
10462void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10463{
10464 sp<SuspendedEffectDesc> desc;
10465
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010466 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010467 if (suspend) {
10468 if (index >= 0) {
10469 desc = mSuspendedEffects.valueAt(index);
10470 } else {
10471 desc = new SuspendedEffectDesc();
10472 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010473 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010474 }
10475 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010476 Vector< sp<EffectModule> > effects;
10477 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010478 for (size_t i = 0; i < effects.size(); i++) {
10479 setEffectSuspended_l(&effects[i]->desc().type, true);
10480 }
10481 }
10482 } else {
10483 if (index < 0) {
10484 return;
10485 }
10486 desc = mSuspendedEffects.valueAt(index);
10487 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010488 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010489 desc->mRefCount = 1;
10490 }
10491 if (--desc->mRefCount == 0) {
10492 Vector<const effect_uuid_t *> types;
10493 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10494 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10495 continue;
10496 }
10497 types.add(&mSuspendedEffects.valueAt(i)->mType);
10498 }
10499 for (size_t i = 0; i < types.size(); i++) {
10500 setEffectSuspended_l(types[i], false);
10501 }
Steve Block3856b092011-10-20 11:56:00 +010010502 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010503 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10504 }
10505 }
10506}
10507
Eric Laurent6bffdb82011-09-23 08:40:41 -070010508
10509// The volume effect is used for automated tests only
10510#ifndef OPENSL_ES_H_
10511static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10512 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10513const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10514#endif //OPENSL_ES_H_
10515
Eric Laurentdb7c0792011-08-10 10:37:50 -070010516bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10517{
10518 // auxiliary effects and visualizer are never suspended on output mix
10519 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10520 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010521 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10522 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010523 return false;
10524 }
10525 return true;
10526}
10527
Glenn Kastend0539712012-01-30 12:56:03 -080010528void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010529{
Glenn Kastend0539712012-01-30 12:56:03 -080010530 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010531 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010532 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10533 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010534 }
Eric Laurent59255e42011-07-27 19:49:51 -070010535 }
Eric Laurent59255e42011-07-27 19:49:51 -070010536}
10537
10538sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10539 const effect_uuid_t *type)
10540{
Glenn Kasten090f0192012-01-30 13:00:02 -080010541 sp<EffectModule> effect = getEffectFromType_l(type);
10542 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010543}
10544
10545void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10546 bool enabled)
10547{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010548 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010549 if (enabled) {
10550 if (index < 0) {
10551 // if the effect is not suspend check if all effects are suspended
10552 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10553 if (index < 0) {
10554 return;
10555 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010556 if (!isEffectEligibleForSuspend(effect->desc())) {
10557 return;
10558 }
Eric Laurent59255e42011-07-27 19:49:51 -070010559 setEffectSuspended_l(&effect->desc().type, enabled);
10560 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010561 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010562 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010563 return;
10564 }
Eric Laurent59255e42011-07-27 19:49:51 -070010565 }
Steve Block3856b092011-10-20 11:56:00 +010010566 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010567 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010568 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10569 // if effect is requested to suspended but was not yet enabled, supend it now.
10570 if (desc->mEffect == 0) {
10571 desc->mEffect = effect;
10572 effect->setEnabled(false);
10573 effect->setSuspended(true);
10574 }
10575 } else {
10576 if (index < 0) {
10577 return;
10578 }
Steve Block3856b092011-10-20 11:56:00 +010010579 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010580 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010581 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10582 desc->mEffect.clear();
10583 effect->setSuspended(false);
10584 }
10585}
10586
Mathias Agopian65ab4712010-07-14 17:59:35 -070010587#undef LOG_TAG
10588#define LOG_TAG "AudioFlinger"
10589
10590// ----------------------------------------------------------------------------
10591
10592status_t AudioFlinger::onTransact(
10593 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10594{
10595 return BnAudioFlinger::onTransact(code, data, reply, flags);
10596}
10597
Mathias Agopian65ab4712010-07-14 17:59:35 -070010598}; // namespace android