blob: 26652082c14b04ad2faa8bcf7f5aaf05d81a9d2d [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
vivek mehta2192bc92012-12-04 11:46:08 -08004** Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
5**
6** Copyright (c) 2012, The Linux Foundation. All rights reserved.
7** Not a Contribution, Apache license notifications and license are retained
8** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07009**
10** Licensed under the Apache License, Version 2.0 (the "License");
11** you may not use this file except in compliance with the License.
12** You may obtain a copy of the License at
13**
14** http://www.apache.org/licenses/LICENSE-2.0
15**
16** Unless required by applicable law or agreed to in writing, software
17** distributed under the License is distributed on an "AS IS" BASIS,
18** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19** See the License for the specific language governing permissions and
20** limitations under the License.
21*/
22
23
24#define LOG_TAG "AudioFlinger"
25//#define LOG_NDEBUG 0
26
27#include <math.h>
28#include <signal.h>
29#include <sys/time.h>
30#include <sys/resource.h>
31
Gloria Wang9ee159b2011-02-24 14:51:45 -080032#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/IServiceManager.h>
34#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070035#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
38#include <utils/String16.h>
39#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070040#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041
Dima Zavinfce7a472011-04-19 22:30:36 -070042#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080044#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#undef ADD_BATTERY_DATA
47
48#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080049#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080050#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070051#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include <private/media/AudioTrackShared.h>
54#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070057#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59#include "AudioMixer.h"
60#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080061#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070064#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070065#include <audio_effects/effect_ns.h>
66#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
Glenn Kasten3b21c502011-12-15 09:52:39 -080068#include <audio_utils/primitives.h>
69
Eric Laurentfeb0db62011-07-22 09:04:31 -070070#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080071
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070077
John Grossman4ff14ba2012-02-08 16:37:41 -080078#include <common_time/cc_helper.h>
79#include <common_time/local_clock.h>
80
Glenn Kasten58912562012-04-03 10:45:00 -070081#include "FastMixer.h"
82
83// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070084#include <media/nbaio/AudioStreamOutSink.h>
85#include <media/nbaio/MonoPipe.h>
86#include <media/nbaio/MonoPipeReader.h>
87#include <media/nbaio/Pipe.h>
88#include <media/nbaio/PipeReader.h>
89#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070090
Glenn Kasten1dc28b72012-04-24 10:01:03 -070091#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070092
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
John Grossman1c345192012-03-27 14:00:17 -070095// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
Eric Laurentde070132010-07-13 04:45:46 -0700107
vivek mehta2192bc92012-12-04 11:46:08 -0800108#ifdef QCOM_HARDWARE
109#define DIRECT_TRACK_EOS 1
110static const char lockName[] = "DirectTrack";
111#endif
112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113namespace android {
114
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800115static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
116static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800119static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121// retry counts for buffer fill timeout
122// 50 * ~20msecs = 1 second
123static const int8_t kMaxTrackRetries = 50;
124static const int8_t kMaxTrackStartupRetries = 50;
125// allow less retry attempts on direct output thread.
126// direct outputs can be a scarce resource in audio hardware and should
127// be released as quickly as possible.
128static const int8_t kMaxTrackRetriesDirect = 2;
129
130static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800131static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700132
Glenn Kasten7dede872011-12-13 11:04:14 -0800133// don't warn about blocked writes or record buffer overflows more often than this
134static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700136// RecordThread loop sleep time upon application overrun or audio HAL read error
137static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138
Glenn Kasten7dede872011-12-13 11:04:14 -0800139// maximum time to wait for setParameters to complete
140static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700141
Eric Laurent7cafbb32011-11-22 18:50:29 -0800142// minimum sleep time for the mixer thread loop when tracks are active but in underrun
143static const uint32_t kMinThreadSleepTimeUs = 5000;
144// maximum divider applied to the active sleep time in the mixer thread loop
145static const uint32_t kMaxThreadSleepTimeShift = 2;
146
Glenn Kasten58912562012-04-03 10:45:00 -0700147// minimum normal mix buffer size, expressed in milliseconds rather than frames
148static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700149// maximum normal mix buffer size
150static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700151
John Grossman4ff14ba2012-02-08 16:37:41 -0800152nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800153
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700160 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700162 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700171static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
172 // AudioFlinger::setParameters() updates, other threads read w/o lock
173
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700174// Priorities for requestPriority
175static const int kPriorityAudioApp = 2;
176static const int kPriorityFastMixer = 3;
177
Glenn Kasten3ed29202012-08-07 15:24:44 -0700178// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
179// for the track. The client then sub-divides this into smaller buffers for its use.
180// Currently the client uses double-buffering by default, but doesn't tell us about that.
181// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700182// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
183// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700184// See the client's minBufCount and mNotificationFramesAct calculations for details.
185static const int kFastTrackMultiplier = 2;
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700189#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800190// To collect the amplifier usage
191static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800192 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
193 if (service == NULL) {
194 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800195 return;
196 }
197
198 service->addBatteryData(params);
199}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700200#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800201
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700203{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700204 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 int rc;
206
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700207 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
208 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
209 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
210 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700212 }
213 rc = audio_hw_device_open(mod, dev);
214 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
215 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
216 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700218 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000219#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700220 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
221 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
222 rc = BAD_VALUE;
223 goto out;
224 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100225#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 return 0;
227
228out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 *dev = NULL;
230 return rc;
231}
232
vivek mehta2192bc92012-12-04 11:46:08 -0800233static uint32_t getInputChannelCount(uint32_t channels) {
234#ifdef QCOM_HARDWARE
235 // only mono or stereo and 5.1 are supported for input sources
236 return popcount((channels) & (AUDIO_CHANNEL_IN_STEREO | AUDIO_CHANNEL_IN_MONO | AUDIO_CHANNEL_IN_5POINT1));
237#else
238 return popcount(channels);
239#endif
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241// ----------------------------------------------------------------------------
242
243AudioFlinger::AudioFlinger()
244 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800245 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700246 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800248 mMasterMute(false),
249 mNextUniqueId(1),
250 mMode(AUDIO_MODE_INVALID),
251 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700253}
254
255void AudioFlinger::onFirstRef()
256{
Dima Zavin799a70e2011-04-18 16:57:27 -0700257 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700258
Eric Laurent93575202011-01-18 18:39:02 -0800259 Mutex::Autolock _l(mLock);
260
Dima Zavin799a70e2011-04-18 16:57:27 -0700261 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800262#ifdef QCOM_HARDWARE
263 mLPASessionId = -2; // -2 is invalid session ID
264 mIsEffectConfigChanged = false;
265 mLPAEffectChain = NULL;
266#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800267 char val_str[PROPERTY_VALUE_MAX] = { 0 };
268 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
269 uint32_t int_val;
270 if (1 == sscanf(val_str, "%u", &int_val)) {
271 mStandbyTimeInNsecs = milliseconds(int_val);
272 ALOGI("Using %u mSec as standby time.", int_val);
273 } else {
274 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
275 ALOGI("Using default %u mSec as standby time.",
276 (uint32_t)(mStandbyTimeInNsecs / 1000000));
277 }
278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281}
282
283AudioFlinger::~AudioFlinger()
284{
285 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700286 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700287 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700288 }
289 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700290 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700291 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700292 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700293
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800294 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
295 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
297 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298 }
299}
300
Eric Laurenta4c5a552012-03-29 10:12:40 -0700301static const char * const audio_interfaces[] = {
302 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
303 AUDIO_HARDWARE_MODULE_ID_A2DP,
304 AUDIO_HARDWARE_MODULE_ID_USB,
305};
306#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
307
John Grossmanee578c02012-07-23 17:05:46 -0700308AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
309 audio_module_handle_t module,
310 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700311{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700312 // if module is 0, the request comes from an old policy manager and we should load
313 // well known modules
314 if (module == 0) {
315 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
316 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
317 loadHwModule_l(audio_interfaces[i]);
318 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700319 // then try to find a module supporting the requested device.
320 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
321 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
322 audio_hw_device_t *dev = audioHwDevice->hwDevice();
323 if ((dev->get_supported_devices != NULL) &&
324 (dev->get_supported_devices(dev) & devices) == devices)
325 return audioHwDevice;
326 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700327 } else {
328 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700329 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
330 if (audioHwDevice != NULL) {
331 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700332 }
333 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700334
Dima Zavin799a70e2011-04-18 16:57:27 -0700335 return NULL;
336}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700338void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
343
344 result.append("Clients:\n");
345 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800346 sp<Client> client = mClients.valueAt(i).promote();
347 if (client != 0) {
348 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
349 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 }
351 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700352
353 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800354 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700355 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
356 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800357 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700358 result.append(buffer);
359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361}
362
363
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700364void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365{
366 const size_t SIZE = 256;
367 char buffer[SIZE];
368 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800369 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370
John Grossman4ff14ba2012-02-08 16:37:41 -0800371 snprintf(buffer, SIZE, "Hardware status: %d\n"
372 "Standby Time mSec: %u\n",
373 hardwareStatus,
374 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 result.append(buffer);
376 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377}
378
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700379void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380{
381 const size_t SIZE = 256;
382 char buffer[SIZE];
383 String8 result;
384 snprintf(buffer, SIZE, "Permission Denial: "
385 "can't dump AudioFlinger from pid=%d, uid=%d\n",
386 IPCThreadState::self()->getCallingPid(),
387 IPCThreadState::self()->getCallingUid());
388 result.append(buffer);
389 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390}
391
392static bool tryLock(Mutex& mutex)
393{
394 bool locked = false;
395 for (int i = 0; i < kDumpLockRetries; ++i) {
396 if (mutex.tryLock() == NO_ERROR) {
397 locked = true;
398 break;
399 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800400 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 }
402 return locked;
403}
404
405status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
406{
Glenn Kasten44deb052012-02-05 18:09:08 -0800407 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 dumpPermissionDenial(fd, args);
409 } else {
410 // get state of hardware lock
411 bool hardwareLocked = tryLock(mHardwareLock);
412 if (!hardwareLocked) {
413 String8 result(kHardwareLockedString);
414 write(fd, result.string(), result.size());
415 } else {
416 mHardwareLock.unlock();
417 }
418
419 bool locked = tryLock(mLock);
420
421 // failed to lock - AudioFlinger is probably deadlocked
422 if (!locked) {
423 String8 result(kDeadlockedString);
424 write(fd, result.string(), result.size());
425 }
426
427 dumpClients(fd, args);
428 dumpInternals(fd, args);
429
430 // dump playback threads
431 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
432 mPlaybackThreads.valueAt(i)->dump(fd, args);
433 }
434
435 // dump record threads
436 for (size_t i = 0; i < mRecordThreads.size(); i++) {
437 mRecordThreads.valueAt(i)->dump(fd, args);
438 }
439
Dima Zavin799a70e2011-04-18 16:57:27 -0700440 // dump all hardware devs
441 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700442 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700443 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 }
445 if (locked) mLock.unlock();
446 }
447 return NO_ERROR;
448}
449
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800450sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
451{
452 // If pid is already in the mClients wp<> map, then use that entry
453 // (for which promote() is always != 0), otherwise create a new entry and Client.
454 sp<Client> client = mClients.valueFor(pid).promote();
455 if (client == 0) {
456 client = new Client(this, pid);
457 mClients.add(pid, client);
458 }
459
460 return client;
461}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462
463// IAudioFlinger interface
464
465
466sp<IAudioTrack> AudioFlinger::createTrack(
467 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800468 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800470 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700471 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800473 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800475 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800476 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477 int *sessionId,
478 status_t *status)
479{
480 sp<PlaybackThread::Track> track;
481 sp<TrackHandle> trackHandle;
482 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 status_t lStatus;
484 int lSessionId;
485
Glenn Kasten263709e2012-01-06 08:40:01 -0800486 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
487 // but if someone uses binder directly they could bypass that and cause us to crash
488 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000489 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 lStatus = BAD_VALUE;
491 goto Exit;
492 }
493
494 {
495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700497 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000499 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 lStatus = BAD_VALUE;
501 goto Exit;
502 }
503
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800504 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505
Steve Block3856b092011-10-20 11:56:00 +0100506 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700507 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700508 // check if an effect chain with the same session ID is present on another
509 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700511 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
512 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700513 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700514 if (sessions & PlaybackThread::EFFECT_SESSION) {
515 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700516 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700517 }
Eric Laurentde070132010-07-13 04:45:46 -0700518 }
519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 lSessionId = *sessionId;
521 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700522 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700523 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700524 if (sessionId != NULL) {
525 *sessionId = lSessionId;
526 }
527 }
Steve Block3856b092011-10-20 11:56:00 +0100528 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529
530 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800531 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700532
533 // move effect chain to this output thread if an effect on same session was waiting
534 // for a track to be created
535 if (lStatus == NO_ERROR && effectThread != NULL) {
536 Mutex::Autolock _dl(thread->mLock);
537 Mutex::Autolock _sl(effectThread->mLock);
538 moveEffectChain_l(lSessionId, effectThread, thread, true);
539 }
Eric Laurenta011e352012-03-29 15:51:43 -0700540
541 // Look for sync events awaiting for a session to be used.
542 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
543 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
544 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700545 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700546 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700547 } else {
548 mPendingSyncEvents[i]->cancel();
549 }
Eric Laurenta011e352012-03-29 15:51:43 -0700550 mPendingSyncEvents.removeAt(i);
551 i--;
552 }
553 }
554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 }
556 if (lStatus == NO_ERROR) {
557 trackHandle = new TrackHandle(track);
558 } else {
559 // remove local strong reference to Client before deleting the Track so that the Client
560 // destructor is called by the TrackBase destructor with mLock held
561 client.clear();
562 track.clear();
563 }
564
565Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700566 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 *status = lStatus;
568 }
569 return trackHandle;
570}
571
vivek mehta2192bc92012-12-04 11:46:08 -0800572#ifdef QCOM_HARDWARE
573sp<IDirectTrack> AudioFlinger::createDirectTrack(
574 pid_t pid,
575 uint32_t sampleRate,
576 audio_channel_mask_t channelMask,
577 audio_io_handle_t output,
578 int *sessionId,
579 IDirectTrackClient *client,
580 audio_stream_type_t streamType,
581 status_t *status)
582{
583 *status = NO_ERROR;
584 status_t lStatus = NO_ERROR;
585 sp<IDirectTrack> track = NULL;
586 DirectAudioTrack* directTrack = NULL;
587 Mutex::Autolock _l(mLock);
588
589 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
590 *sessionId, sampleRate, channelMask);
591 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
592 if(desc == NULL) {
593 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
594 lStatus = BAD_VALUE;
595 goto Exit;
596 }
597 desc->mStreamType = streamType;
598 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
599 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
600 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
601 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
602 // Check if the session ID is already associated with a track
603 uint32_t sessions = t->hasAudioSession(*sessionId);
604
605 // check if an effect with same session ID is waiting for a ssession to be created
606 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
607 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
608 // Clear reference to previous effect chain if any
609 t->mLock.lock();
610 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
611 mLPAEffectChain = t->getEffectChain_l(*sessionId);
612 t->mLock.unlock();
613 }
614 }
615 mLPASessionId = *sessionId;
616 if (mLPAEffectChain != NULL) {
617 mLPAEffectChain->setLPAFlag(true);
618 // For LPA, the volume will be applied in DSP. No need for volume
619 // control in the Effect chain, so setting it to unity.
620 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
621 mLPAEffectChain->setVolume_l(&volume,&volume);
622 } else {
623 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
624 }
625 mLPASampleRate = sampleRate;
626 mLPANumChannels = popcount(channelMask);
627 } else {
628 if(sessionId != NULL) {
629 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
630 }
631 }
632 }
633 mLock.unlock();
634 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
635 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
636 mLock.lock();
637 if (directTrack != 0) {
638 track = dynamic_cast<IDirectTrack *>(directTrack);
639 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
640 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
641 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
642 } else {
643 lStatus = BAD_VALUE;
644 }
645Exit:
646 if(lStatus) {
647 if (track != NULL) {
648 track.clear();
649 }
650 *status = lStatus;
651 }
652 return track;
653}
654
655void AudioFlinger::deleteEffectSession()
656{
657 Mutex::Autolock _l(mLock);
658 ALOGV("deleteSession");
659 // -2 is invalid session ID
660 mLPASessionId = -2;
661 if (mLPAEffectChain != NULL) {
662 mLPAEffectChain->setLPAFlag(false);
663 size_t i, numEffects = mLPAEffectChain->getNumEffects();
664 for(i = 0; i < numEffects; i++) {
665 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
666 effect->setInBuffer(mLPAEffectChain->inBuffer());
667 if (i == numEffects-1) {
668 effect->setOutBuffer(mLPAEffectChain->outBuffer());
669 } else {
670 effect->setOutBuffer(mLPAEffectChain->inBuffer());
671 }
672 effect->configure();
673 }
674 mLPAEffectChain.clear();
675 mLPAEffectChain = NULL;
676 }
677}
678
679// ToDo: Should we go ahead with this frameCount?
680#define DEAFULT_FRAME_COUNT 1200
681void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
682{
683 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
684 // This might be the first buffer to apply effects after effect config change
685 // should not skip effects processing
686 mIsEffectConfigChanged = false;
687
688 volatile size_t numEffects = 0;
689 if(mLPAEffectChain != NULL) {
690 numEffects = mLPAEffectChain->getNumEffects();
691 }
692
693 if( numEffects > 0) {
694 size_t i = 0;
695 int16_t *pIn = inBuffer;
696 int16_t *pOut = outBuffer;
697
698 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
699
700 while(frameCount > 0) {
701 if(mLPAEffectChain == NULL) {
702 ALOGV("LPA Effect Chain is removed - No effects processing !!");
703 numEffects = 0;
704 break;
705 }
706 mLPAEffectChain->lock();
707
708 numEffects = mLPAEffectChain->getNumEffects();
709 if(!numEffects) {
710 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
711 mLPAEffectChain->unlock();
712 break;
713 }
714
715 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
716 bool isEffectEnabled = false;
717 for(i = 0; i < numEffects; i++) {
718 // If effect configuration is changed while applying effects do not process further
719 if(mIsEffectConfigChanged) {
720 mLPAEffectChain->unlock();
721 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
722 return;
723 }
724 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
725 if(effect == NULL) {
726 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
727 mLPAEffectChain->unlock();
728 return;
729 }
730 if(i == 0) {
731 // For the first set input and output buffers different
732 isEffectEnabled = effect->isProcessEnabled();
733 effect->setInBuffer(pIn);
734 effect->setOutBuffer(pOut);
735 } else {
736 // For the remaining use previous effect's output buffer as input buffer
737 effect->setInBuffer(pOut);
738 effect->setOutBuffer(pOut);
739 }
740 // true indicates that it is being applied on LPA output
741 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
742 }
743
744 if(isEffectEnabled) {
745 // Clear the output buffer
746 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
747 } else {
748 // Copy input buffer content to the output buffer
749 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
750 }
751
752 mLPAEffectChain->process_l();
753
754 mLPAEffectChain->unlock();
755
756 // Update input and output buffer pointers
757 pIn += (outFrameCount * mLPANumChannels);
758 pOut += (outFrameCount * mLPANumChannels);
759 frameCount -= outFrameCount;
760 }
761 }
762
763 if (!numEffects) {
764 ALOGV("applyEffectsOn: There are no effects to be applied");
765 if(inBuffer != outBuffer) {
766 // No effect applied so just copy input buffer to output buffer
767 memcpy(outBuffer, inBuffer, size);
768 }
769 }
770}
771#endif
772
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800773uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774{
775 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800776#ifdef QCOM_HARDWARE
777 if (!mDirectAudioTracks.isEmpty()) {
778 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
779 if(desc != NULL) {
780 return desc->stream->common.get_sample_rate(&desc->stream->common);
781 }
782 }
783#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784 PlaybackThread *thread = checkPlaybackThread_l(output);
785 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000786 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 return 0;
788 }
789 return thread->sampleRate();
790}
791
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800792int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
794 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800795#ifdef QCOM_HARDWARE
796 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
797 if(desc != NULL) {
798 return desc->stream->common.get_channels(&desc->stream->common);
799 }
800#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 PlaybackThread *thread = checkPlaybackThread_l(output);
802 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000803 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 return 0;
805 }
806 return thread->channelCount();
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
811 Mutex::Autolock _l(mLock);
812 PlaybackThread *thread = checkPlaybackThread_l(output);
813 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000814 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800815 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 }
817 return thread->format();
818}
819
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800820size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
822 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800823#ifdef QCOM_HARDWARE
824 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
825 if(desc != NULL) {
826 return desc->stream->common.get_buffer_size(&desc->stream->common);
827 }
828#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 PlaybackThread *thread = checkPlaybackThread_l(output);
830 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000831 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 return 0;
833 }
Glenn Kasten58912562012-04-03 10:45:00 -0700834 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
835 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return thread->frameCount();
837}
838
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800839uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
841 Mutex::Autolock _l(mLock);
842 PlaybackThread *thread = checkPlaybackThread_l(output);
843 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000844 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
847 return thread->latency();
848}
849
850status_t AudioFlinger::setMasterVolume(float value)
851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return ret;
855 }
856
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 // check calling permissions
858 if (!settingsAllowed()) {
859 return PERMISSION_DENIED;
860 }
861
Eric Laurenta4c5a552012-03-29 10:12:40 -0700862 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700863 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700864
John Grossmanee578c02012-07-23 17:05:46 -0700865 // Set master volume in the HALs which support it.
866 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
867 AutoMutex lock(mHardwareLock);
868 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800869
John Grossmanee578c02012-07-23 17:05:46 -0700870 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
871 if (dev->canSetMasterVolume()) {
872 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800873 }
John Grossmanee578c02012-07-23 17:05:46 -0700874 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876
John Grossmanee578c02012-07-23 17:05:46 -0700877 // Now set the master volume in each playback thread. Playback threads
878 // assigned to HALs which do not have master volume support will apply
879 // master volume during the mix operation. Threads with HALs which do
880 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800881 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700882 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883
884 return NO_ERROR;
885}
886
Glenn Kastenf78aee72012-01-04 11:00:47 -0800887status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888{
Eric Laurenta1884f92011-08-23 08:25:03 -0700889 status_t ret = initCheck();
890 if (ret != NO_ERROR) {
891 return ret;
892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893
894 // check calling permissions
895 if (!settingsAllowed()) {
896 return PERMISSION_DENIED;
897 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800898 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000899 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 return BAD_VALUE;
901 }
902
903 { // scope for the lock
904 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700905 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700907 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 mHardwareStatus = AUDIO_HW_IDLE;
909 }
910
911 if (NO_ERROR == ret) {
912 Mutex::Autolock _l(mLock);
913 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800914 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700915 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 }
917
918 return ret;
919}
920
921status_t AudioFlinger::setMicMute(bool state)
922{
Eric Laurenta1884f92011-08-23 08:25:03 -0700923 status_t ret = initCheck();
924 if (ret != NO_ERROR) {
925 return ret;
926 }
927
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 // check calling permissions
929 if (!settingsAllowed()) {
930 return PERMISSION_DENIED;
931 }
932
933 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700934 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700936 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mHardwareStatus = AUDIO_HW_IDLE;
938 return ret;
939}
940
941bool AudioFlinger::getMicMute() const
942{
Eric Laurenta1884f92011-08-23 08:25:03 -0700943 status_t ret = initCheck();
944 if (ret != NO_ERROR) {
945 return false;
946 }
947
Dima Zavinfce7a472011-04-19 22:30:36 -0700948 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800949 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700950 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700952 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 mHardwareStatus = AUDIO_HW_IDLE;
954 return state;
955}
956
957status_t AudioFlinger::setMasterMute(bool muted)
958{
John Grossmand8f178d2012-07-20 14:51:35 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return ret;
962 }
963
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 // check calling permissions
965 if (!settingsAllowed()) {
966 return PERMISSION_DENIED;
967 }
968
John Grossmanee578c02012-07-23 17:05:46 -0700969 Mutex::Autolock _l(mLock);
970 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700971
John Grossmanee578c02012-07-23 17:05:46 -0700972 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100973#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700974 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
975 AutoMutex lock(mHardwareLock);
976 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700977
John Grossmanee578c02012-07-23 17:05:46 -0700978 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
979 if (dev->canSetMasterMute()) {
980 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700981 }
John Grossmanee578c02012-07-23 17:05:46 -0700982 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700983 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100984#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700985
John Grossmanee578c02012-07-23 17:05:46 -0700986 // Now set the master mute in each playback thread. Playback threads
987 // assigned to HALs which do not have master mute support will apply master
988 // mute during the mix operation. Threads with HALs which do support master
989 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800990 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700991 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992
993 return NO_ERROR;
994}
995
996float AudioFlinger::masterVolume() const
997{
Glenn Kasten98067102011-12-13 11:47:54 -0800998 Mutex::Autolock _l(mLock);
999 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000}
1001
1002bool AudioFlinger::masterMute() const
1003{
Glenn Kasten98067102011-12-13 11:47:54 -08001004 Mutex::Autolock _l(mLock);
1005 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006}
1007
John Grossman4ff14ba2012-02-08 16:37:41 -08001008float AudioFlinger::masterVolume_l() const
1009{
John Grossman4ff14ba2012-02-08 16:37:41 -08001010 return mMasterVolume;
1011}
1012
John Grossmand8f178d2012-07-20 14:51:35 -07001013bool AudioFlinger::masterMute_l() const
1014{
John Grossmanee578c02012-07-23 17:05:46 -07001015 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001016}
1017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001018status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1019 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020{
1021 // check calling permissions
1022 if (!settingsAllowed()) {
1023 return PERMISSION_DENIED;
1024 }
1025
Glenn Kasten263709e2012-01-06 08:40:01 -08001026 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001027 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 return BAD_VALUE;
1029 }
1030
1031 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001032#ifdef QCOM_HARDWARE
1033 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1034 AudioSessionDescriptor *desc = NULL;
1035 if (!mDirectAudioTracks.isEmpty()) {
1036 desc = mDirectAudioTracks.valueFor(output);
1037 if (desc != NULL) {
1038 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1039 if (desc->mStreamType == stream) {
1040 mStreamTypes[stream].volume = value;
1041 desc->stream->set_volume(desc->stream,
1042 desc->mVolumeLeft * mStreamTypes[stream].volume,
1043 desc->mVolumeRight* mStreamTypes[stream].volume);
1044 return NO_ERROR;
1045 }
1046 }
1047 }
1048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 PlaybackThread *thread = NULL;
1050 if (output) {
1051 thread = checkPlaybackThread_l(output);
1052 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001053#ifdef QCOM_HARDWARE
1054 if (desc != NULL) {
1055 return NO_ERROR;
1056 }
1057#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 return BAD_VALUE;
1059 }
vivek mehta2192bc92012-12-04 11:46:08 -08001060
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 }
1062
1063 mStreamTypes[stream].volume = value;
1064
1065 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001066 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001067 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 }
1069 } else {
1070 thread->setStreamVolume(stream, value);
1071 }
1072
1073 return NO_ERROR;
1074}
1075
Glenn Kastenfff6d712012-01-12 16:38:12 -08001076status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077{
1078 // check calling permissions
1079 if (!settingsAllowed()) {
1080 return PERMISSION_DENIED;
1081 }
1082
Glenn Kasten263709e2012-01-06 08:40:01 -08001083 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001084 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001085 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 return BAD_VALUE;
1087 }
1088
Eric Laurent93575202011-01-18 18:39:02 -08001089 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090 mStreamTypes[stream].mute = muted;
1091 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001092 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093
1094 return NO_ERROR;
1095}
1096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001097float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098{
Glenn Kasten263709e2012-01-06 08:40:01 -08001099 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 return 0.0f;
1101 }
1102
1103 AutoMutex lock(mLock);
1104 float volume;
1105 if (output) {
1106 PlaybackThread *thread = checkPlaybackThread_l(output);
1107 if (thread == NULL) {
1108 return 0.0f;
1109 }
1110 volume = thread->streamVolume(stream);
1111 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001112 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 }
1114
1115 return volume;
1116}
1117
Glenn Kastenfff6d712012-01-12 16:38:12 -08001118bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119{
Glenn Kasten263709e2012-01-06 08:40:01 -08001120 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 return true;
1122 }
1123
Glenn Kasten6637baa2012-01-09 09:40:36 -08001124 AutoMutex lock(mLock);
1125 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001128status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001130 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1132 // check calling permissions
1133 if (!settingsAllowed()) {
1134 return PERMISSION_DENIED;
1135 }
1136
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 // ioHandle == 0 means the parameters are global to the audio hardware interface
1138 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001139 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001140 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001141 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001142 AutoMutex lock(mHardwareLock);
1143 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1144 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1145 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1146 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1147 final_result = result ?: final_result;
1148 }
1149 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001150 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001151 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1152 AudioParameter param = AudioParameter(keyValuePairs);
1153 String8 value;
1154 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001155 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1156 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001157 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1158 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001159 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001160 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1161 // collect all of the thread's session IDs
1162 KeyedVector<int, bool> ids = thread->sessionIds();
1163 // suspend effects associated with those session IDs
1164 for (size_t j = 0; j < ids.size(); ++j) {
1165 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001166 thread->setEffectSuspended(FX_IID_AEC,
1167 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001168 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001169 thread->setEffectSuspended(FX_IID_NS,
1170 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001171 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001172 }
1173 }
Eric Laurentbee53372011-08-29 12:42:48 -07001174 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001175 }
1176 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001177 String8 screenState;
1178 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1179 bool isOff = screenState == "off";
1180 if (isOff != (gScreenState & 1)) {
1181 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1182 }
1183 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001184 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 }
1186
vivek mehta2192bc92012-12-04 11:46:08 -08001187#ifdef QCOM_HARDWARE
1188 AudioSessionDescriptor *desc = NULL;
1189 if (!mDirectAudioTracks.isEmpty()) {
1190 desc = mDirectAudioTracks.valueFor(ioHandle);
1191 if (desc != NULL) {
1192 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1193 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
1194 return NO_ERROR;
1195 }
1196 }
1197#endif
1198
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1200 // and the thread is exited once the lock is released
1201 sp<ThreadBase> thread;
1202 {
1203 Mutex::Autolock _l(mLock);
1204 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001205 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001207 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001208 // indicate output device change to all input threads for pre processing
1209 AudioParameter param = AudioParameter(keyValuePairs);
1210 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001211 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1212 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001213 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1214 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001215 for (size_t i = 0; i < recordThreads.size(); i++) {
1216 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001217 }
1218 }
vivek mehta2192bc92012-12-04 11:46:08 -08001219 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 }
vivek mehta2192bc92012-12-04 11:46:08 -08001221 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001223 if (thread != 0) {
1224 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 }
1226 return BAD_VALUE;
1227}
1228
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001229String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001231// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1233
Eric Laurenta4c5a552012-03-29 10:12:40 -07001234 Mutex::Autolock _l(mLock);
1235
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001237 String8 out_s8;
1238
Dima Zavin799a70e2011-04-18 16:57:27 -07001239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001240 char *s;
1241 {
1242 AutoMutex lock(mHardwareLock);
1243 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001244 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001245 s = dev->get_parameters(dev, keys.string());
1246 mHardwareStatus = AUDIO_HW_IDLE;
1247 }
John Grossmanef7740b2012-02-09 11:28:36 -08001248 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001249 free(s);
1250 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001251 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 }
1253
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1255 if (playbackThread != NULL) {
1256 return playbackThread->getParameters(keys);
1257 }
1258 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1259 if (recordThread != NULL) {
1260 return recordThread->getParameters(keys);
1261 }
1262 return String8("");
1263}
1264
Glenn Kastendd8104c2012-07-02 12:42:44 -07001265size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1266 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267{
Eric Laurenta1884f92011-08-23 08:25:03 -07001268 status_t ret = initCheck();
1269 if (ret != NO_ERROR) {
1270 return 0;
1271 }
1272
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001273 AutoMutex lock(mHardwareLock);
1274 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001275 struct audio_config config = {
1276 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001277 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001278 format: format,
1279 };
John Grossmanee578c02012-07-23 17:05:46 -07001280 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001281#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001282 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001283#else
1284 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1285#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001286 mHardwareStatus = AUDIO_HW_IDLE;
1287 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288}
1289
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001290unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 Mutex::Autolock _l(mLock);
1293
1294 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1295 if (recordThread != NULL) {
1296 return recordThread->getInputFramesLost();
1297 }
1298 return 0;
1299}
1300
1301status_t AudioFlinger::setVoiceVolume(float value)
1302{
Eric Laurenta1884f92011-08-23 08:25:03 -07001303 status_t ret = initCheck();
1304 if (ret != NO_ERROR) {
1305 return ret;
1306 }
1307
Mathias Agopian65ab4712010-07-14 17:59:35 -07001308 // check calling permissions
1309 if (!settingsAllowed()) {
1310 return PERMISSION_DENIED;
1311 }
1312
1313 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001314 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001315 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001316 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 mHardwareStatus = AUDIO_HW_IDLE;
1318
1319 return ret;
1320}
1321
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001322status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1323 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001324{
1325 status_t status;
1326
1327 Mutex::Autolock _l(mLock);
1328
1329 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1330 if (playbackThread != NULL) {
1331 return playbackThread->getRenderPosition(halFrames, dspFrames);
1332 }
1333
1334 return BAD_VALUE;
1335}
1336
1337void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1338{
1339
1340 Mutex::Autolock _l(mLock);
1341
vivek mehta2192bc92012-12-04 11:46:08 -08001342 sp<IBinder> binder = client->asBinder();
1343 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344 sp<NotificationClient> notificationClient = new NotificationClient(this,
1345 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001346 binder);
1347 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348
vivek mehta2192bc92012-12-04 11:46:08 -08001349 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350
1351 sp<IBinder> binder = client->asBinder();
1352 binder->linkToDeath(notificationClient);
1353
1354 // the config change is always sent from playback or record threads to avoid deadlock
1355 // with AudioSystem::gLock
1356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001357 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 }
1359
1360 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001361 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001362 }
1363 }
1364}
1365
vivek mehta2192bc92012-12-04 11:46:08 -08001366#ifdef QCOM_HARDWARE
1367status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1368{
1369 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1370 Mutex::Autolock _l(mLock);
1371
1372 sp<IBinder> binder = client->asBinder();
1373 int index = mNotificationClients.indexOfKey(binder);
1374 if (index >= 0) {
1375 mNotificationClients.removeItemsAt(index);
1376 return true;
1377 }
1378
1379 return false;
1380}
1381#endif
1382
1383void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384{
1385 Mutex::Autolock _l(mLock);
1386
vivek mehta2192bc92012-12-04 11:46:08 -08001387 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001388
vivek mehta2192bc92012-12-04 11:46:08 -08001389 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001390 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001391 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001392 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001393 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001394 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001395 ALOGV(" pid %d @ %d", ref->mPid, i);
1396 if (ref->mPid == pid) {
1397 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001398 mAudioSessionRefs.removeAt(i);
1399 delete ref;
1400 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001401 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001402 } else {
1403 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001404 }
1405 }
1406 if (removed) {
1407 purgeStaleEffects_l();
1408 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409}
1410
1411// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001412void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413{
vivek mehta2192bc92012-12-04 11:46:08 -08001414#ifdef QCOM_HARDWARE
1415 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1416 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1417 mIsEffectConfigChanged = true;
1418 }
1419#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 size_t size = mNotificationClients.size();
1421 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001422 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1423 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424 }
1425}
1426
1427// removeClient_l() must be called with AudioFlinger::mLock held
1428void AudioFlinger::removeClient_l(pid_t pid)
1429{
Steve Block3856b092011-10-20 11:56:00 +01001430 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 mClients.removeItem(pid);
1432}
1433
Eric Laurent717e1282012-06-29 16:36:52 -07001434// getEffectThread_l() must be called with AudioFlinger::mLock held
1435sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1436{
1437 sp<PlaybackThread> thread;
1438
1439 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1440 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1441 ALOG_ASSERT(thread == 0);
1442 thread = mPlaybackThreads.valueAt(i);
1443 }
1444 }
1445
1446 return thread;
1447}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
1449// ----------------------------------------------------------------------------
1450
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001451AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001452 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001453 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001454 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001455 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001456 // mChannelMask
1457 mChannelCount(0),
1458 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1459 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001460 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1461 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001462 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001463 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464{
1465}
1466
1467AudioFlinger::ThreadBase::~ThreadBase()
1468{
1469 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001470 // do not lock the mutex in destructor
1471 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001472 if (mPowerManager != 0) {
1473 sp<IBinder> binder = mPowerManager->asBinder();
1474 binder->unlinkToDeath(mDeathRecipient);
1475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478void AudioFlinger::ThreadBase::exit()
1479{
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001481 // do any cleanup required for exit to succeed
1482 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001484 // This lock prevents the following race in thread (uniprocessor for illustration):
1485 // if (!exitPending()) {
1486 // // context switch from here to exit()
1487 // // exit() calls requestExit(), what exitPending() observes
1488 // // exit() calls signal(), which is dropped since no waiters
1489 // // context switch back from exit() to here
1490 // mWaitWorkCV.wait(...);
1491 // // now thread is hung
1492 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001493 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001495 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001497 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1498 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 requestExitAndWait();
1500}
1501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1503{
1504 status_t status;
1505
Steve Block3856b092011-10-20 11:56:00 +01001506 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 Mutex::Autolock _l(mLock);
1508
1509 mNewParameters.add(keyValuePairs);
1510 mWaitWorkCV.signal();
1511 // wait condition with timeout in case the thread loop has exited
1512 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001513 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 status = mParamStatus;
1515 mWaitWorkCV.signal();
1516 } else {
1517 status = TIMED_OUT;
1518 }
1519 return status;
1520}
1521
vivek mehta2192bc92012-12-04 11:46:08 -08001522#ifdef QCOM_HARDWARE
1523void AudioFlinger::ThreadBase::effectConfigChanged() {
1524 mAudioFlinger->mLock.lock();
1525 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1526 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1527 mAudioFlinger->mLock.unlock();
1528}
1529#endif
1530
Eric Laurent896adcd2012-09-13 11:18:23 -07001531void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532{
1533 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001534 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535}
1536
Eric Laurent896adcd2012-09-13 11:18:23 -07001537// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1538void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539{
Eric Laurent896adcd2012-09-13 11:18:23 -07001540 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1541 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1542 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1543 mWaitWorkCV.signal();
1544}
1545
1546// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1547void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1548{
1549 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1550 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1551 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1552 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 mWaitWorkCV.signal();
1554}
1555
1556void AudioFlinger::ThreadBase::processConfigEvents()
1557{
1558 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001559 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001560 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001561 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 mConfigEvents.removeAt(0);
1563 // release mLock before locking AudioFlinger mLock: lock order is always
1564 // AudioFlinger then ThreadBase to avoid cross deadlock
1565 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001566 switch(event->type()) {
1567 case CFG_EVENT_PRIO: {
1568 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1569 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1570 if (err != 0) {
1571 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1572 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1573 }
1574 } break;
1575 case CFG_EVENT_IO: {
1576 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1577 mAudioFlinger->mLock.lock();
1578 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1579 mAudioFlinger->mLock.unlock();
1580 } break;
1581 default:
1582 ALOGE("processConfigEvents() unknown event type %d", event->type());
1583 break;
1584 }
1585 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 mLock.lock();
1587 }
1588 mLock.unlock();
1589}
1590
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001591void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592{
1593 const size_t SIZE = 256;
1594 char buffer[SIZE];
1595 String8 result;
1596
1597 bool locked = tryLock(mLock);
1598 if (!locked) {
1599 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1600 write(fd, buffer, strlen(buffer));
1601 }
1602
Eric Laurent612bbb52012-03-14 15:03:26 -07001603 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1604 result.append(buffer);
1605 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1606 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1608 result.append(buffer);
1609 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1610 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001611 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1612 result.append(buffer);
1613 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 result.append(buffer);
1615 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1616 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001617 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1618 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1620 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001621 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 result.append(buffer);
1623
1624 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1625 result.append(buffer);
1626 result.append(" Index Command");
1627 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1628 snprintf(buffer, SIZE, "\n %02d ", i);
1629 result.append(buffer);
1630 result.append(mNewParameters[i]);
1631 }
1632
1633 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1634 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001636 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 result.append(buffer);
1638 }
1639 result.append("\n");
1640
1641 write(fd, result.string(), result.size());
1642
1643 if (locked) {
1644 mLock.unlock();
1645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646}
1647
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001648void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001649{
1650 const size_t SIZE = 256;
1651 char buffer[SIZE];
1652 String8 result;
1653
1654 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1655 write(fd, buffer, strlen(buffer));
1656
1657 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1658 sp<EffectChain> chain = mEffectChains[i];
1659 if (chain != 0) {
1660 chain->dump(fd, args);
1661 }
1662 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001663}
1664
Eric Laurentfeb0db62011-07-22 09:04:31 -07001665void AudioFlinger::ThreadBase::acquireWakeLock()
1666{
1667 Mutex::Autolock _l(mLock);
1668 acquireWakeLock_l();
1669}
1670
1671void AudioFlinger::ThreadBase::acquireWakeLock_l()
1672{
1673 if (mPowerManager == 0) {
1674 // use checkService() to avoid blocking if power service is not up yet
1675 sp<IBinder> binder =
1676 defaultServiceManager()->checkService(String16("power"));
1677 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001678 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001679 } else {
1680 mPowerManager = interface_cast<IPowerManager>(binder);
1681 binder->linkToDeath(mDeathRecipient);
1682 }
1683 }
1684 if (mPowerManager != 0) {
1685 sp<IBinder> binder = new BBinder();
1686 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1687 binder,
1688 String16(mName));
1689 if (status == NO_ERROR) {
1690 mWakeLockToken = binder;
1691 }
Steve Block3856b092011-10-20 11:56:00 +01001692 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001693 }
1694}
1695
1696void AudioFlinger::ThreadBase::releaseWakeLock()
1697{
1698 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001699 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001700}
1701
1702void AudioFlinger::ThreadBase::releaseWakeLock_l()
1703{
1704 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001705 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001706 if (mPowerManager != 0) {
1707 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1708 }
1709 mWakeLockToken.clear();
1710 }
1711}
1712
1713void AudioFlinger::ThreadBase::clearPowerManager()
1714{
1715 Mutex::Autolock _l(mLock);
1716 releaseWakeLock_l();
1717 mPowerManager.clear();
1718}
1719
1720void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1721{
1722 sp<ThreadBase> thread = mThread.promote();
1723 if (thread != 0) {
1724 thread->clearPowerManager();
1725 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001726 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001727}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001728
Eric Laurent59255e42011-07-27 19:49:51 -07001729void AudioFlinger::ThreadBase::setEffectSuspended(
1730 const effect_uuid_t *type, bool suspend, int sessionId)
1731{
1732 Mutex::Autolock _l(mLock);
1733 setEffectSuspended_l(type, suspend, sessionId);
1734}
1735
1736void AudioFlinger::ThreadBase::setEffectSuspended_l(
1737 const effect_uuid_t *type, bool suspend, int sessionId)
1738{
Glenn Kasten090f0192012-01-30 13:00:02 -08001739 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001740 if (chain != 0) {
1741 if (type != NULL) {
1742 chain->setEffectSuspended_l(type, suspend);
1743 } else {
1744 chain->setEffectSuspendedAll_l(suspend);
1745 }
1746 }
1747
1748 updateSuspendedSessions_l(type, suspend, sessionId);
1749}
1750
1751void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1752{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001753 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001754 if (index < 0) {
1755 return;
1756 }
1757
Glenn Kasten0a7af182012-07-09 16:09:19 -07001758 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1759 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001760
1761 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001762 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001763 for (int j = 0; j < desc->mRefCount; j++) {
1764 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1765 chain->setEffectSuspendedAll_l(true);
1766 } else {
Steve Block3856b092011-10-20 11:56:00 +01001767 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001768 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001769 chain->setEffectSuspended_l(&desc->mType, true);
1770 }
1771 }
1772 }
1773}
1774
Eric Laurent59255e42011-07-27 19:49:51 -07001775void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1776 bool suspend,
1777 int sessionId)
1778{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001779 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001780
1781 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1782
1783 if (suspend) {
1784 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001785 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001786 } else {
1787 mSuspendedSessions.add(sessionId, sessionEffects);
1788 }
1789 } else {
1790 if (index < 0) {
1791 return;
1792 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001793 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001794 }
1795
1796
1797 int key = EffectChain::kKeyForSuspendAll;
1798 if (type != NULL) {
1799 key = type->timeLow;
1800 }
1801 index = sessionEffects.indexOfKey(key);
1802
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001803 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001804 if (suspend) {
1805 if (index >= 0) {
1806 desc = sessionEffects.valueAt(index);
1807 } else {
1808 desc = new SuspendedSessionDesc();
1809 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001810 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001811 }
1812 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001813 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001814 }
1815 desc->mRefCount++;
1816 } else {
1817 if (index < 0) {
1818 return;
1819 }
1820 desc = sessionEffects.valueAt(index);
1821 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001822 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001823 sessionEffects.removeItemsAt(index);
1824 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001825 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001826 sessionId);
1827 mSuspendedSessions.removeItem(sessionId);
1828 }
1829 }
1830 }
1831 if (!sessionEffects.isEmpty()) {
1832 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1833 }
1834}
1835
1836void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1837 bool enabled,
1838 int sessionId)
1839{
1840 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001841 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1842}
Eric Laurent59255e42011-07-27 19:49:51 -07001843
Eric Laurenta85a74a2011-10-19 11:44:54 -07001844void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1845 bool enabled,
1846 int sessionId)
1847{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001848 if (mType != RECORD) {
1849 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1850 // another session. This gives the priority to well behaved effect control panels
1851 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001852 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1853 // global effects
1854 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001855 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1856 }
1857 }
Eric Laurent59255e42011-07-27 19:49:51 -07001858
1859 sp<EffectChain> chain = getEffectChain_l(sessionId);
1860 if (chain != 0) {
1861 chain->checkSuspendOnEffectEnabled(effect, enabled);
1862 }
1863}
1864
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865// ----------------------------------------------------------------------------
1866
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001867AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1868 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001869 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001870 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001871 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001872 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001873 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001874 // mStreamTypes[] initialized in constructor body
1875 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001876 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001877 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001878 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001879 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001880 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001881 // index 0 is reserved for normal mixer's submix
1882 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883{
Glenn Kasten480b4682012-02-28 12:30:08 -08001884 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001885
John Grossmanee578c02012-07-23 17:05:46 -07001886 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1887 // it would be safer to explicitly pass initial masterVolume/masterMute as
1888 // parameter.
1889 //
1890 // If the HAL we are using has support for master volume or master mute,
1891 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1892 // and the mute set to false).
1893 mMasterVolume = audioFlinger->masterVolume_l();
1894 mMasterMute = audioFlinger->masterMute_l();
1895 if (mOutput && mOutput->audioHwDev) {
1896 if (mOutput->audioHwDev->canSetMasterVolume()) {
1897 mMasterVolume = 1.0;
1898 }
1899
1900 if (mOutput->audioHwDev->canSetMasterMute()) {
1901 mMasterMute = false;
1902 }
1903 }
1904
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 readOutputParameters();
1906
Glenn Kasten263709e2012-01-06 08:40:01 -08001907 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001908 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1909 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1910 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001911 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1912 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001914 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1915 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916}
1917
1918AudioFlinger::PlaybackThread::~PlaybackThread()
1919{
1920 delete [] mMixBuffer;
1921}
1922
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001923void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924{
1925 dumpInternals(fd, args);
1926 dumpTracks(fd, args);
1927 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928}
1929
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001930void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931{
1932 const size_t SIZE = 256;
1933 char buffer[SIZE];
1934 String8 result;
1935
Glenn Kasten58912562012-04-03 10:45:00 -07001936 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1937 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1938 const stream_type_t *st = &mStreamTypes[i];
1939 if (i > 0) {
1940 result.appendFormat(", ");
1941 }
1942 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1943 if (st->mute) {
1944 result.append("M");
1945 }
1946 }
1947 result.append("\n");
1948 write(fd, result.string(), result.length());
1949 result.clear();
1950
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1952 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001953 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 for (size_t i = 0; i < mTracks.size(); ++i) {
1955 sp<Track> track = mTracks[i];
1956 if (track != 0) {
1957 track->dump(buffer, SIZE);
1958 result.append(buffer);
1959 }
1960 }
1961
1962 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1963 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001964 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001966 sp<Track> track = mActiveTracks[i].promote();
1967 if (track != 0) {
1968 track->dump(buffer, SIZE);
1969 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 }
1971 }
1972 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001973
1974 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1975 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1976 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1977 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978}
1979
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001980void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981{
1982 const size_t SIZE = 256;
1983 char buffer[SIZE];
1984 String8 result;
1985
1986 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1987 result.append(buffer);
1988 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1989 result.append(buffer);
1990 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1991 result.append(buffer);
1992 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1993 result.append(buffer);
1994 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1995 result.append(buffer);
1996 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1997 result.append(buffer);
1998 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1999 result.append(buffer);
2000 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002001 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002
2003 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004}
2005
2006// Thread virtuals
2007status_t AudioFlinger::PlaybackThread::readyToRun()
2008{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002009 status_t status = initCheck();
2010 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002011 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002012 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002013 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002015 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016}
2017
2018void AudioFlinger::PlaybackThread::onFirstRef()
2019{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002020 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021}
2022
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002023// ThreadBase virtuals
2024void AudioFlinger::PlaybackThread::preExit()
2025{
2026 ALOGV(" preExit()");
2027 // FIXME this is using hard-coded strings but in the future, this functionality will be
2028 // converted to use audio HAL extensions required to support tunneling
2029 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2030}
2031
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002033sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002035 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002037 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002038 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 int frameCount,
2040 const sp<IMemory>& sharedBuffer,
2041 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002042 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002043 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 status_t *status)
2045{
2046 sp<Track> track;
2047 status_t lStatus;
2048
Glenn Kasten73d22752012-03-19 13:38:30 -07002049 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2050
2051 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002052 if (flags & IAudioFlinger::TRACK_FAST) {
2053 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002054 // not timed
2055 (!isTimed) &&
2056 // either of these use cases:
2057 (
2058 // use case 1: shared buffer with any frame count
2059 (
2060 (sharedBuffer != 0)
2061 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002062 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002063 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002064 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002065 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002066 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002067 )
2068 ) &&
2069 // PCM data
2070 audio_is_linear_pcm(format) &&
2071 // mono or stereo
2072 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2073 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002074#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002075 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002076 (sampleRate == mSampleRate) &&
2077#endif
2078 // normal mixer has an associated fast mixer
2079 hasFastMixer() &&
2080 // there are sufficient fast track slots available
2081 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002082 // FIXME test that MixerThread for this fast track has a capable output HAL
2083 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002084 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002085 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2086 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002087 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002088 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002089 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002090 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002091 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002092 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002093 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002094 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2095 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2096 audio_is_linear_pcm(format),
2097 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002098 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002099 // For compatibility with AudioTrack calculation, buffer depth is forced
2100 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2101 // This is probably too conservative, but legacy application code may depend on it.
2102 // If you change this calculation, also review the start threshold which is related.
2103 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2104 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2105 if (minBufCount < 2) {
2106 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002107 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002108 int minFrameCount = mNormalFrameCount * minBufCount;
2109 if (frameCount < minFrameCount) {
2110 frameCount = minFrameCount;
2111 }
2112 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002113 }
2114
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002116 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2117 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002118 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002119 "for output %p with format %d",
2120 sampleRate, format, channelMask, mOutput, mFormat);
2121 lStatus = BAD_VALUE;
2122 goto Exit;
2123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 }
2125 } else {
2126 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2127 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002128 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 lStatus = BAD_VALUE;
2130 goto Exit;
2131 }
2132 }
2133
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002134 lStatus = initCheck();
2135 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002136 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 goto Exit;
2138 }
2139
2140 { // scope for mLock
2141 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002142
2143 // all tracks in same audio session must share the same routing strategy otherwise
2144 // conflicts will happen when tracks are moved from one output to another by audio policy
2145 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002146 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002147 for (size_t i = 0; i < mTracks.size(); ++i) {
2148 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002149 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002150 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002151 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002152 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002153 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002154 lStatus = BAD_VALUE;
2155 goto Exit;
2156 }
2157 }
2158 }
2159
John Grossman4ff14ba2012-02-08 16:37:41 -08002160 if (!isTimed) {
2161 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002162 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002163 } else {
2164 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2165 channelMask, frameCount, sharedBuffer, sessionId);
2166 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002167 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 lStatus = NO_MEMORY;
2169 goto Exit;
2170 }
2171 mTracks.add(track);
2172
2173 sp<EffectChain> chain = getEffectChain_l(sessionId);
2174 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002175 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002177 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002178 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002180
Eric Laurent896adcd2012-09-13 11:18:23 -07002181 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2182 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2183 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2184 // so ask activity manager to do this on our behalf
2185 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002186 }
2187 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002188
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 lStatus = NO_ERROR;
2190
2191Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002192 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 *status = lStatus;
2194 }
2195 return track;
2196}
2197
Eric Laurente737cda2012-05-22 18:55:44 -07002198uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2199{
2200 if (mFastMixer != NULL) {
2201 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2202 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2203 }
2204 return latency;
2205}
2206
2207uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2208{
2209 return latency;
2210}
2211
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212uint32_t AudioFlinger::PlaybackThread::latency() const
2213{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002214 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002215 return latency_l();
2216}
2217uint32_t AudioFlinger::PlaybackThread::latency_l() const
2218{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002219 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002220 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002221 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 return 0;
2223 }
2224}
2225
Glenn Kasten6637baa2012-01-09 09:40:36 -08002226void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002228 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002229 // Don't apply master volume in SW if our HAL can do it for us.
2230 if (mOutput && mOutput->audioHwDev &&
2231 mOutput->audioHwDev->canSetMasterVolume()) {
2232 mMasterVolume = 1.0;
2233 } else {
2234 mMasterVolume = value;
2235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236}
2237
Glenn Kasten6637baa2012-01-09 09:40:36 -08002238void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002240 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002241 // Don't apply master mute in SW if our HAL can do it for us.
2242 if (mOutput && mOutput->audioHwDev &&
2243 mOutput->audioHwDev->canSetMasterMute()) {
2244 mMasterMute = false;
2245 } else {
2246 mMasterMute = muted;
2247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248}
2249
Glenn Kasten6637baa2012-01-09 09:40:36 -08002250void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002252 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254}
2255
Glenn Kasten6637baa2012-01-09 09:40:36 -08002256void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002258 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260}
2261
Glenn Kastenfff6d712012-01-12 16:38:12 -08002262float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002264 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 return mStreamTypes[stream].volume;
2266}
2267
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268// addTrack_l() must be called with ThreadBase::mLock held
2269status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2270{
2271 status_t status = ALREADY_EXISTS;
2272
2273 // set retry count for buffer fill
2274 track->mRetryCount = kMaxTrackStartupRetries;
2275 if (mActiveTracks.indexOf(track) < 0) {
2276 // the track is newly added, make sure it fills up all its
2277 // buffers before playing. This is to ensure the client will
2278 // effectively get the latency it requested.
2279 track->mFillingUpStatus = Track::FS_FILLING;
2280 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002281 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 mActiveTracks.add(track);
2283 if (track->mainBuffer() != mMixBuffer) {
2284 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2285 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002286 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002287 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289 }
2290
2291 status = NO_ERROR;
2292 }
2293
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 mWaitWorkCV.broadcast();
2296
2297 return status;
2298}
2299
2300// destroyTrack_l() must be called with ThreadBase::mLock held
2301void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2302{
2303 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002304 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002306 removeTrack_l(track);
2307 }
2308}
2309
2310void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2311{
Eric Laurent29864602012-05-08 18:57:51 -07002312 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002313 mTracks.remove(track);
2314 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002315 // redundant as track is about to be destroyed, for dumpsys only
2316 track->mName = -1;
2317 if (track->isFastTrack()) {
2318 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002319 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002320 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2321 mFastTrackAvailMask |= 1 << index;
2322 // redundant as track is about to be destroyed, for dumpsys only
2323 track->mFastIndex = -1;
2324 }
Eric Laurentb469b942011-05-09 12:09:06 -07002325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2326 if (chain != 0) {
2327 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329}
2330
2331String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2332{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002333 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002334 char *s;
2335
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002336 Mutex::Autolock _l(mLock);
2337 if (initCheck() != NO_ERROR) {
2338 return out_s8;
2339 }
2340
Dima Zavin799a70e2011-04-18 16:57:27 -07002341 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002342 out_s8 = String8(s);
2343 free(s);
2344 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345}
2346
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002347// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2349 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002350 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351
Steve Block3856b092011-10-20 11:56:00 +01002352 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353
2354 switch (event) {
2355 case AudioSystem::OUTPUT_OPENED:
2356 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002357 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 desc.samplingRate = mSampleRate;
2359 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002360 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 desc.latency = latency();
2362 param2 = &desc;
2363 break;
2364
2365 case AudioSystem::STREAM_CONFIG_CHANGED:
2366 param2 = &param;
2367 case AudioSystem::OUTPUT_CLOSED:
2368 default:
2369 break;
2370 }
2371 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2372}
2373
2374void AudioFlinger::PlaybackThread::readOutputParameters()
2375{
Dima Zavin799a70e2011-04-18 16:57:27 -07002376 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002377 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2378 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002379 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002380 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002381 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002382 if (mFrameCount & 15) {
2383 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2384 mFrameCount);
2385 }
2386
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002387 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002388 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002389 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002390 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002391 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2392 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2393 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2394 maxNormalFrameCount = maxNormalFrameCount & ~15;
2395 if (maxNormalFrameCount < minNormalFrameCount) {
2396 maxNormalFrameCount = minNormalFrameCount;
2397 }
2398 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2399 if (multiplier <= 1.0) {
2400 multiplier = 1.0;
2401 } else if (multiplier <= 2.0) {
2402 if (2 * mFrameCount <= maxNormalFrameCount) {
2403 multiplier = 2.0;
2404 } else {
2405 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2406 }
2407 } else {
2408 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2409 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2410 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2411 // FIXME this rounding up should not be done if no HAL SRC
2412 uint32_t truncMult = (uint32_t) multiplier;
2413 if ((truncMult & 1)) {
2414 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2415 ++truncMult;
2416 }
2417 }
2418 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002419 }
Glenn Kasten58912562012-04-03 10:45:00 -07002420 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002421 mNormalFrameCount = multiplier * mFrameCount;
2422 // round up to nearest 16 frames to satisfy AudioMixer
2423 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002424 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425
Glenn Kastene9dd0172012-01-27 18:08:45 -08002426 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002427 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2428 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429
Eric Laurentde070132010-07-13 04:45:46 -07002430 // force reconfiguration of effect chains and engines to take new buffer size and audio
2431 // parameters into account
2432 // Note that mLock is not held when readOutputParameters() is called from the constructor
2433 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2434 // matter.
2435 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2436 Vector< sp<EffectChain> > effectChains = mEffectChains;
2437 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002438 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440}
2441
Eric Laurente737cda2012-05-22 18:55:44 -07002442
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2444{
Glenn Kastena0d68332012-01-27 16:47:15 -08002445 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 return BAD_VALUE;
2447 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002448 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002449 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 return INVALID_OPERATION;
2451 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002452 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453
Eric Laurent1afc26d2012-09-23 15:20:50 -07002454 if (isSuspended()) {
2455 // return an estimation of rendered frames when the output is suspended
2456 int32_t frames = mBytesWritten - latency_l();
2457 if (frames < 0) {
2458 frames = 0;
2459 }
2460 *dspFrames = (uint32_t)frames;
2461 return NO_ERROR;
2462 } else {
2463 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465}
2466
Glenn Kasten106e8a42012-08-02 13:37:12 -07002467uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468{
2469 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002470 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002472 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473 }
2474
2475 for (size_t i = 0; i < mTracks.size(); ++i) {
2476 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002477 if (sessionId == track->sessionId() &&
2478 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002479 result |= TRACK_SESSION;
2480 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
2482 }
2483
Eric Laurent39e94f82010-07-28 01:32:47 -07002484 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485}
2486
Eric Laurentde070132010-07-13 04:45:46 -07002487uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2488{
Dima Zavinfce7a472011-04-19 22:30:36 -07002489 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002490 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002491 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2492 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002493 }
2494 for (size_t i = 0; i < mTracks.size(); i++) {
2495 sp<Track> track = mTracks[i];
2496 if (sessionId == track->sessionId() &&
2497 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002498 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002499 }
2500 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002501 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002502}
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504
Glenn Kastenaed850d2012-01-26 09:46:34 -08002505AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002506{
2507 Mutex::Autolock _l(mLock);
2508 return mOutput;
2509}
2510
2511AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2512{
2513 Mutex::Autolock _l(mLock);
2514 AudioStreamOut *output = mOutput;
2515 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002516 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2517 // must push a NULL and wait for ack
2518 mOutputSink.clear();
2519 mPipeSink.clear();
2520 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002521 return output;
2522}
2523
2524// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002525audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002526{
2527 if (mOutput == NULL) {
2528 return NULL;
2529 }
2530 return &mOutput->stream->common;
2531}
2532
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002533uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002534{
Eric Laurentab9071b2012-06-04 13:45:29 -07002535 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002536}
2537
Eric Laurenta011e352012-03-29 15:51:43 -07002538status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2539{
2540 if (!isValidSyncEvent(event)) {
2541 return BAD_VALUE;
2542 }
2543
2544 Mutex::Autolock _l(mLock);
2545
2546 for (size_t i = 0; i < mTracks.size(); ++i) {
2547 sp<Track> track = mTracks[i];
2548 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002549 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002550 return NO_ERROR;
2551 }
2552 }
2553
2554 return NAME_NOT_FOUND;
2555}
2556
Glenn Kasten106e8a42012-08-02 13:37:12 -07002557bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002558{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002559 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002560}
2561
Eric Laurent44a957f2012-05-15 15:26:05 -07002562void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2563{
2564 size_t count = tracksToRemove.size();
2565 if (CC_UNLIKELY(count)) {
2566 for (size_t i = 0 ; i < count ; i++) {
2567 const sp<Track>& track = tracksToRemove.itemAt(i);
2568 if ((track->sharedBuffer() != 0) &&
2569 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2570 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2571 }
2572 }
2573 }
2574
2575}
2576
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577// ----------------------------------------------------------------------------
2578
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002579AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002580 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002581 : PlaybackThread(audioFlinger, output, id, device, type),
2582 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002583 // mFastMixer below
2584 mFastMixerFutex(0)
2585 // mOutputSink below
2586 // mPipeSink below
2587 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002589 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002590 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002591 "mFrameCount=%d, mNormalFrameCount=%d",
2592 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2593 mNormalFrameCount);
2594 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2595
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002597 if (mChannelCount != FCC_2) {
2598 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 }
Glenn Kasten58912562012-04-03 10:45:00 -07002600
2601 // create an NBAIO sink for the HAL output stream, and negotiate
2602 mOutputSink = new AudioStreamOutSink(output->stream);
2603 size_t numCounterOffers = 0;
2604 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2605 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2606 ALOG_ASSERT(index == 0);
2607
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002608 // initialize fast mixer depending on configuration
2609 bool initFastMixer;
2610 switch (kUseFastMixer) {
2611 case FastMixer_Never:
2612 initFastMixer = false;
2613 break;
2614 case FastMixer_Always:
2615 initFastMixer = true;
2616 break;
2617 case FastMixer_Static:
2618 case FastMixer_Dynamic:
2619 initFastMixer = mFrameCount < mNormalFrameCount;
2620 break;
2621 }
2622 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002623
2624 // create a MonoPipe to connect our submix to FastMixer
2625 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002626 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2627 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2628 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2629 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002630 const NBAIO_Format offers[1] = {format};
2631 size_t numCounterOffers = 0;
2632 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2633 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002634 monoPipe->setAvgFrames((mScreenState & 1) ?
2635 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002636 mPipeSink = monoPipe;
2637
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002638#ifdef TEE_SINK_FRAMES
2639 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2640 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2641 numCounterOffers = 0;
2642 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2643 ALOG_ASSERT(index == 0);
2644 mTeeSink = teeSink;
2645 PipeReader *teeSource = new PipeReader(*teeSink);
2646 numCounterOffers = 0;
2647 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2648 ALOG_ASSERT(index == 0);
2649 mTeeSource = teeSource;
2650#endif
2651
Glenn Kasten58912562012-04-03 10:45:00 -07002652 // create fast mixer and configure it initially with just one fast track for our submix
2653 mFastMixer = new FastMixer();
2654 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002655#ifdef STATE_QUEUE_DUMP
2656 sq->setObserverDump(&mStateQueueObserverDump);
2657 sq->setMutatorDump(&mStateQueueMutatorDump);
2658#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002659 FastMixerState *state = sq->begin();
2660 FastTrack *fastTrack = &state->mFastTracks[0];
2661 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2662 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2663 fastTrack->mVolumeProvider = NULL;
2664 fastTrack->mGeneration++;
2665 state->mFastTracksGen++;
2666 state->mTrackMask = 1;
2667 // fast mixer will use the HAL output sink
2668 state->mOutputSink = mOutputSink.get();
2669 state->mOutputSinkGen++;
2670 state->mFrameCount = mFrameCount;
2671 state->mCommand = FastMixerState::COLD_IDLE;
2672 // already done in constructor initialization list
2673 //mFastMixerFutex = 0;
2674 state->mColdFutexAddr = &mFastMixerFutex;
2675 state->mColdGen++;
2676 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002677 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002678 sq->end();
2679 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2680
2681 // start the fast mixer
2682 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002683 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002684 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002685 if (err != 0) {
2686 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002687 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002688 }
Glenn Kasten58912562012-04-03 10:45:00 -07002689
Glenn Kastenc15d6652012-05-30 14:52:57 -07002690#ifdef AUDIO_WATCHDOG
2691 // create and start the watchdog
2692 mAudioWatchdog = new AudioWatchdog();
2693 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2694 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2695 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002696 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002697 if (err != 0) {
2698 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002699 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002700 }
2701#endif
2702
Glenn Kasten58912562012-04-03 10:45:00 -07002703 } else {
2704 mFastMixer = NULL;
2705 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002706
2707 switch (kUseFastMixer) {
2708 case FastMixer_Never:
2709 case FastMixer_Dynamic:
2710 mNormalSink = mOutputSink;
2711 break;
2712 case FastMixer_Always:
2713 mNormalSink = mPipeSink;
2714 break;
2715 case FastMixer_Static:
2716 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2717 break;
2718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719}
2720
2721AudioFlinger::MixerThread::~MixerThread()
2722{
Glenn Kasten58912562012-04-03 10:45:00 -07002723 if (mFastMixer != NULL) {
2724 FastMixerStateQueue *sq = mFastMixer->sq();
2725 FastMixerState *state = sq->begin();
2726 if (state->mCommand == FastMixerState::COLD_IDLE) {
2727 int32_t old = android_atomic_inc(&mFastMixerFutex);
2728 if (old == -1) {
2729 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2730 }
2731 }
2732 state->mCommand = FastMixerState::EXIT;
2733 sq->end();
2734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2735 mFastMixer->join();
2736 // Though the fast mixer thread has exited, it's state queue is still valid.
2737 // We'll use that extract the final state which contains one remaining fast track
2738 // corresponding to our sub-mix.
2739 state = sq->begin();
2740 ALOG_ASSERT(state->mTrackMask == 1);
2741 FastTrack *fastTrack = &state->mFastTracks[0];
2742 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2743 delete fastTrack->mBufferProvider;
2744 sq->end(false /*didModify*/);
2745 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002746#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002747 if (mAudioWatchdog != 0) {
2748 mAudioWatchdog->requestExit();
2749 mAudioWatchdog->requestExitAndWait();
2750 mAudioWatchdog.clear();
2751 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002752#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 delete mAudioMixer;
2755}
2756
Glenn Kasten83efdd02012-02-24 07:21:32 -08002757class CpuStats {
2758public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002759 CpuStats();
2760 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002761#ifdef DEBUG_CPU_USAGE
2762private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002763 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2764 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2765
2766 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2767
2768 int mCpuNum; // thread's current CPU number
2769 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002770#endif
2771};
2772
Glenn Kasten190a46f2012-03-06 11:27:10 -08002773CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002774#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002775 : mCpuNum(-1), mCpukHz(-1)
2776#endif
2777{
2778}
2779
2780void CpuStats::sample(const String8 &title) {
2781#ifdef DEBUG_CPU_USAGE
2782 // get current thread's delta CPU time in wall clock ns
2783 double wcNs;
2784 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2785
2786 // record sample for wall clock statistics
2787 if (valid) {
2788 mWcStats.sample(wcNs);
2789 }
2790
2791 // get the current CPU number
2792 int cpuNum = sched_getcpu();
2793
2794 // get the current CPU frequency in kHz
2795 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2796
2797 // check if either CPU number or frequency changed
2798 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2799 mCpuNum = cpuNum;
2800 mCpukHz = cpukHz;
2801 // ignore sample for purposes of cycles
2802 valid = false;
2803 }
2804
2805 // if no change in CPU number or frequency, then record sample for cycle statistics
2806 if (valid && mCpukHz > 0) {
2807 double cycles = wcNs * cpukHz * 0.000001;
2808 mHzStats.sample(cycles);
2809 }
2810
2811 unsigned n = mWcStats.n();
2812 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002813 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002814 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002815 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2816 double perLoop = elapsed / (double) n;
2817 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002818 double perLoop1k = perLoop * 0.001;
2819 double mean = mWcStats.mean();
2820 double stddev = mWcStats.stddev();
2821 double minimum = mWcStats.minimum();
2822 double maximum = mWcStats.maximum();
2823 double meanCycles = mHzStats.mean();
2824 double stddevCycles = mHzStats.stddev();
2825 double minCycles = mHzStats.minimum();
2826 double maxCycles = mHzStats.maximum();
2827 mCpuUsage.resetElapsed();
2828 mWcStats.reset();
2829 mHzStats.reset();
2830 ALOGD("CPU usage for %s over past %.1f secs\n"
2831 " (%u mixer loops at %.1f mean ms per loop):\n"
2832 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2833 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2834 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2835 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002836 elapsed * .000000001, n, perLoop * .000001,
2837 mean * .001,
2838 stddev * .001,
2839 minimum * .001,
2840 maximum * .001,
2841 mean / perLoop100,
2842 stddev / perLoop100,
2843 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002844 maximum / perLoop100,
2845 meanCycles / perLoop1k,
2846 stddevCycles / perLoop1k,
2847 minCycles / perLoop1k,
2848 maxCycles / perLoop1k);
2849
Glenn Kasten83efdd02012-02-24 07:21:32 -08002850 }
2851 }
2852#endif
2853};
2854
Glenn Kasten37d825e2012-02-24 07:21:48 -08002855void AudioFlinger::PlaybackThread::checkSilentMode_l()
2856{
2857 if (!mMasterMute) {
2858 char value[PROPERTY_VALUE_MAX];
2859 if (property_get("ro.audio.silent", value, "0") > 0) {
2860 char *endptr;
2861 unsigned long ul = strtoul(value, &endptr, 0);
2862 if (*endptr == '\0' && ul != 0) {
2863 ALOGD("Silence is golden");
2864 // The setprop command will not allow a property to be changed after
2865 // the first time it is set, so we don't have to worry about un-muting.
2866 setMasterMute_l(true);
2867 }
2868 }
2869 }
2870}
2871
Glenn Kasten000f0e32012-03-01 17:10:56 -08002872bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873{
2874 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002875
Glenn Kasten000f0e32012-03-01 17:10:56 -08002876 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002877
2878 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002880
Glenn Kasten000f0e32012-03-01 17:10:56 -08002881 // DUPLICATING
2882 // FIXME could this be made local to while loop?
2883 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002884
Glenn Kasten66fcab92012-02-24 14:59:21 -08002885 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002886 sleepTime = idleSleepTime;
2887
Glenn Kasten9f34a362012-03-20 16:46:41 -07002888 if (mType == MIXER) {
2889 sleepTimeShift = 0;
2890 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002891
Glenn Kasten83efdd02012-02-24 07:21:32 -08002892 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002893 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894
Eric Laurentfeb0db62011-07-22 09:04:31 -07002895 acquireWakeLock();
2896
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 while (!exitPending())
2898 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002899 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002900
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002901 Vector< sp<EffectChain> > effectChains;
2902
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 processConfigEvents();
2904
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 { // scope for mLock
2906
2907 Mutex::Autolock _l(mLock);
2908
2909 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002910 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 }
2912
Glenn Kastenfa26a852012-03-06 11:28:04 -08002913 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002914
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002916 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002917 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002919
2920 threadLoop_standby();
2921
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 }
2924
Glenn Kasten3e074702012-02-28 18:40:35 -08002925 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 // we're about to wait, flush the binder command buffer
2927 IPCThreadState::self()->flushCommands();
2928
Glenn Kastenfa26a852012-03-06 11:28:04 -08002929 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002930
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 if (exitPending()) break;
2932
Eric Laurentfeb0db62011-07-22 09:04:31 -07002933 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002935 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002937 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002938 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Eric Laurentda747442012-04-25 18:53:13 -07002940 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002941 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002942 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002943
Glenn Kasten37d825e2012-02-24 07:21:48 -08002944 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945
Glenn Kasten000f0e32012-03-01 17:10:56 -08002946 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002948 if (mType == MIXER) {
2949 sleepTimeShift = 0;
2950 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002951
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 continue;
2953 }
2954 }
2955
Glenn Kasten81028042012-04-30 18:15:12 -07002956 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002957 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958
2959 // prevent any changes in effect chain list and in each effect chain
2960 // during mixing and effect process as the audio buffers could be deleted
2961 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002962 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964
Glenn Kastenfec279f2012-03-08 07:47:15 -08002965 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002966 threadLoop_mix();
2967 } else {
2968 threadLoop_sleepTime();
2969 }
2970
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002971 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002972 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002973 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002974 }
2975
2976 // only process effects if we're going to write
2977 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002978 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08002979#ifdef QCOM_HARDWARE
2980 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
2981#endif
2982 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002983 }
2984 }
2985
2986 // enable changes in effect chain
2987 unlockEffectChains(effectChains);
2988
2989 // sleepTime == 0 means we must write to audio hardware
2990 if (sleepTime == 0) {
2991
2992 threadLoop_write();
2993
2994if (mType == MIXER) {
2995 // write blocked detection
2996 nsecs_t now = systemTime();
2997 nsecs_t delta = now - mLastWriteTime;
2998 if (!mStandby && delta > maxPeriod) {
2999 mNumDelayedWrites++;
3000 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003001#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003002 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003003#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003004 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3005 ns2ms(delta), mNumDelayedWrites, this);
3006 lastWarning = now;
3007 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003008 }
3009}
3010
3011 mStandby = false;
3012 } else {
3013 usleep(sleepTime);
3014 }
3015
Glenn Kasten58912562012-04-03 10:45:00 -07003016 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003017 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003018 // same lock. This will also mutate and push a new fast mixer state.
3019 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003020 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003021
Glenn Kastenfa26a852012-03-06 11:28:04 -08003022 // FIXME I don't understand the need for this here;
3023 // it was in the original code but maybe the
3024 // assignment in saveOutputTracks() makes this unnecessary?
3025 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003026
3027 // Effect chains will be actually deleted here if they were removed from
3028 // mEffectChains list during mixing or effects processing
3029 effectChains.clear();
3030
3031 // FIXME Note that the above .clear() is no longer necessary since effectChains
3032 // is now local to this block, but will keep it for now (at least until merge done).
3033 }
3034
Glenn Kasten9f34a362012-03-20 16:46:41 -07003035 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3036 if (mType == MIXER || mType == DIRECT) {
3037 // put output stream into standby mode
3038 if (!mStandby) {
3039 mOutput->stream->common.standby(&mOutput->stream->common);
3040 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003041 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003042
3043 releaseWakeLock();
3044
3045 ALOGV("Thread %p type %d exiting", this, mType);
3046 return false;
3047}
3048
Glenn Kasten58912562012-04-03 10:45:00 -07003049void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3050{
Glenn Kasten58912562012-04-03 10:45:00 -07003051 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3052}
3053
3054void AudioFlinger::MixerThread::threadLoop_write()
3055{
3056 // FIXME we should only do one push per cycle; confirm this is true
3057 // Start the fast mixer if it's not already running
3058 if (mFastMixer != NULL) {
3059 FastMixerStateQueue *sq = mFastMixer->sq();
3060 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003061 if (state->mCommand != FastMixerState::MIX_WRITE &&
3062 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003063 if (state->mCommand == FastMixerState::COLD_IDLE) {
3064 int32_t old = android_atomic_inc(&mFastMixerFutex);
3065 if (old == -1) {
3066 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3067 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003068#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003069 if (mAudioWatchdog != 0) {
3070 mAudioWatchdog->resume();
3071 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003072#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003073 }
3074 state->mCommand = FastMixerState::MIX_WRITE;
3075 sq->end();
3076 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003077 if (kUseFastMixer == FastMixer_Dynamic) {
3078 mNormalSink = mPipeSink;
3079 }
Glenn Kasten58912562012-04-03 10:45:00 -07003080 } else {
3081 sq->end(false /*didModify*/);
3082 }
3083 }
3084 PlaybackThread::threadLoop_write();
3085}
3086
Glenn Kasten000f0e32012-03-01 17:10:56 -08003087// shared by MIXER and DIRECT, overridden by DUPLICATING
3088void AudioFlinger::PlaybackThread::threadLoop_write()
3089{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003090 // FIXME rewrite to reduce number of system calls
3091 mLastWriteTime = systemTime();
3092 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003093 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003094
Eric Laurent67c0a582012-05-01 19:31:12 -07003095 // If an NBAIO sink is present, use it to write the normal mixer's submix
3096 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003097#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003098 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003099#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003100 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003101#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003102 // update the setpoint when gScreenState changes
3103 uint32_t screenState = gScreenState;
3104 if (screenState != mScreenState) {
3105 mScreenState = screenState;
3106 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3107 if (pipe != NULL) {
3108 pipe->setAvgFrames((mScreenState & 1) ?
3109 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3110 }
3111 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003112 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003113#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003114 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003115#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003116 if (framesWritten > 0) {
3117 bytesWritten = framesWritten << mBitShift;
3118 } else {
3119 bytesWritten = framesWritten;
3120 }
3121 // otherwise use the HAL / AudioStreamOut directly
3122 } else {
3123 // Direct output thread.
3124 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003125 }
3126
Eric Laurent67c0a582012-05-01 19:31:12 -07003127 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003128 mNumWrites++;
3129 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003130}
3131
Glenn Kasten58912562012-04-03 10:45:00 -07003132void AudioFlinger::MixerThread::threadLoop_standby()
3133{
3134 // Idle the fast mixer if it's currently running
3135 if (mFastMixer != NULL) {
3136 FastMixerStateQueue *sq = mFastMixer->sq();
3137 FastMixerState *state = sq->begin();
3138 if (!(state->mCommand & FastMixerState::IDLE)) {
3139 state->mCommand = FastMixerState::COLD_IDLE;
3140 state->mColdFutexAddr = &mFastMixerFutex;
3141 state->mColdGen++;
3142 mFastMixerFutex = 0;
3143 sq->end();
3144 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3145 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003146 if (kUseFastMixer == FastMixer_Dynamic) {
3147 mNormalSink = mOutputSink;
3148 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003149#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003150 if (mAudioWatchdog != 0) {
3151 mAudioWatchdog->pause();
3152 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003153#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003154 } else {
3155 sq->end(false /*didModify*/);
3156 }
3157 }
3158 PlaybackThread::threadLoop_standby();
3159}
3160
Glenn Kasten000f0e32012-03-01 17:10:56 -08003161// shared by MIXER and DIRECT, overridden by DUPLICATING
3162void AudioFlinger::PlaybackThread::threadLoop_standby()
3163{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003164 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003165 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003166}
3167
3168void AudioFlinger::MixerThread::threadLoop_mix()
3169{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003170 // obtain the presentation timestamp of the next output buffer
3171 int64_t pts;
3172 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003173
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003174#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003175 if (mNormalSink != 0) {
3176 status = mNormalSink->getNextWriteTimestamp(&pts);
3177 } else {
3178 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003179 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003180#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003181
Glenn Kasten952eeb22012-03-06 11:30:57 -08003182 if (status != NO_ERROR) {
3183 pts = AudioBufferProvider::kInvalidPTS;
3184 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003185
Glenn Kasten952eeb22012-03-06 11:30:57 -08003186 // mix buffers...
3187 mAudioMixer->process(pts);
3188 // increase sleep time progressively when application underrun condition clears.
3189 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3190 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3191 // such that we would underrun the audio HAL.
3192 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3193 sleepTimeShift--;
3194 }
3195 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003196 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003197 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003198}
3199
3200void AudioFlinger::MixerThread::threadLoop_sleepTime()
3201{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003202 // If no tracks are ready, sleep once for the duration of an output
3203 // buffer size, then write 0s to the output
3204 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003205 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003206 sleepTime = activeSleepTime >> sleepTimeShift;
3207 if (sleepTime < kMinThreadSleepTimeUs) {
3208 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003210 // reduce sleep time in case of consecutive application underruns to avoid
3211 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3212 // duration we would end up writing less data than needed by the audio HAL if
3213 // the condition persists.
3214 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3215 sleepTimeShift++;
3216 }
3217 } else {
3218 sleepTime = idleSleepTime;
3219 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003220 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003221 memset (mMixBuffer, 0, mixBufferSize);
3222 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003223 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003224 }
3225 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226}
3227
3228// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003229AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003230 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231{
3232
Glenn Kasten29c23c32012-01-26 13:37:52 -08003233 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003235 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 size_t mixedTracks = 0;
3237 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003238 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003239 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003240 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241
3242 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003243 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244
Eric Laurent571d49c2010-08-11 05:20:11 -07003245 if (masterMute) {
3246 masterVolume = 0;
3247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003249 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003251 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003252 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 masterVolume = (float)((v + (1 << 23)) >> 24);
3254 chain.clear();
3255 }
3256
Glenn Kasten288ed212012-04-25 17:52:27 -07003257 // prepare a new state to push
3258 FastMixerStateQueue *sq = NULL;
3259 FastMixerState *state = NULL;
3260 bool didModify = false;
3261 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3262 if (mFastMixer != NULL) {
3263 sq = mFastMixer->sq();
3264 state = sq->begin();
3265 }
3266
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003268 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 if (t == 0) continue;
3270
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003271 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003273
Glenn Kasten288ed212012-04-25 17:52:27 -07003274 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003275 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003276
3277 // It's theoretically possible (though unlikely) for a fast track to be created
3278 // and then removed within the same normal mix cycle. This is not a problem, as
3279 // the track never becomes active so it's fast mixer slot is never touched.
3280 // The converse, of removing an (active) track and then creating a new track
3281 // at the identical fast mixer slot within the same normal mix cycle,
3282 // is impossible because the slot isn't marked available until the end of each cycle.
3283 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003284 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3285 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003286 FastTrack *fastTrack = &state->mFastTracks[j];
3287
3288 // Determine whether the track is currently in underrun condition,
3289 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003290 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3291 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003292 uint32_t recentFull = (underruns.mBitFields.mFull -
3293 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3294 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3295 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3296 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3297 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3298 uint32_t recentUnderruns = recentPartial + recentEmpty;
3299 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003300 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003301 // or stopped which can occur when flush() is called while active
3302 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003303 track->mUnderrunCount += recentUnderruns;
3304 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003305
Glenn Kastend08f48c2012-05-01 18:14:02 -07003306 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003307 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003308 bool isActive = true;
3309 switch (track->mState) {
3310 case TrackBase::STOPPING_1:
3311 // track stays active in STOPPING_1 state until first underrun
3312 if (recentUnderruns > 0) {
3313 track->mState = TrackBase::STOPPING_2;
3314 }
3315 break;
3316 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003317 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003318 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003319 break;
3320 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003321 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003322 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003323 break;
3324 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003325 if (recentFull > 0 || recentPartial > 0) {
3326 // track has provided at least some frames recently: reset retry count
3327 track->mRetryCount = kMaxTrackRetries;
3328 }
3329 if (recentUnderruns == 0) {
3330 // no recent underruns: stay active
3331 break;
3332 }
3333 // there has recently been an underrun of some kind
3334 if (track->sharedBuffer() == 0) {
3335 // were any of the recent underruns "empty" (no frames available)?
3336 if (recentEmpty == 0) {
3337 // no, then ignore the partial underruns as they are allowed indefinitely
3338 break;
3339 }
3340 // there has recently been an "empty" underrun: decrement the retry counter
3341 if (--(track->mRetryCount) > 0) {
3342 break;
3343 }
3344 // indicate to client process that the track was disabled because of underrun;
3345 // it will then automatically call start() when data is available
3346 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3347 // remove from active list, but state remains ACTIVE [confusing but true]
3348 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003349 break;
3350 }
3351 // fall through
3352 case TrackBase::STOPPING_2:
3353 case TrackBase::PAUSED:
3354 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003355 case TrackBase::STOPPED:
3356 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003357 // Check for presentation complete if track is inactive
3358 // We have consumed all the buffers of this track.
3359 // This would be incomplete if we auto-paused on underrun
3360 {
3361 size_t audioHALFrames =
3362 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3363 size_t framesWritten =
3364 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003365 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003366 // track stays in active list until presentation is complete
3367 break;
3368 }
3369 }
3370 if (track->isStopping_2()) {
3371 track->mState = TrackBase::STOPPED;
3372 }
3373 if (track->isStopped()) {
3374 // Can't reset directly, as fast mixer is still polling this track
3375 // track->reset();
3376 // So instead mark this track as needing to be reset after push with ack
3377 resetMask |= 1 << i;
3378 }
3379 isActive = false;
3380 break;
3381 case TrackBase::IDLE:
3382 default:
3383 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003384 }
3385
3386 if (isActive) {
3387 // was it previously inactive?
3388 if (!(state->mTrackMask & (1 << j))) {
3389 ExtendedAudioBufferProvider *eabp = track;
3390 VolumeProvider *vp = track;
3391 fastTrack->mBufferProvider = eabp;
3392 fastTrack->mVolumeProvider = vp;
3393 fastTrack->mSampleRate = track->mSampleRate;
3394 fastTrack->mChannelMask = track->mChannelMask;
3395 fastTrack->mGeneration++;
3396 state->mTrackMask |= 1 << j;
3397 didModify = true;
3398 // no acknowledgement required for newly active tracks
3399 }
3400 // cache the combined master volume and stream type volume for fast mixer; this
3401 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3402 track->mCachedVolume = track->isMuted() ?
3403 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3404 ++fastTracks;
3405 } else {
3406 // was it previously active?
3407 if (state->mTrackMask & (1 << j)) {
3408 fastTrack->mBufferProvider = NULL;
3409 fastTrack->mGeneration++;
3410 state->mTrackMask &= ~(1 << j);
3411 didModify = true;
3412 // If any fast tracks were removed, we must wait for acknowledgement
3413 // because we're about to decrement the last sp<> on those tracks.
3414 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003415 } else {
3416 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003417 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003418 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003419 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003420 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003421 }
3422 continue;
3423 }
3424
3425 { // local variable scope to avoid goto warning
3426
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 audio_track_cblk_t* cblk = track->cblk();
3428
3429 // The first time a track is added we wait
3430 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003431 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003432 // make sure that we have enough frames to mix one full buffer.
3433 // enforce this condition only once to enable draining the buffer in case the client
3434 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003435 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003436 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003437 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003438 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003439 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003440 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003441 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003442 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003443 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003444 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003445 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003446 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003447 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3448 // the minimum track buffer size is normally twice the number of frames necessary
3449 // to fill one buffer and the resampler should not leave more than one buffer worth
3450 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003451 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003452 }
3453 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003454 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 !track->isPaused() && !track->isTerminated())
3456 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003457 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458
3459 mixedTracks++;
3460
3461 // track->mainBuffer() != mMixBuffer means there is an effect chain
3462 // connected to the track
3463 chain.clear();
3464 if (track->mainBuffer() != mMixBuffer) {
3465 chain = getEffectChain_l(track->sessionId());
3466 // Delegate volume control to effect in track effect chain if needed
3467 if (chain != 0) {
3468 tracksWithEffect++;
3469 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003470 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003471 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 }
3473 }
3474
3475
3476 int param = AudioMixer::VOLUME;
3477 if (track->mFillingUpStatus == Track::FS_FILLED) {
3478 // no ramp for the first volume setting
3479 track->mFillingUpStatus = Track::FS_ACTIVE;
3480 if (track->mState == TrackBase::RESUMING) {
3481 track->mState = TrackBase::ACTIVE;
3482 param = AudioMixer::RAMP_VOLUME;
3483 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003484 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 } else if (cblk->server != 0) {
3486 // If the track is stopped before the first frame was mixed,
3487 // do not apply ramp
3488 param = AudioMixer::RAMP_VOLUME;
3489 }
3490
3491 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003492 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003493 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003494 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003495 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 if (track->isPausing()) {
3497 track->setPaused();
3498 }
3499 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003500
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003502 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003504 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003505 vl = vlr & 0xFFFF;
3506 vr = vlr >> 16;
3507 // track volumes come from shared memory, so can't be trusted and must be clamped
3508 if (vl > MAX_GAIN_INT) {
3509 ALOGV("Track left volume out of range: %04X", vl);
3510 vl = MAX_GAIN_INT;
3511 }
3512 if (vr > MAX_GAIN_INT) {
3513 ALOGV("Track right volume out of range: %04X", vr);
3514 vr = MAX_GAIN_INT;
3515 }
3516 // now apply the master volume and stream type volume
3517 vl = (uint32_t)(v * vl) << 12;
3518 vr = (uint32_t)(v * vr) << 12;
3519 // assuming master volume and stream type volume each go up to 1.0,
3520 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521
Glenn Kasten05632a52012-01-03 14:22:33 -08003522 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3523 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003524 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003525 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003526 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003527 }
3528 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003530 // Delegate volume control to effect in track effect chain if needed
3531 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3532 // Do not ramp volume if volume is controlled by effect
3533 param = AudioMixer::VOLUME;
3534 track->mHasVolumeController = true;
3535 } else {
3536 // force no volume ramp when volume controller was just disabled or removed
3537 // from effect chain to avoid volume spike
3538 if (track->mHasVolumeController) {
3539 param = AudioMixer::VOLUME;
3540 }
3541 track->mHasVolumeController = false;
3542 }
3543
3544 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003545 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003546 vl = (vl + (1 << 11)) >> 12;
3547 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3548 vr = (vr + (1 << 11)) >> 12;
3549 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003550
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003551 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003554 mAudioMixer->setBufferProvider(name, track);
3555 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003557 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3558 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3559 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003561 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 AudioMixer::TRACK,
3563 AudioMixer::FORMAT, (void *)track->format());
3564 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003565 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003567 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003569 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 AudioMixer::RESAMPLE,
3571 AudioMixer::SAMPLE_RATE,
3572 (void *)(cblk->sampleRate));
3573 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003574 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 AudioMixer::TRACK,
3576 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3577 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003578 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 AudioMixer::TRACK,
3580 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3581
3582 // reset retry count
3583 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003584
Eric Laurent27741442012-01-17 19:20:12 -08003585 // If one track is ready, set the mixer ready if:
3586 // - the mixer was not ready during previous round OR
3587 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003588 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003589 mixerStatus != MIXER_TRACKS_ENABLED) {
3590 mixerStatus = MIXER_TRACKS_READY;
3591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003593 // clear effect chain input buffer if an active track underruns to avoid sending
3594 // previous audio buffer again to effects
3595 chain = getEffectChain_l(track->sessionId());
3596 if (chain != 0) {
3597 chain->clearInputBuffer();
3598 }
3599
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003600 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003601 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003602 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 // We have consumed all the buffers of this track.
3604 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003605 // TODO: use actual buffer filling status instead of latency when available from
3606 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003607 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003608 size_t framesWritten =
3609 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003610 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003611 if (track->isStopped()) {
3612 track->reset();
3613 }
Eric Laurenta011e352012-03-29 15:51:43 -07003614 tracksToRemove->add(track);
3615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003617 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 // No buffers for this track. Give it a few chances to
3619 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003620 if (--(track->mRetryCount) <= 0) {
3621 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003623 // indicate to client process that the track was disabled because of underrun;
3624 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003625 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003626 // If one track is not ready, mark the mixer also not ready if:
3627 // - the mixer was ready during previous round OR
3628 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003629 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003630 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 mixerStatus = MIXER_TRACKS_ENABLED;
3632 }
3633 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003634 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 }
Glenn Kasten58912562012-04-03 10:45:00 -07003636
3637 } // local variable scope to avoid goto warning
3638track_is_ready: ;
3639
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 }
3641
Glenn Kasten288ed212012-04-25 17:52:27 -07003642 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003643 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003644 if (didModify) {
3645 state->mFastTracksGen++;
3646 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3647 if (kUseFastMixer == FastMixer_Dynamic &&
3648 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3649 state->mCommand = FastMixerState::COLD_IDLE;
3650 state->mColdFutexAddr = &mFastMixerFutex;
3651 state->mColdGen++;
3652 mFastMixerFutex = 0;
3653 if (kUseFastMixer == FastMixer_Dynamic) {
3654 mNormalSink = mOutputSink;
3655 }
3656 // If we go into cold idle, need to wait for acknowledgement
3657 // so that fast mixer stops doing I/O.
3658 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003659 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003660 }
3661 sq->end();
3662 }
3663 if (sq != NULL) {
3664 sq->end(didModify);
3665 sq->push(block);
3666 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003667#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003668 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3669 mAudioWatchdog->pause();
3670 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003671#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003672
3673 // Now perform the deferred reset on fast tracks that have stopped
3674 while (resetMask != 0) {
3675 size_t i = __builtin_ctz(resetMask);
3676 ALOG_ASSERT(i < count);
3677 resetMask &= ~(1 << i);
3678 sp<Track> t = mActiveTracks[i].promote();
3679 if (t == 0) continue;
3680 Track* track = t.get();
3681 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3682 track->reset();
3683 }
Glenn Kasten58912562012-04-03 10:45:00 -07003684
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 // remove all the tracks that need to be...
3686 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003687 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 for (size_t i=0 ; i<count ; i++) {
3689 const sp<Track>& track = tracksToRemove->itemAt(i);
3690 mActiveTracks.remove(track);
3691 if (track->mainBuffer() != mMixBuffer) {
3692 chain = getEffectChain_l(track->sessionId());
3693 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003694 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003695 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 }
3697 }
3698 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003699 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 }
3701 }
3702 }
3703
3704 // mix buffer must be cleared if all tracks are connected to an
3705 // effect chain as in this case the mixer will not write to
3706 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003707 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3708 // FIXME as a performance optimization, should remember previous zero status
3709 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 }
3711
Glenn Kasten58912562012-04-03 10:45:00 -07003712 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003713 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003714 if (fastTracks > 0) {
3715 mixerStatus = MIXER_TRACKS_READY;
3716 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 return mixerStatus;
3718}
3719
Glenn Kasten66fcab92012-02-24 14:59:21 -08003720/*
3721The derived values that are cached:
3722 - mixBufferSize from frame count * frame size
3723 - activeSleepTime from activeSleepTimeUs()
3724 - idleSleepTime from idleSleepTimeUs()
3725 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3726 - maxPeriod from frame count and sample rate (MIXER only)
3727
3728The parameters that affect these derived values are:
3729 - frame count
3730 - frame size
3731 - sample rate
3732 - device type: A2DP or not
3733 - device latency
3734 - format: PCM or not
3735 - active sleep time
3736 - idle sleep time
3737*/
3738
3739void AudioFlinger::PlaybackThread::cacheParameters_l()
3740{
Glenn Kasten58912562012-04-03 10:45:00 -07003741 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003742 activeSleepTime = activeSleepTimeUs();
3743 idleSleepTime = idleSleepTimeUs();
3744}
3745
Eric Laurent22167852012-06-20 12:26:32 -07003746void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747{
Steve Block3856b092011-10-20 11:56:00 +01003748 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003749 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003751
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 size_t size = mTracks.size();
3753 for (size_t i = 0; i < size; i++) {
3754 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003755 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003756 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 }
3759 }
3760}
3761
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003763int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003765 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766}
3767
3768// deleteTrackName_l() must be called with ThreadBase::mLock held
3769void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3770{
Steve Block3856b092011-10-20 11:56:00 +01003771 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 mAudioMixer->deleteTrackName(name);
3773}
3774
3775// checkForNewParameters_l() must be called with ThreadBase::mLock held
3776bool AudioFlinger::MixerThread::checkForNewParameters_l()
3777{
Glenn Kasten58912562012-04-03 10:45:00 -07003778 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3779 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 bool reconfig = false;
3781
3782 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003783
3784 if (mFastMixer != NULL) {
3785 FastMixerStateQueue *sq = mFastMixer->sq();
3786 FastMixerState *state = sq->begin();
3787 if (!(state->mCommand & FastMixerState::IDLE)) {
3788 previousCommand = state->mCommand;
3789 state->mCommand = FastMixerState::HOT_IDLE;
3790 sq->end();
3791 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3792 } else {
3793 sq->end(false /*didModify*/);
3794 }
3795 }
3796
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 status_t status = NO_ERROR;
3798 String8 keyValuePair = mNewParameters[0];
3799 AudioParameter param = AudioParameter(keyValuePair);
3800 int value;
3801
3802 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3803 reconfig = true;
3804 }
3805 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003806 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 status = BAD_VALUE;
3808 } else {
3809 reconfig = true;
3810 }
3811 }
3812 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003813 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 status = BAD_VALUE;
3815 } else {
3816 reconfig = true;
3817 }
3818 }
3819 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3820 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003821 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 // if frame count is changed after track creation
3823 if (!mTracks.isEmpty()) {
3824 status = INVALID_OPERATION;
3825 } else {
3826 reconfig = true;
3827 }
3828 }
3829 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003830#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003831 // when changing the audio output device, call addBatteryData to notify
3832 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003833 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003834 uint32_t params = 0;
3835 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003836 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003837 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3838 }
3839
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003840 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003841 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003842 // check if any other device (except speaker) is on
3843 if (value & deviceWithoutSpeaker ) {
3844 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3845 }
3846
3847 if (params != 0) {
3848 addBatteryData(params);
3849 }
3850 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003851#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003852
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 // forward device change to effects that have requested to be
3854 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003855 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003857 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 }
3859 }
3860
3861 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003862 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003863 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003865 mOutput->stream->common.standby(&mOutput->stream->common);
3866 mStandby = true;
3867 mBytesWritten = 0;
3868 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003869 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 }
3871 if (status == NO_ERROR && reconfig) {
3872 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003873 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3874 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003876 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003878 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 if (name < 0) break;
3880 mTracks[i]->mName = name;
3881 // limit track sample rate to 2 x new output sample rate
3882 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3883 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3884 }
3885 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003886 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 }
3888 }
3889
3890 mNewParameters.removeAt(0);
3891
3892 mParamStatus = status;
3893 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003894 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3895 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003896 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 }
Glenn Kasten58912562012-04-03 10:45:00 -07003898
3899 if (!(previousCommand & FastMixerState::IDLE)) {
3900 ALOG_ASSERT(mFastMixer != NULL);
3901 FastMixerStateQueue *sq = mFastMixer->sq();
3902 FastMixerState *state = sq->begin();
3903 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3904 state->mCommand = previousCommand;
3905 sq->end();
3906 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3907 }
3908
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 return reconfig;
3910}
3911
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003912void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913{
3914 const size_t SIZE = 256;
3915 char buffer[SIZE];
3916 String8 result;
3917
3918 PlaybackThread::dumpInternals(fd, args);
3919
3920 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3921 result.append(buffer);
3922 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003923
3924 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3925 FastMixerDumpState copy = mFastMixerDumpState;
3926 copy.dump(fd);
3927
Glenn Kasten39993082012-05-31 13:40:27 -07003928#ifdef STATE_QUEUE_DUMP
3929 // Similar for state queue
3930 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3931 observerCopy.dump(fd);
3932 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3933 mutatorCopy.dump(fd);
3934#endif
3935
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003936 // Write the tee output to a .wav file
3937 NBAIO_Source *teeSource = mTeeSource.get();
3938 if (teeSource != NULL) {
3939 char teePath[64];
3940 struct timeval tv;
3941 gettimeofday(&tv, NULL);
3942 struct tm tm;
3943 localtime_r(&tv.tv_sec, &tm);
3944 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3945 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3946 if (teeFd >= 0) {
3947 char wavHeader[44];
3948 memcpy(wavHeader,
3949 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3950 sizeof(wavHeader));
3951 NBAIO_Format format = teeSource->format();
3952 unsigned channelCount = Format_channelCount(format);
3953 ALOG_ASSERT(channelCount <= FCC_2);
3954 unsigned sampleRate = Format_sampleRate(format);
3955 wavHeader[22] = channelCount; // number of channels
3956 wavHeader[24] = sampleRate; // sample rate
3957 wavHeader[25] = sampleRate >> 8;
3958 wavHeader[32] = channelCount * 2; // block alignment
3959 write(teeFd, wavHeader, sizeof(wavHeader));
3960 size_t total = 0;
3961 bool firstRead = true;
3962 for (;;) {
3963#define TEE_SINK_READ 1024
3964 short buffer[TEE_SINK_READ * FCC_2];
3965 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003966 ssize_t actual = teeSource->read(buffer, count,
3967 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003968 bool wasFirstRead = firstRead;
3969 firstRead = false;
3970 if (actual <= 0) {
3971 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3972 continue;
3973 }
3974 break;
3975 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003976 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003977 write(teeFd, buffer, actual * channelCount * sizeof(short));
3978 total += actual;
3979 }
3980 lseek(teeFd, (off_t) 4, SEEK_SET);
3981 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3982 write(teeFd, &temp, sizeof(temp));
3983 lseek(teeFd, (off_t) 40, SEEK_SET);
3984 temp = total * channelCount * sizeof(short);
3985 write(teeFd, &temp, sizeof(temp));
3986 close(teeFd);
3987 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3988 } else {
3989 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3990 }
3991 }
3992
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003993#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003994 if (mAudioWatchdog != 0) {
3995 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3996 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3997 wdCopy.dump(fd);
3998 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003999#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000}
4001
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004002uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003{
Glenn Kasten58912562012-04-03 10:45:00 -07004004 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005}
4006
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004007uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004008{
Glenn Kasten58912562012-04-03 10:45:00 -07004009 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004010}
4011
Glenn Kasten66fcab92012-02-24 14:59:21 -08004012void AudioFlinger::MixerThread::cacheParameters_l()
4013{
4014 PlaybackThread::cacheParameters_l();
4015
4016 // FIXME: Relaxed timing because of a certain device that can't meet latency
4017 // Should be reduced to 2x after the vendor fixes the driver issue
4018 // increase threshold again due to low power audio mode. The way this warning
4019 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004020 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004021}
4022
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004024AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004025 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004026 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004027 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
4031AudioFlinger::DirectOutputThread::~DirectOutputThread()
4032{
4033}
4034
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004035AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4036 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004037)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004039 sp<Track> trackToRemove;
4040
Glenn Kastenfec279f2012-03-08 07:47:15 -08004041 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042
Glenn Kasten952eeb22012-03-06 11:30:57 -08004043 // find out which tracks need to be processed
4044 if (mActiveTracks.size() != 0) {
4045 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004046 // The track died recently
4047 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048
Glenn Kasten952eeb22012-03-06 11:30:57 -08004049 Track* const track = t.get();
4050 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051
Glenn Kasten952eeb22012-03-06 11:30:57 -08004052 // The first time a track is added we wait
4053 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004054 uint32_t minFrames;
4055 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4056 minFrames = mNormalFrameCount;
4057 } else {
4058 minFrames = 1;
4059 }
4060 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004061 !track->isPaused() && !track->isTerminated())
4062 {
4063 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064
Glenn Kasten952eeb22012-03-06 11:30:57 -08004065 if (track->mFillingUpStatus == Track::FS_FILLED) {
4066 track->mFillingUpStatus = Track::FS_ACTIVE;
4067 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004068 if (track->mState == TrackBase::RESUMING) {
4069 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004070 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004071 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004072
Glenn Kasten952eeb22012-03-06 11:30:57 -08004073 // compute volume for this track
4074 float left, right;
4075 if (track->isMuted() || mMasterMute || track->isPausing() ||
4076 mStreamTypes[track->streamType()].mute) {
4077 left = right = 0;
4078 if (track->isPausing()) {
4079 track->setPaused();
4080 }
4081 } else {
4082 float typeVolume = mStreamTypes[track->streamType()].volume;
4083 float v = mMasterVolume * typeVolume;
4084 uint32_t vlr = cblk->getVolumeLR();
4085 float v_clamped = v * (vlr & 0xFFFF);
4086 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4087 left = v_clamped/MAX_GAIN;
4088 v_clamped = v * (vlr >> 16);
4089 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4090 right = v_clamped/MAX_GAIN;
4091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092
Glenn Kasten952eeb22012-03-06 11:30:57 -08004093 if (left != mLeftVolFloat || right != mRightVolFloat) {
4094 mLeftVolFloat = left;
4095 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096
Glenn Kasten952eeb22012-03-06 11:30:57 -08004097 // Convert volumes from float to 8.24
4098 uint32_t vl = (uint32_t)(left * (1 << 24));
4099 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100
Glenn Kasten952eeb22012-03-06 11:30:57 -08004101 // Delegate volume control to effect in track effect chain if needed
4102 // only one effect chain can be present on DirectOutputThread, so if
4103 // there is one, the track is connected to it
4104 if (!mEffectChains.isEmpty()) {
4105 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004106 mEffectChains[0]->setVolume_l(&vl, &vr);
4107 left = (float)vl / (1 << 24);
4108 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004109 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004110 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004111 }
4112
4113 // reset retry count
4114 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004115 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004116 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004117 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004118 // clear effect chain input buffer if an active track underruns to avoid sending
4119 // previous audio buffer again to effects
4120 if (!mEffectChains.isEmpty()) {
4121 mEffectChains[0]->clearInputBuffer();
4122 }
4123
Glenn Kasten952eeb22012-03-06 11:30:57 -08004124 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004125 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004126 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004127 // We have consumed all the buffers of this track.
4128 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004129 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004130 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004131 size_t framesWritten =
4132 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004133 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004134 if (track->isStopped()) {
4135 track->reset();
4136 }
Eric Laurenta011e352012-03-29 15:51:43 -07004137 trackToRemove = track;
4138 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004139 } else {
4140 // No buffers for this track. Give it a few chances to
4141 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004142 if (--(track->mRetryCount) <= 0) {
4143 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004144 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004146 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 }
4148 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004149 }
4150 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004152 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004153 // remove all the tracks that need to be...
4154 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004155 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004156 mActiveTracks.remove(trackToRemove);
4157 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004158 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004159 trackToRemove->sessionId());
4160 mEffectChains[0]->decActiveTrackCnt();
4161 }
4162 if (trackToRemove->isTerminated()) {
4163 removeTrack_l(trackToRemove);
4164 }
4165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166
Glenn Kastenfec279f2012-03-08 07:47:15 -08004167 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004168}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169
Glenn Kasten000f0e32012-03-01 17:10:56 -08004170void AudioFlinger::DirectOutputThread::threadLoop_mix()
4171{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004172 AudioBufferProvider::Buffer buffer;
4173 size_t frameCount = mFrameCount;
4174 int8_t *curBuf = (int8_t *)mMixBuffer;
4175 // output audio to hardware
4176 while (frameCount) {
4177 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004178 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004179 if (CC_UNLIKELY(buffer.raw == NULL)) {
4180 memset(curBuf, 0, frameCount * mFrameSize);
4181 break;
4182 }
4183 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4184 frameCount -= buffer.frameCount;
4185 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004186 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004187 }
4188 sleepTime = 0;
4189 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004190 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004191
Glenn Kasten000f0e32012-03-01 17:10:56 -08004192}
4193
4194void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4195{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004196 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004197 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004198 sleepTime = activeSleepTime;
4199 } else {
4200 sleepTime = idleSleepTime;
4201 }
4202 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004203 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004204 sleepTime = 0;
4205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206}
4207
4208// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004209int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4210 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211{
4212 return 0;
4213}
4214
4215// deleteTrackName_l() must be called with ThreadBase::mLock held
4216void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4217{
4218}
4219
4220// checkForNewParameters_l() must be called with ThreadBase::mLock held
4221bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4222{
4223 bool reconfig = false;
4224
4225 while (!mNewParameters.isEmpty()) {
4226 status_t status = NO_ERROR;
4227 String8 keyValuePair = mNewParameters[0];
4228 AudioParameter param = AudioParameter(keyValuePair);
4229 int value;
4230
4231 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4232 // do not accept frame count changes if tracks are open as the track buffer
4233 // size depends on frame count and correct behavior would not be garantied
4234 // if frame count is changed after track creation
4235 if (!mTracks.isEmpty()) {
4236 status = INVALID_OPERATION;
4237 } else {
4238 reconfig = true;
4239 }
4240 }
4241 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004242 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004243 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004245 mOutput->stream->common.standby(&mOutput->stream->common);
4246 mStandby = true;
4247 mBytesWritten = 0;
4248 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004249 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 }
4251 if (status == NO_ERROR && reconfig) {
4252 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004253 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 }
4255 }
4256
4257 mNewParameters.removeAt(0);
4258
4259 mParamStatus = status;
4260 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004261 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4262 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004263 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 }
4265 return reconfig;
4266}
4267
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004268uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269{
4270 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004271 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004272 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 } else {
4274 time = 10000;
4275 }
4276 return time;
4277}
4278
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004279uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280{
4281 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004282 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004283 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 } else {
4285 time = 10000;
4286 }
4287 return time;
4288}
4289
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004290uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004291{
4292 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004293 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004294 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4295 } else {
4296 time = 10000;
4297 }
4298 return time;
4299}
4300
Glenn Kasten66fcab92012-02-24 14:59:21 -08004301void AudioFlinger::DirectOutputThread::cacheParameters_l()
4302{
4303 PlaybackThread::cacheParameters_l();
4304
4305 // use shorter standby delay as on normal output to release
4306 // hardware resources as soon as possible
4307 standbyDelay = microseconds(activeSleepTime*2);
4308}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004309
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310// ----------------------------------------------------------------------------
4311
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004312AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004313 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004314 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004315 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 addOutputTrack(mainThread);
4318}
4319
4320AudioFlinger::DuplicatingThread::~DuplicatingThread()
4321{
4322 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4323 mOutputTracks[i]->destroy();
4324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325}
4326
Glenn Kasten000f0e32012-03-01 17:10:56 -08004327void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004329 // mix buffers...
4330 if (outputsReady(outputTracks)) {
4331 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4332 } else {
4333 memset(mMixBuffer, 0, mixBufferSize);
4334 }
4335 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004336 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004337 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004338}
4339
4340void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4341{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004342 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004343 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004344 sleepTime = activeSleepTime;
4345 } else {
4346 sleepTime = idleSleepTime;
4347 }
4348 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004349 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4350 writeFrames = mNormalFrameCount;
4351 memset(mMixBuffer, 0, mixBufferSize);
4352 } else {
4353 // flush remaining overflow buffers in output tracks
4354 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004355 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004356 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004357 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004358}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359
Glenn Kasten000f0e32012-03-01 17:10:56 -08004360void AudioFlinger::DuplicatingThread::threadLoop_write()
4361{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004362 for (size_t i = 0; i < outputTracks.size(); i++) {
4363 outputTracks[i]->write(mMixBuffer, writeFrames);
4364 }
4365 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004366}
Glenn Kasten688a6402012-02-29 07:57:06 -08004367
Glenn Kasten000f0e32012-03-01 17:10:56 -08004368void AudioFlinger::DuplicatingThread::threadLoop_standby()
4369{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004370 // DuplicatingThread implements standby by stopping all tracks
4371 for (size_t i = 0; i < outputTracks.size(); i++) {
4372 outputTracks[i]->stop();
4373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374}
4375
Glenn Kastenfa26a852012-03-06 11:28:04 -08004376void AudioFlinger::DuplicatingThread::saveOutputTracks()
4377{
4378 outputTracks = mOutputTracks;
4379}
4380
4381void AudioFlinger::DuplicatingThread::clearOutputTracks()
4382{
4383 outputTracks.clear();
4384}
4385
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4387{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004388 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004389 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004390 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004391 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 this,
4393 mSampleRate,
4394 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004395 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 frameCount);
4397 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004398 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004400 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004401 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 }
4403}
4404
4405void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4406{
4407 Mutex::Autolock _l(mLock);
4408 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004409 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 mOutputTracks[i]->destroy();
4411 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004412 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 return;
4414 }
4415 }
Steve Block3856b092011-10-20 11:56:00 +01004416 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417}
4418
Glenn Kasten438b0362012-03-06 11:24:48 -08004419// caller must hold mLock
4420void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421{
4422 mWaitTimeMs = UINT_MAX;
4423 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4424 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004425 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4427 if (waitTimeMs < mWaitTimeMs) {
4428 mWaitTimeMs = waitTimeMs;
4429 }
4430 }
4431 }
4432}
4433
4434
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004435bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436{
4437 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004438 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004440 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 return false;
4442 }
4443 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004444 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004446 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 return false;
4448 }
4449 }
4450 return true;
4451}
4452
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004453uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454{
4455 return (mWaitTimeMs * 1000) / 2;
4456}
4457
Glenn Kasten66fcab92012-02-24 14:59:21 -08004458void AudioFlinger::DuplicatingThread::cacheParameters_l()
4459{
4460 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4461 updateWaitTime_l();
4462
4463 MixerThread::cacheParameters_l();
4464}
4465
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466// ----------------------------------------------------------------------------
4467
4468// TrackBase constructor must be called with AudioFlinger::mLock held
4469AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004470 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 const sp<Client>& client,
4472 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004473 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004474 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 const sp<IMemory>& sharedBuffer,
4477 int sessionId)
4478 : RefBase(),
4479 mThread(thread),
4480 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004481 mCblk(NULL),
4482 // mBuffer
4483 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 mFrameCount(0),
4485 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004486 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004488 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004490 // mChannelCount
4491 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492{
Steve Block3856b092011-10-20 11:56:00 +01004493 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494
Steve Blockb8a80522011-12-20 16:23:08 +00004495 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004496 size_t size = sizeof(audio_track_cblk_t);
4497 uint8_t channelCount = popcount(channelMask);
4498 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4499 if (sharedBuffer == 0) {
4500 size += bufferSize;
4501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004503 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 mCblkMemory = client->heap()->allocate(size);
4505 if (mCblkMemory != 0) {
4506 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004507 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 new(mCblk) audio_track_cblk_t();
4509 // clear all buffers
4510 mCblk->frameCount = frameCount;
4511 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004512// uncomment the following lines to quickly test 32-bit wraparound
4513// mCblk->user = 0xffff0000;
4514// mCblk->server = 0xffff0000;
4515// mCblk->userBase = 0xffff0000;
4516// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004517 mChannelCount = channelCount;
4518 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 if (sharedBuffer == 0) {
4520 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4521 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4522 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004523 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 mCblk->flags = CBLK_UNDERRUN_ON;
4525 } else {
4526 mBuffer = sharedBuffer->pointer();
4527 }
4528 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4529 }
4530 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004531 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 client->heap()->dump("AudioTrack");
4533 return;
4534 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004535 } else {
4536 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004537 // construct the shared structure in-place.
4538 new(mCblk) audio_track_cblk_t();
4539 // clear all buffers
4540 mCblk->frameCount = frameCount;
4541 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004542// uncomment the following lines to quickly test 32-bit wraparound
4543// mCblk->user = 0xffff0000;
4544// mCblk->server = 0xffff0000;
4545// mCblk->userBase = 0xffff0000;
4546// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004547 mChannelCount = channelCount;
4548 mChannelMask = channelMask;
4549 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4550 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4551 // Force underrun condition to avoid false underrun callback until first data is
4552 // written to buffer (other flags are cleared)
4553 mCblk->flags = CBLK_UNDERRUN_ON;
4554 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556}
4557
4558AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4559{
Glenn Kastena0d68332012-01-27 16:47:15 -08004560 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004561 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004563 } else {
4564 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 }
4566 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004567 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004568 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004569 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004571 // If the client's reference count drops to zero, the associated destructor
4572 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4573 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 mClient.clear();
4575 }
4576}
4577
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004578// AudioBufferProvider interface
4579// getNextBuffer() = 0;
4580// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4582{
Glenn Kastene0feee32011-12-13 11:53:26 -08004583 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004585 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004586 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 buffer->frameCount = 0;
4588}
4589
4590bool AudioFlinger::ThreadBase::TrackBase::step() {
4591 bool result;
4592 audio_track_cblk_t* cblk = this->cblk();
4593
4594 result = cblk->stepServer(mFrameCount);
4595 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004596 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004597 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 return result;
4600}
4601
4602void AudioFlinger::ThreadBase::TrackBase::reset() {
4603 audio_track_cblk_t* cblk = this->cblk();
4604
4605 cblk->user = 0;
4606 cblk->server = 0;
4607 cblk->userBase = 0;
4608 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004609 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004610 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611}
4612
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4614 return (int)mCblk->sampleRate;
4615}
4616
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4618 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004619 size_t frameSize = cblk->frameSize;
4620 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4621 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622
4623 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004624 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4625 "TrackBase::getBuffer buffer out of range:\n"
4626 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4627 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004629 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630
4631 return bufferStart;
4632}
4633
Eric Laurenta011e352012-03-29 15:51:43 -07004634status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4635{
4636 mSyncEvents.add(event);
4637 return NO_ERROR;
4638}
4639
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640// ----------------------------------------------------------------------------
4641
4642// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4643AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004644 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004646 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004648 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004649 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 int frameCount,
4651 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004652 int sessionId,
4653 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004654 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004655 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004656 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004657 // mRetryCount initialized later when needed
4658 mSharedBuffer(sharedBuffer),
4659 mStreamType(streamType),
4660 mName(-1), // see note below
4661 mMainBuffer(thread->mixBuffer()),
4662 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004663 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004664 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004665 mFlags(flags),
4666 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004667 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004668 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669{
4670 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4672 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004673 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004674 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004675 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004676 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004677 if (mName < 0) {
4678 ALOGE("no more track names available");
4679 return;
4680 }
4681 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004682 if (flags & IAudioFlinger::TRACK_FAST) {
4683 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4684 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4685 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004686 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004687 // FIXME This is too eager. We allocate a fast track index before the
4688 // fast track becomes active. Since fast tracks are a scarce resource,
4689 // this means we are potentially denying other more important fast tracks from
4690 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004691 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004692 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004693 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004694 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004695 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004698 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699}
4700
4701AudioFlinger::PlaybackThread::Track::~Track()
4702{
Steve Block3856b092011-10-20 11:56:00 +01004703 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004704}
4705
4706void AudioFlinger::PlaybackThread::Track::destroy()
4707{
4708 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4709 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004710 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 // we must acquire a strong reference on this Track before locking mLock
4712 // here so that the destructor is called only when exiting this function.
4713 // On the other hand, as long as Track::destroy() is only called by
4714 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4715 // this Track with its member mTrack.
4716 sp<Track> keep(this);
4717 { // scope for mLock
4718 sp<ThreadBase> thread = mThread.promote();
4719 if (thread != 0) {
4720 if (!isOutputTrack()) {
4721 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004722 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004723
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004724#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004725 // to track the speaker usage
4726 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004727#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 }
4729 AudioSystem::releaseOutput(thread->id());
4730 }
4731 Mutex::Autolock _l(thread->mLock);
4732 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4733 playbackThread->destroyTrack_l(this);
4734 }
4735 }
4736}
4737
Glenn Kasten288ed212012-04-25 17:52:27 -07004738/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4739{
Glenn Kastene213c862012-04-25 13:46:15 -07004740 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004741 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004742}
4743
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4745{
Glenn Kasten83d86532012-01-17 14:39:34 -08004746 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004747 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004748 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004749 } else {
4750 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4751 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004752 track_state state = mState;
4753 char stateChar;
4754 switch (state) {
4755 case IDLE:
4756 stateChar = 'I';
4757 break;
4758 case TERMINATED:
4759 stateChar = 'T';
4760 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004761 case STOPPING_1:
4762 stateChar = 's';
4763 break;
4764 case STOPPING_2:
4765 stateChar = '5';
4766 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004767 case STOPPED:
4768 stateChar = 'S';
4769 break;
4770 case RESUMING:
4771 stateChar = 'R';
4772 break;
4773 case ACTIVE:
4774 stateChar = 'A';
4775 break;
4776 case PAUSING:
4777 stateChar = 'p';
4778 break;
4779 case PAUSED:
4780 stateChar = 'P';
4781 break;
Eric Laurent29864602012-05-08 18:57:51 -07004782 case FLUSHED:
4783 stateChar = 'F';
4784 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004785 default:
4786 stateChar = '?';
4787 break;
4788 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004789 char nowInUnderrun;
4790 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4791 case UNDERRUN_FULL:
4792 nowInUnderrun = ' ';
4793 break;
4794 case UNDERRUN_PARTIAL:
4795 nowInUnderrun = '<';
4796 break;
4797 case UNDERRUN_EMPTY:
4798 nowInUnderrun = '*';
4799 break;
4800 default:
4801 nowInUnderrun = '?';
4802 break;
4803 }
Glenn Kastene213c862012-04-25 13:46:15 -07004804 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4805 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004806 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 mStreamType,
4808 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004809 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004810 mSessionId,
4811 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004812 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004813 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 mMute,
4815 mFillingUpStatus,
4816 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004817 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4818 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 mCblk->server,
4820 mCblk->user,
4821 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004822 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004823 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004824 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004825 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004826}
4827
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004828// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004829status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004830 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004832 audio_track_cblk_t* cblk = this->cblk();
4833 uint32_t framesReady;
4834 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004836 // Check if last stepServer failed, try to step now
4837 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004838 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4839 // Since the fast mixer is higher priority than client callback thread,
4840 // it does not result in priority inversion for client.
4841 // But a non-blocking solution would be preferable to avoid
4842 // fast mixer being unable to tryLock(), and
4843 // to avoid the extra context switches if the client wakes up,
4844 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004845 if (!step()) goto getNextBuffer_exit;
4846 ALOGV("stepServer recovered");
4847 mStepServerFailed = false;
4848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849
Glenn Kasten288ed212012-04-25 17:52:27 -07004850 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004851 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004853 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 uint32_t s = cblk->server;
4855 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4856
4857 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4858 if (framesReq > framesReady) {
4859 framesReq = framesReady;
4860 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004861 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 framesReq = bufferEnd - s;
4863 }
4864
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004865 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004866 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869
4870getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004871 buffer->raw = NULL;
4872 buffer->frameCount = 0;
4873 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4874 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875}
4876
Glenn Kasten288ed212012-04-25 17:52:27 -07004877// Note that framesReady() takes a mutex on the control block using tryLock().
4878// This could result in priority inversion if framesReady() is called by the normal mixer,
4879// as the normal mixer thread runs at lower
4880// priority than the client's callback thread: there is a short window within framesReady()
4881// during which the normal mixer could be preempted, and the client callback would block.
4882// Another problem can occur if framesReady() is called by the fast mixer:
4883// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4884// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4885size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004886 return mCblk->framesReady();
4887}
4888
Glenn Kasten288ed212012-04-25 17:52:27 -07004889// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004891 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004892
John Grossman4ff14ba2012-02-08 16:37:41 -08004893 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4895 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004896 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 return true;
4898 }
4899 return false;
4900}
4901
Glenn Kasten3acbd052012-02-28 10:39:56 -08004902status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004903 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904{
4905 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004906 ALOGV("start(%d), calling pid %d session %d",
4907 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004908
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 sp<ThreadBase> thread = mThread.promote();
4910 if (thread != 0) {
4911 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004912 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 // here the track could be either new, or restarted
4914 // in both cases "unstop" the track
4915 if (mState == PAUSED) {
4916 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004917 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918 } else {
4919 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004920 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 }
4922
4923 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4924 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004925 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004927
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004928#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004929 // to track the speaker usage
4930 if (status == NO_ERROR) {
4931 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4932 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004933#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 }
4935 if (status == NO_ERROR) {
4936 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4937 playbackThread->addTrack_l(this);
4938 } else {
4939 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004940 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941 }
4942 } else {
4943 status = BAD_VALUE;
4944 }
4945 return status;
4946}
4947
4948void AudioFlinger::PlaybackThread::Track::stop()
4949{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004950 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 sp<ThreadBase> thread = mThread.promote();
4952 if (thread != 0) {
4953 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004954 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004955 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004956 // If the track is not active (PAUSED and buffers full), flush buffers
4957 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4958 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4959 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004960 mState = STOPPED;
4961 } else if (!isFastTrack()) {
4962 mState = STOPPED;
4963 } else {
4964 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4965 // and then to STOPPED and reset() when presentation is complete
4966 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004967 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004968 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 }
4970 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4971 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004972 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004974
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004975#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004976 // to track the speaker usage
4977 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004978#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 }
4980 }
4981}
4982
4983void AudioFlinger::PlaybackThread::Track::pause()
4984{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004985 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 sp<ThreadBase> thread = mThread.promote();
4987 if (thread != 0) {
4988 Mutex::Autolock _l(thread->mLock);
4989 if (mState == ACTIVE || mState == RESUMING) {
4990 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004991 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992 if (!isOutputTrack()) {
4993 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004994 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004996
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004997#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004998 // to track the speaker usage
4999 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005000#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 }
5002 }
5003 }
5004}
5005
5006void AudioFlinger::PlaybackThread::Track::flush()
5007{
Steve Block3856b092011-10-20 11:56:00 +01005008 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 sp<ThreadBase> thread = mThread.promote();
5010 if (thread != 0) {
5011 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005012 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005013 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 return;
5015 }
5016 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005017 // FLUSHED state
5018 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005019 // do not reset the track if it is still in the process of being stopped or paused.
5020 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005021 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005022 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005023 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5024 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5025 reset();
5026 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 }
5028}
5029
5030void AudioFlinger::PlaybackThread::Track::reset()
5031{
5032 // Do not reset twice to avoid discarding data written just after a flush and before
5033 // the audioflinger thread detects the track is stopped.
5034 if (!mResetDone) {
5035 TrackBase::reset();
5036 // Force underrun condition to avoid false underrun callback until first data is
5037 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005038 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5039 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 mFillingUpStatus = FS_FILLING;
5041 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005042 if (mState == FLUSHED) {
5043 mState = IDLE;
5044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 }
5046}
5047
5048void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5049{
5050 mMute = muted;
5051}
5052
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5054{
5055 status_t status = DEAD_OBJECT;
5056 sp<ThreadBase> thread = mThread.promote();
5057 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005058 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005059 sp<AudioFlinger> af = mClient->audioFlinger();
5060
5061 Mutex::Autolock _l(af->mLock);
5062
5063 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005064
Eric Laurent109347d2012-07-02 12:31:03 -07005065 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005066 Mutex::Autolock _dl(playbackThread->mLock);
5067 Mutex::Autolock _sl(srcThread->mLock);
5068 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5069 if (chain == 0) {
5070 return INVALID_OPERATION;
5071 }
5072
5073 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5074 if (effect == 0) {
5075 return INVALID_OPERATION;
5076 }
5077 srcThread->removeEffect_l(effect);
5078 playbackThread->addEffect_l(effect);
5079 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5080 if (effect->state() == EffectModule::ACTIVE ||
5081 effect->state() == EffectModule::STOPPING) {
5082 effect->start();
5083 }
5084
5085 sp<EffectChain> dstChain = effect->chain().promote();
5086 if (dstChain == 0) {
5087 srcThread->addEffect_l(effect);
5088 return INVALID_OPERATION;
5089 }
5090 AudioSystem::unregisterEffect(effect->id());
5091 AudioSystem::registerEffect(&effect->desc(),
5092 srcThread->id(),
5093 dstChain->strategy(),
5094 AUDIO_SESSION_OUTPUT_MIX,
5095 effect->id());
5096 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005097 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 }
5099 return status;
5100}
5101
5102void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5103{
5104 mAuxEffectId = EffectId;
5105 mAuxBuffer = buffer;
5106}
5107
Eric Laurenta011e352012-03-29 15:51:43 -07005108bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5109 size_t audioHalFrames)
5110{
5111 // a track is considered presented when the total number of frames written to audio HAL
5112 // corresponds to the number of frames written when presentationComplete() is called for the
5113 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5114 if (mPresentationCompleteFrames == 0) {
5115 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5116 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5117 mPresentationCompleteFrames, audioHalFrames);
5118 }
5119 if (framesWritten >= mPresentationCompleteFrames) {
5120 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5121 mSessionId, framesWritten);
5122 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005123 return true;
5124 }
5125 return false;
5126}
5127
5128void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5129{
5130 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5131 if (mSyncEvents[i]->type() == type) {
5132 mSyncEvents[i]->trigger();
5133 mSyncEvents.removeAt(i);
5134 i--;
5135 }
5136 }
5137}
5138
Glenn Kasten58912562012-04-03 10:45:00 -07005139// implement VolumeBufferProvider interface
5140
5141uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5142{
5143 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5144 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5145 uint32_t vlr = mCblk->getVolumeLR();
5146 uint32_t vl = vlr & 0xFFFF;
5147 uint32_t vr = vlr >> 16;
5148 // track volumes come from shared memory, so can't be trusted and must be clamped
5149 if (vl > MAX_GAIN_INT) {
5150 vl = MAX_GAIN_INT;
5151 }
5152 if (vr > MAX_GAIN_INT) {
5153 vr = MAX_GAIN_INT;
5154 }
5155 // now apply the cached master volume and stream type volume;
5156 // this is trusted but lacks any synchronization or barrier so may be stale
5157 float v = mCachedVolume;
5158 vl *= v;
5159 vr *= v;
5160 // re-combine into U4.16
5161 vlr = (vr << 16) | (vl & 0xFFFF);
5162 // FIXME look at mute, pause, and stop flags
5163 return vlr;
5164}
Eric Laurenta011e352012-03-29 15:51:43 -07005165
Eric Laurent29864602012-05-08 18:57:51 -07005166status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5167{
5168 if (mState == TERMINATED || mState == PAUSED ||
5169 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5170 (mState == STOPPED)))) {
5171 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5172 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5173 event->cancel();
5174 return INVALID_OPERATION;
5175 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005176 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005177 return NO_ERROR;
5178}
5179
John Grossman4ff14ba2012-02-08 16:37:41 -08005180// timed audio tracks
5181
5182sp<AudioFlinger::PlaybackThread::TimedTrack>
5183AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005184 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 const sp<Client>& client,
5186 audio_stream_type_t streamType,
5187 uint32_t sampleRate,
5188 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005189 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005190 int frameCount,
5191 const sp<IMemory>& sharedBuffer,
5192 int sessionId) {
5193 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005194 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005195
Glenn Kastena0356762012-03-19 10:38:51 -07005196 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005197 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5198 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005199}
5200
5201AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005202 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 const sp<Client>& client,
5204 audio_stream_type_t streamType,
5205 uint32_t sampleRate,
5206 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005207 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005208 int frameCount,
5209 const sp<IMemory>& sharedBuffer,
5210 int sessionId)
5211 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005212 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005213 mQueueHeadInFlight(false),
5214 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005215 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 mTimedSilenceBuffer(NULL),
5217 mTimedSilenceBufferSize(0),
5218 mTimedAudioOutputOnTime(false),
5219 mMediaTimeTransformValid(false)
5220{
5221 LocalClock lc;
5222 mLocalTimeFreq = lc.getLocalFreq();
5223
5224 mLocalTimeToSampleTransform.a_zero = 0;
5225 mLocalTimeToSampleTransform.b_zero = 0;
5226 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5227 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5228 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5229 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005230
5231 mMediaTimeToSampleTransform.a_zero = 0;
5232 mMediaTimeToSampleTransform.b_zero = 0;
5233 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5234 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5235 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5236 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005237}
5238
5239AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5240 mClient->releaseTimedTrack();
5241 delete [] mTimedSilenceBuffer;
5242}
5243
5244status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5245 size_t size, sp<IMemory>* buffer) {
5246
5247 Mutex::Autolock _l(mTimedBufferQueueLock);
5248
5249 trimTimedBufferQueue_l();
5250
5251 // lazily initialize the shared memory heap for timed buffers
5252 if (mTimedMemoryDealer == NULL) {
5253 const int kTimedBufferHeapSize = 512 << 10;
5254
5255 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5256 "AudioFlingerTimed");
5257 if (mTimedMemoryDealer == NULL)
5258 return NO_MEMORY;
5259 }
5260
5261 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5262 if (newBuffer == NULL) {
5263 newBuffer = mTimedMemoryDealer->allocate(size);
5264 if (newBuffer == NULL)
5265 return NO_MEMORY;
5266 }
5267
5268 *buffer = newBuffer;
5269 return NO_ERROR;
5270}
5271
5272// caller must hold mTimedBufferQueueLock
5273void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5274 int64_t mediaTimeNow;
5275 {
5276 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5277 if (!mMediaTimeTransformValid)
5278 return;
5279
5280 int64_t targetTimeNow;
5281 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5282 ? mCCHelper.getCommonTime(&targetTimeNow)
5283 : mCCHelper.getLocalTime(&targetTimeNow);
5284
5285 if (OK != res)
5286 return;
5287
5288 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5289 &mediaTimeNow)) {
5290 return;
5291 }
5292 }
5293
John Grossman1c345192012-03-27 14:00:17 -07005294 size_t trimEnd;
5295 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005296 int64_t bufEnd;
5297
John Grossmanc95cfbb2012-04-12 11:53:11 -07005298 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5299 // We have a next buffer. Just use its PTS as the PTS of the frame
5300 // following the last frame in this buffer. If the stream is sparse
5301 // (ie, there are deliberate gaps left in the stream which should be
5302 // filled with silence by the TimedAudioTrack), then this can result
5303 // in one extra buffer being left un-trimmed when it could have
5304 // been. In general, this is not typical, and we would rather
5305 // optimized away the TS calculation below for the more common case
5306 // where PTSes are contiguous.
5307 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5308 } else {
5309 // We have no next buffer. Compute the PTS of the frame following
5310 // the last frame in this buffer by computing the duration of of
5311 // this frame in media time units and adding it to the PTS of the
5312 // buffer.
5313 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5314 / mCblk->frameSize;
5315
5316 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5317 &bufEnd)) {
5318 ALOGE("Failed to convert frame count of %lld to media time"
5319 " duration" " (scale factor %d/%u) in %s",
5320 frameCount,
5321 mMediaTimeToSampleTransform.a_to_b_numer,
5322 mMediaTimeToSampleTransform.a_to_b_denom,
5323 __PRETTY_FUNCTION__);
5324 break;
5325 }
5326 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005327 }
John Grossman9fbdee12012-03-26 17:51:46 -07005328
5329 if (bufEnd > mediaTimeNow)
5330 break;
5331
5332 // Is the buffer we want to use in the middle of a mix operation right
5333 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5334 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005335 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005336 mTrimQueueHeadOnRelease = true;
5337 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005338 }
5339
John Grossman9fbdee12012-03-26 17:51:46 -07005340 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005341 if (trimStart < trimEnd) {
5342 // Update the bookkeeping for framesReady()
5343 for (size_t i = trimStart; i < trimEnd; ++i) {
5344 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5345 }
5346
5347 // Now actually remove the buffers from the queue.
5348 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005349 }
5350}
5351
John Grossman1c345192012-03-27 14:00:17 -07005352void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5353 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005354 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5355 "%s called (reason \"%s\"), but timed buffer queue has no"
5356 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005357
5358 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5359 mTimedBufferQueue.removeAt(0);
5360}
5361
5362void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5363 const TimedBuffer& buf,
5364 const char* logTag) {
5365 uint32_t bufBytes = buf.buffer()->size();
5366 uint32_t consumedAlready = buf.position();
5367
Eric Laurentb388e532012-04-14 13:32:48 -07005368 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005369 "Bad bookkeeping while updating frames pending. Timed buffer is"
5370 " only %u bytes long, but claims to have consumed %u"
5371 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005372 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005373
5374 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005375 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5376 "Bad bookkeeping while updating frames pending. Should have at"
5377 " least %u queued frames, but we think we have only %u. (update"
5378 " reason: \"%s\")",
5379 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005380
5381 mFramesPendingInQueue -= bufFrames;
5382}
5383
John Grossman4ff14ba2012-02-08 16:37:41 -08005384status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5385 const sp<IMemory>& buffer, int64_t pts) {
5386
5387 {
5388 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5389 if (!mMediaTimeTransformValid)
5390 return INVALID_OPERATION;
5391 }
5392
5393 Mutex::Autolock _l(mTimedBufferQueueLock);
5394
John Grossman1c345192012-03-27 14:00:17 -07005395 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5396 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005397 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5398
5399 return NO_ERROR;
5400}
5401
5402status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5403 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5404
John Grossman1c345192012-03-27 14:00:17 -07005405 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5406 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5407 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005408
5409 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5410 target == TimedAudioTrack::COMMON_TIME)) {
5411 return BAD_VALUE;
5412 }
5413
5414 Mutex::Autolock lock(mMediaTimeTransformLock);
5415 mMediaTimeTransform = xform;
5416 mMediaTimeTransformTarget = target;
5417 mMediaTimeTransformValid = true;
5418
5419 return NO_ERROR;
5420}
5421
5422#define min(a, b) ((a) < (b) ? (a) : (b))
5423
5424// implementation of getNextBuffer for tracks whose buffers have timestamps
5425status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5426 AudioBufferProvider::Buffer* buffer, int64_t pts)
5427{
5428 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005429 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005430 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005431 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005432 return INVALID_OPERATION;
5433 }
5434
John Grossman4ff14ba2012-02-08 16:37:41 -08005435 Mutex::Autolock _l(mTimedBufferQueueLock);
5436
John Grossman9fbdee12012-03-26 17:51:46 -07005437 ALOG_ASSERT(!mQueueHeadInFlight,
5438 "getNextBuffer called without releaseBuffer!");
5439
John Grossman4ff14ba2012-02-08 16:37:41 -08005440 while (true) {
5441
5442 // if we have no timed buffers, then fail
5443 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005444 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005445 buffer->frameCount = 0;
5446 return NOT_ENOUGH_DATA;
5447 }
5448
5449 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5450
5451 // calculate the PTS of the head of the timed buffer queue expressed in
5452 // local time
5453 int64_t headLocalPTS;
5454 {
5455 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5456
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005457 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005458
5459 if (mMediaTimeTransform.a_to_b_denom == 0) {
5460 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005461 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005462 return NO_ERROR;
5463 }
5464
5465 int64_t transformedPTS;
5466 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5467 &transformedPTS)) {
5468 // the transform failed. this shouldn't happen, but if it does
5469 // then just drop this buffer
5470 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005471 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005472 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005473 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005474 return NO_ERROR;
5475 }
5476
5477 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5478 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5479 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005480 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005481 buffer->frameCount = 0;
5482 return INVALID_OPERATION;
5483 }
5484 } else {
5485 headLocalPTS = transformedPTS;
5486 }
5487 }
5488
5489 // adjust the head buffer's PTS to reflect the portion of the head buffer
5490 // that has already been consumed
5491 int64_t effectivePTS = headLocalPTS +
5492 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5493
5494 // Calculate the delta in samples between the head of the input buffer
5495 // queue and the start of the next output buffer that will be written.
5496 // If the transformation fails because of over or underflow, it means
5497 // that the sample's position in the output stream is so far out of
5498 // whack that it should just be dropped.
5499 int64_t sampleDelta;
5500 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5501 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005502 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5503 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005504 continue;
5505 }
5506 if (!mLocalTimeToSampleTransform.doForwardTransform(
5507 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005508 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005509 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005510 continue;
5511 }
5512
John Grossman1c345192012-03-27 14:00:17 -07005513 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5514 " sampleDelta=[%d.%08x]",
5515 head.pts(), head.position(), pts,
5516 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5517 + (sampleDelta >> 32)),
5518 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005519
5520 // if the delta between the ideal placement for the next input sample and
5521 // the current output position is within this threshold, then we will
5522 // concatenate the next input samples to the previous output
5523 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005524 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005525
5526 // if this is the first buffer of audio that we're emitting from this track
5527 // then it should be almost exactly on time.
5528 const int64_t kSampleStartupThreshold = 1LL << 32;
5529
5530 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005531 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005532 // the next input is close enough to being on time, so concatenate it
5533 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005534 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005535
John Grossman1c345192012-03-27 14:00:17 -07005536 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5537 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005538 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005539 }
5540
5541 // Looks like our output is not on time. Reset our on timed status.
5542 // Next time we mix samples from our input queue, then should be within
5543 // the StartupThreshold.
5544 mTimedAudioOutputOnTime = false;
5545 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005546 // the gap between the current output position and the proper start of
5547 // the next input sample is too big, so fill it with silence
5548 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5549
John Grossman9fbdee12012-03-26 17:51:46 -07005550 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005551 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5552 return NO_ERROR;
5553 } else {
5554 // the next input sample is late
5555 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5556 size_t onTimeSamplePosition =
5557 head.position() + lateFrames * mCblk->frameSize;
5558
5559 if (onTimeSamplePosition > head.buffer()->size()) {
5560 // all the remaining samples in the head are too late, so
5561 // drop it and move on
5562 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005563 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005564 continue;
5565 } else {
5566 // skip over the late samples
5567 head.setPosition(onTimeSamplePosition);
5568
5569 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005570 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005571
5572 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5573 return NO_ERROR;
5574 }
5575 }
5576 }
5577}
5578
5579// Yield samples from the timed buffer queue head up to the given output
5580// buffer's capacity.
5581//
5582// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005583void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005584 AudioBufferProvider::Buffer* buffer) {
5585
5586 const TimedBuffer& head = mTimedBufferQueue[0];
5587
5588 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5589 head.position());
5590
5591 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5592 mCblk->frameSize);
5593 size_t framesRequested = buffer->frameCount;
5594 buffer->frameCount = min(framesLeftInHead, framesRequested);
5595
John Grossman9fbdee12012-03-26 17:51:46 -07005596 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005597 mTimedAudioOutputOnTime = true;
5598}
5599
5600// Yield samples of silence up to the given output buffer's capacity
5601//
5602// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005603void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005604 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5605
5606 // lazily allocate a buffer filled with silence
5607 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5608 delete [] mTimedSilenceBuffer;
5609 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5610 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5611 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5612 }
5613
5614 buffer->raw = mTimedSilenceBuffer;
5615 size_t framesRequested = buffer->frameCount;
5616 buffer->frameCount = min(numFrames, framesRequested);
5617
5618 mTimedAudioOutputOnTime = false;
5619}
5620
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005621// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005622void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5623 AudioBufferProvider::Buffer* buffer) {
5624
5625 Mutex::Autolock _l(mTimedBufferQueueLock);
5626
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005627 // If the buffer which was just released is part of the buffer at the head
5628 // of the queue, be sure to update the amt of the buffer which has been
5629 // consumed. If the buffer being returned is not part of the head of the
5630 // queue, its either because the buffer is part of the silence buffer, or
5631 // because the head of the timed queue was trimmed after the mixer called
5632 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005633 if (buffer->raw == mTimedSilenceBuffer) {
5634 ALOG_ASSERT(!mQueueHeadInFlight,
5635 "Queue head in flight during release of silence buffer!");
5636 goto done;
5637 }
5638
5639 ALOG_ASSERT(mQueueHeadInFlight,
5640 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5641 " head in flight.");
5642
5643 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005644 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005645
5646 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005647 void* end = reinterpret_cast<void*>(
5648 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5649 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005650
John Grossman9fbdee12012-03-26 17:51:46 -07005651 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5652 "released buffer not within the head of the timed buffer"
5653 " queue; qHead = [%p, %p], released buffer = %p",
5654 start, end, buffer->raw);
5655
5656 head.setPosition(head.position() +
5657 (buffer->frameCount * mCblk->frameSize));
5658 mQueueHeadInFlight = false;
5659
John Grossman1c345192012-03-27 14:00:17 -07005660 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5661 "Bad bookkeeping during releaseBuffer! Should have at"
5662 " least %u queued frames, but we think we have only %u",
5663 buffer->frameCount, mFramesPendingInQueue);
5664
5665 mFramesPendingInQueue -= buffer->frameCount;
5666
John Grossman9fbdee12012-03-26 17:51:46 -07005667 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5668 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005669 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005670 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005671 }
John Grossman9fbdee12012-03-26 17:51:46 -07005672 } else {
5673 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5674 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005675 }
5676
John Grossman9fbdee12012-03-26 17:51:46 -07005677done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005678 buffer->raw = 0;
5679 buffer->frameCount = 0;
5680}
5681
Glenn Kasten288ed212012-04-25 17:52:27 -07005682size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005683 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005684 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005685}
5686
5687AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5688 : mPTS(0), mPosition(0) {}
5689
5690AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5691 const sp<IMemory>& buffer, int64_t pts)
5692 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5693
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694// ----------------------------------------------------------------------------
5695
5696// RecordTrack constructor must be called with AudioFlinger::mLock held
5697AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005698 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699 const sp<Client>& client,
5700 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005701 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005702 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 int sessionId)
5705 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005706 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 mOverflow(false)
5708{
5709 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005710 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5711 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5712 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5713 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5714 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5715 } else {
5716 mCblk->frameSize = sizeof(int8_t);
5717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 }
5719}
5720
5721AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5722{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005723 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724}
5725
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005726// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005727status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728{
5729 audio_track_cblk_t* cblk = this->cblk();
5730 uint32_t framesAvail;
5731 uint32_t framesReq = buffer->frameCount;
5732
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005733 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005734 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005736 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005737 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 }
5739
5740 framesAvail = cblk->framesAvailable_l();
5741
Glenn Kastenf6b16782011-12-15 09:51:17 -08005742 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 uint32_t s = cblk->server;
5744 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5745
5746 if (framesReq > framesAvail) {
5747 framesReq = framesAvail;
5748 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005749 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 framesReq = bufferEnd - s;
5751 }
5752
5753 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 buffer->frameCount = framesReq;
5755 return NO_ERROR;
5756 }
5757
5758getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005759 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 buffer->frameCount = 0;
5761 return NOT_ENOUGH_DATA;
5762}
5763
Glenn Kasten3acbd052012-02-28 10:39:56 -08005764status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005765 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766{
5767 sp<ThreadBase> thread = mThread.promote();
5768 if (thread != 0) {
5769 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005770 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 } else {
5772 return BAD_VALUE;
5773 }
5774}
5775
5776void AudioFlinger::RecordThread::RecordTrack::stop()
5777{
5778 sp<ThreadBase> thread = mThread.promote();
5779 if (thread != 0) {
5780 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005781 recordThread->mLock.lock();
5782 bool doStop = recordThread->stop_l(this);
5783 if (doStop) {
5784 TrackBase::reset();
5785 // Force overrun condition to avoid false overrun callback until first data is
5786 // read from buffer
5787 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5788 }
5789 recordThread->mLock.unlock();
5790 if (doStop) {
5791 AudioSystem::stopInput(recordThread->id());
5792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 }
5794}
5795
Glenn Kasten510a3d62012-07-16 14:24:34 -07005796/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5797{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005798 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005799}
5800
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5802{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005803 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005804 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005806 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 mSessionId,
5808 mFrameCount,
5809 mState,
5810 mCblk->sampleRate,
5811 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005812 mCblk->user,
5813 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814}
5815
5816
5817// ----------------------------------------------------------------------------
5818
5819AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005820 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 DuplicatingThread *sourceThread,
5822 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005823 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005824 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005826 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5827 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 mActive(false), mSourceThread(sourceThread)
5829{
5830
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 if (mCblk != NULL) {
5832 mCblk->flags |= CBLK_DIRECTION_OUT;
5833 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 mOutBuffer.frameCount = 0;
5835 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005836 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005837 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5838 mCblk, mBuffer, mCblk->buffers,
5839 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005841 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 }
5843}
5844
5845AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5846{
5847 clearBufferQueue();
5848}
5849
Glenn Kasten3acbd052012-02-28 10:39:56 -08005850status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005851 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005853 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854 if (status != NO_ERROR) {
5855 return status;
5856 }
5857
5858 mActive = true;
5859 mRetryCount = 127;
5860 return status;
5861}
5862
5863void AudioFlinger::PlaybackThread::OutputTrack::stop()
5864{
5865 Track::stop();
5866 clearBufferQueue();
5867 mOutBuffer.frameCount = 0;
5868 mActive = false;
5869}
5870
5871bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5872{
5873 Buffer *pInBuffer;
5874 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005875 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 bool outputBufferFull = false;
5877 inBuffer.frameCount = frames;
5878 inBuffer.i16 = data;
5879
5880 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5881
5882 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005883 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 sp<ThreadBase> thread = mThread.promote();
5885 if (thread != 0) {
5886 MixerThread *mixerThread = (MixerThread *)thread.get();
5887 if (mCblk->frameCount > frames){
5888 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5889 uint32_t startFrames = (mCblk->frameCount - frames);
5890 pInBuffer = new Buffer;
5891 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5892 pInBuffer->frameCount = startFrames;
5893 pInBuffer->i16 = pInBuffer->mBuffer;
5894 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5895 mBufferQueue.add(pInBuffer);
5896 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005897 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 }
5899 }
5900 }
5901 }
5902
5903 while (waitTimeLeftMs) {
5904 // First write pending buffers, then new data
5905 if (mBufferQueue.size()) {
5906 pInBuffer = mBufferQueue.itemAt(0);
5907 } else {
5908 pInBuffer = &inBuffer;
5909 }
5910
5911 if (pInBuffer->frameCount == 0) {
5912 break;
5913 }
5914
5915 if (mOutBuffer.frameCount == 0) {
5916 mOutBuffer.frameCount = pInBuffer->frameCount;
5917 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005918 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 outputBufferFull = true;
5921 break;
5922 }
5923 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5924 if (waitTimeLeftMs >= waitTimeMs) {
5925 waitTimeLeftMs -= waitTimeMs;
5926 } else {
5927 waitTimeLeftMs = 0;
5928 }
5929 }
5930
5931 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5932 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5933 mCblk->stepUser(outFrames);
5934 pInBuffer->frameCount -= outFrames;
5935 pInBuffer->i16 += outFrames * channelCount;
5936 mOutBuffer.frameCount -= outFrames;
5937 mOutBuffer.i16 += outFrames * channelCount;
5938
5939 if (pInBuffer->frameCount == 0) {
5940 if (mBufferQueue.size()) {
5941 mBufferQueue.removeAt(0);
5942 delete [] pInBuffer->mBuffer;
5943 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005944 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 } else {
5946 break;
5947 }
5948 }
5949 }
5950
5951 // If we could not write all frames, allocate a buffer and queue it for next time.
5952 if (inBuffer.frameCount) {
5953 sp<ThreadBase> thread = mThread.promote();
5954 if (thread != 0 && !thread->standby()) {
5955 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5956 pInBuffer = new Buffer;
5957 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5958 pInBuffer->frameCount = inBuffer.frameCount;
5959 pInBuffer->i16 = pInBuffer->mBuffer;
5960 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5961 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005962 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005964 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 }
5966 }
5967 }
5968
5969 // Calling write() with a 0 length buffer, means that no more data will be written:
5970 // If no more buffers are pending, fill output track buffer to make sure it is started
5971 // by output mixer.
5972 if (frames == 0 && mBufferQueue.size() == 0) {
5973 if (mCblk->user < mCblk->frameCount) {
5974 frames = mCblk->frameCount - mCblk->user;
5975 pInBuffer = new Buffer;
5976 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5977 pInBuffer->frameCount = frames;
5978 pInBuffer->i16 = pInBuffer->mBuffer;
5979 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5980 mBufferQueue.add(pInBuffer);
5981 } else if (mActive) {
5982 stop();
5983 }
5984 }
5985
5986 return outputBufferFull;
5987}
5988
5989status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5990{
5991 int active;
5992 status_t result;
5993 audio_track_cblk_t* cblk = mCblk;
5994 uint32_t framesReq = buffer->frameCount;
5995
Steve Block3856b092011-10-20 11:56:00 +01005996// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 buffer->frameCount = 0;
5998
5999 uint32_t framesAvail = cblk->framesAvailable();
6000
6001
6002 if (framesAvail == 0) {
6003 Mutex::Autolock _l(cblk->lock);
6004 goto start_loop_here;
6005 while (framesAvail == 0) {
6006 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006007 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006008 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006009 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 }
6011 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6012 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006013 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 }
6015 // read the server count again
6016 start_loop_here:
6017 framesAvail = cblk->framesAvailable_l();
6018 }
6019 }
6020
6021// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006022// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023// }
6024
6025 if (framesReq > framesAvail) {
6026 framesReq = framesAvail;
6027 }
6028
6029 uint32_t u = cblk->user;
6030 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6031
Marco Nelissena1472d92012-03-30 14:36:54 -07006032 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 framesReq = bufferEnd - u;
6034 }
6035
6036 buffer->frameCount = framesReq;
6037 buffer->raw = (void *)cblk->buffer(u);
6038 return NO_ERROR;
6039}
6040
6041
6042void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6043{
6044 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045
6046 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006047 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 delete [] pBuffer->mBuffer;
6049 delete pBuffer;
6050 }
6051 mBufferQueue.clear();
6052}
6053
6054// ----------------------------------------------------------------------------
6055
6056AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6057 : RefBase(),
6058 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006059 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006061 mPid(pid),
6062 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063{
6064 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6065}
6066
6067// Client destructor must be called with AudioFlinger::mLock held
6068AudioFlinger::Client::~Client()
6069{
6070 mAudioFlinger->removeClient_l(mPid);
6071}
6072
Glenn Kasten435dbe62012-01-30 10:15:48 -08006073sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074{
6075 return mMemoryDealer;
6076}
6077
John Grossman4ff14ba2012-02-08 16:37:41 -08006078// Reserve one of the limited slots for a timed audio track associated
6079// with this client
6080bool AudioFlinger::Client::reserveTimedTrack()
6081{
6082 const int kMaxTimedTracksPerClient = 4;
6083
6084 Mutex::Autolock _l(mTimedTrackLock);
6085
6086 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6087 ALOGW("can not create timed track - pid %d has exceeded the limit",
6088 mPid);
6089 return false;
6090 }
6091
6092 mTimedTrackCount++;
6093 return true;
6094}
6095
6096// Release a slot for a timed audio track
6097void AudioFlinger::Client::releaseTimedTrack()
6098{
6099 Mutex::Autolock _l(mTimedTrackLock);
6100 mTimedTrackCount--;
6101}
6102
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103// ----------------------------------------------------------------------------
6104
6105AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6106 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006107 sp<IBinder> binder)
6108 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109{
6110}
6111
6112AudioFlinger::NotificationClient::~NotificationClient()
6113{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114}
6115
6116void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6117{
6118 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006119 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120}
6121
6122// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006123#ifdef QCOM_HARDWARE
6124AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6125 int output, AudioSessionDescriptor *outputDesc,
6126 IDirectTrackClient* client, audio_output_flags_t outflag)
6127 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6128 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6129{
6130 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6131 createEffectThread();
6132
6133 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6134 mAudioFlinger->registerClient(mAudioFlingerClient);
6135
6136 allocateBufPool();
6137 }
6138 mDeathRecipient = new PMDeathRecipient(this);
6139 acquireWakeLock();
6140}
6141
6142AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6143 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6144 requestAndWaitForEffectsThreadExit();
6145 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6146 mAudioFlinger->deleteEffectSession();
6147 deallocateBufPool();
6148 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006149 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006150 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006151
vivek mehta2192bc92012-12-04 11:46:08 -08006152 if (mPowerManager != 0) {
6153 sp<IBinder> binder = mPowerManager->asBinder();
6154 binder->unlinkToDeath(mDeathRecipient);
6155 }
vivek mehta2192bc92012-12-04 11:46:08 -08006156}
6157
6158status_t AudioFlinger::DirectAudioTrack::start() {
6159 if(mIsPaused) {
6160 mIsPaused = false;
6161 mOutputDesc->stream->start(mOutputDesc->stream);
6162 }
6163 mOutputDesc->mActive = true;
6164 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6165 return NO_ERROR;
6166}
6167
6168void AudioFlinger::DirectAudioTrack::stop() {
6169 mOutputDesc->mActive = false;
6170 mOutputDesc->stream->stop(mOutputDesc->stream);
6171 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6172}
6173
6174void AudioFlinger::DirectAudioTrack::pause() {
6175 if(!mIsPaused) {
6176 mIsPaused = true;
6177 mOutputDesc->stream->pause(mOutputDesc->stream);
6178 mOutputDesc->mActive = false;
6179 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6180 }
6181}
6182
6183ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6184 ALOGV("Writing to AudioSessionOut");
6185 int isAvail = 0;
6186 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6187 if (!isAvail) {
6188 return 0;
6189 }
6190
6191 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6192 mEffectLock.lock();
6193 List<BufferInfo>::iterator it = mEffectsPool.begin();
6194 BufferInfo buf = *it;
6195 mEffectsPool.erase(it);
6196 memcpy((char *) buf.localBuf, (char *)buffer, size);
6197 buf.bytesToWrite = size;
6198 mEffectsPool.push_back(buf);
6199 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6200 mEffectLock.unlock();
6201 }
6202 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6203}
6204
6205void AudioFlinger::DirectAudioTrack::flush() {
6206 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6207 mEffectsPool.clear();
6208 mEffectsPool = mBufPool;
6209 }
6210 mOutputDesc->stream->flush(mOutputDesc->stream);
6211}
6212
6213void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6214}
6215
6216void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
6217 mOutputDesc->mVolumeLeft = 1.0;
6218 mOutputDesc->mVolumeRight = 1.0;
6219}
6220
6221int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6222 int64_t time;
6223 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6224 ALOGV("Timestamp %lld",time);
6225 return time;
6226}
6227
6228void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
6229 ALOGV("Notify Audio Track of EOS event");
6230 mClient->notify(DIRECT_TRACK_EOS);
6231}
6232
6233void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6234 void *dsp_buf = NULL;
6235 void *local_buf = NULL;
6236
6237 //1. get the ion buffer information
6238 struct buf_info* buf = NULL;
6239 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6240 ALOGV("get buffer info %p",buf);
6241 if (!buf) {
6242 ALOGV("buffer is NULL");
6243 return;
6244 }
6245 int nSize = buf->bufsize;
6246 int bufferCount = buf->nBufs;
6247
6248 //2. allocate the buffer pool, allocate local buffers
6249 for (int i = 0; i < bufferCount; i++) {
6250 dsp_buf = (void *)buf->buffers[i];
6251 local_buf = malloc(nSize);
6252 memset(local_buf, 0, nSize);
6253 // Store this information for internal mapping / maintanence
6254 BufferInfo buf(local_buf, dsp_buf, nSize);
6255 buf.bytesToWrite = 0;
6256 mBufPool.push_back(buf);
6257 mEffectsPool.push_back(buf);
6258
6259 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6260 }
6261 free(buf);
6262}
6263
6264void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6265
6266 //1. Deallocate the local memory
6267 //2. Remove all the buffers from bufpool
6268 while (!mBufPool.empty()) {
6269 List<BufferInfo>::iterator it = mBufPool.begin();
6270 BufferInfo &memBuffer = *it;
6271 // free the local buffer corresponding to mem buffer
6272 if (memBuffer.localBuf) {
6273 free(memBuffer.localBuf);
6274 memBuffer.localBuf = NULL;
6275 }
6276 ALOGV("Removing from bufpool");
6277 mBufPool.erase(it);
6278 }
6279}
6280
6281status_t AudioFlinger::DirectAudioTrack::onTransact(
6282 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6283{
6284 return BnDirectTrack::onTransact(code, data, reply, flags);
6285}
6286
6287void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6288 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6289 return NULL;
6290}
6291
6292void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6293 while(1) {
6294 mEffectLock.lock();
6295 if (!mEffectConfigChanged && !mKillEffectsThread) {
6296 mEffectCv.wait(mEffectLock);
6297 }
6298
6299 if(mKillEffectsThread) {
6300 mEffectLock.unlock();
6301 break;
6302 }
6303
6304 if (mEffectConfigChanged) {
6305 mEffectConfigChanged = false;
6306 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6307 it != mEffectsPool.end(); it++) {
6308 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6309 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6310 (int16_t *)it->localBuf,
6311 (int16_t *)it->dspBuf,
6312 it->bytesToWrite);
6313 if (mEffectConfigChanged) {
6314 break;
6315 }
6316 }
6317
6318 }
6319 mEffectLock.unlock();
6320 }
6321 ALOGV("Effects thread is dead");
6322 mEffectsThreadAlive = false;
6323}
6324
6325void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6326 if (!mEffectsThreadAlive)
6327 return;
6328 mKillEffectsThread = true;
6329 mEffectCv.signal();
6330 pthread_join(mEffectsThread,NULL);
6331 ALOGV("effects thread killed");
6332}
6333
6334void AudioFlinger::DirectAudioTrack::createEffectThread() {
6335 //Create the effects thread
6336 pthread_attr_t attr;
6337 pthread_attr_init(&attr);
6338 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6339 mEffectsThreadAlive = true;
6340 ALOGV("Creating Effects Thread");
6341 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6342}
6343AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6344{
6345 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6346 pBaseClass = (DirectAudioTrack*)obj;
6347}
6348
6349void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6350 pBaseClass->mAudioFlinger.clear();
6351 ALOGW("AudioFlinger server died!");
6352}
6353
6354void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6355 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6356 ALOGV("ioConfigChanged() event %d", event);
6357 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6358 ALOGV("Received notification for change in effect module");
6359 // Seek to current media time - flush the decoded buffers with the driver
6360 pBaseClass->mEffectConfigChanged = true;
6361 // Signal effects thread to re-apply effects
6362 ALOGV("Signalling Effects Thread");
6363 pBaseClass->mEffectCv.signal();
6364
6365 }
6366 ALOGV("ioConfigChanged Out");
6367}
6368
6369void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6370{
6371 Mutex::Autolock _l(pmLock);
6372
6373 if (mPowerManager == 0) {
6374 // use checkService() to avoid blocking if power service is not up yet
6375 sp<IBinder> binder =
6376 defaultServiceManager()->checkService(String16("power"));
6377 if (binder == 0) {
6378 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6379 } else {
6380 mPowerManager = interface_cast<IPowerManager>(binder);
6381 binder->linkToDeath(mDeathRecipient);
6382 }
6383 }
6384 if (mPowerManager != 0 && mWakeLockToken == 0) {
6385 sp<IBinder> binder = new BBinder();
6386 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6387 binder,
6388 String16(lockName));
6389 if (status == NO_ERROR) {
6390 mWakeLockToken = binder;
6391 }
6392 ALOGV("acquireWakeLock() status %d", status);
6393 }
6394}
6395
6396void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6397{
6398 Mutex::Autolock _l(pmLock);
6399
6400 if (mWakeLockToken != 0) {
6401 ALOGV("releaseWakeLock()");
6402 if (mPowerManager != 0) {
6403 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6404 }
6405 mWakeLockToken.clear();
6406 }
6407}
6408
6409void AudioFlinger::DirectAudioTrack::clearPowerManager()
6410{
6411 Mutex::Autolock _l(pmLock);
6412 releaseWakeLock();
6413 mPowerManager.clear();
6414}
6415
6416void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6417{
6418 parentClass->clearPowerManager();
6419 ALOGW("power manager service died !!!");
6420}
6421#endif
6422
6423// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424
6425AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6426 : BnAudioTrack(),
6427 mTrack(track)
6428{
6429}
6430
6431AudioFlinger::TrackHandle::~TrackHandle() {
6432 // just stop the track on deletion, associated resources
6433 // will be freed from the main thread once all pending buffers have
6434 // been played. Unless it's not in the active track list, in which
6435 // case we free everything now...
6436 mTrack->destroy();
6437}
6438
Glenn Kasten90716c52012-01-26 13:40:12 -08006439sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6440 return mTrack->getCblk();
6441}
6442
Glenn Kasten3acbd052012-02-28 10:39:56 -08006443status_t AudioFlinger::TrackHandle::start() {
6444 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445}
6446
6447void AudioFlinger::TrackHandle::stop() {
6448 mTrack->stop();
6449}
6450
6451void AudioFlinger::TrackHandle::flush() {
6452 mTrack->flush();
6453}
6454
6455void AudioFlinger::TrackHandle::mute(bool e) {
6456 mTrack->mute(e);
6457}
6458
6459void AudioFlinger::TrackHandle::pause() {
6460 mTrack->pause();
6461}
6462
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6464{
6465 return mTrack->attachAuxEffect(EffectId);
6466}
6467
John Grossman4ff14ba2012-02-08 16:37:41 -08006468status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6469 sp<IMemory>* buffer) {
6470 if (!mTrack->isTimedTrack())
6471 return INVALID_OPERATION;
6472
6473 PlaybackThread::TimedTrack* tt =
6474 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6475 return tt->allocateTimedBuffer(size, buffer);
6476}
6477
6478status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6479 int64_t pts) {
6480 if (!mTrack->isTimedTrack())
6481 return INVALID_OPERATION;
6482
6483 PlaybackThread::TimedTrack* tt =
6484 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6485 return tt->queueTimedBuffer(buffer, pts);
6486}
6487
6488status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6489 const LinearTransform& xform, int target) {
6490
6491 if (!mTrack->isTimedTrack())
6492 return INVALID_OPERATION;
6493
6494 PlaybackThread::TimedTrack* tt =
6495 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6496 return tt->setMediaTimeTransform(
6497 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6498}
6499
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500status_t AudioFlinger::TrackHandle::onTransact(
6501 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6502{
6503 return BnAudioTrack::onTransact(code, data, reply, flags);
6504}
6505
6506// ----------------------------------------------------------------------------
6507
6508sp<IAudioRecord> AudioFlinger::openRecord(
6509 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006510 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006512 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006513 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006515 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006516 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 int *sessionId,
6518 status_t *status)
6519{
6520 sp<RecordThread::RecordTrack> recordTrack;
6521 sp<RecordHandle> recordHandle;
6522 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 status_t lStatus;
6524 RecordThread *thread;
6525 size_t inFrameCount;
6526 int lSessionId;
6527
6528 // check calling permissions
6529 if (!recordingAllowed()) {
6530 lStatus = PERMISSION_DENIED;
6531 goto Exit;
6532 }
6533
6534 // add client to list
6535 { // scope for mLock
6536 Mutex::Autolock _l(mLock);
6537 thread = checkRecordThread_l(input);
6538 if (thread == NULL) {
6539 lStatus = BAD_VALUE;
6540 goto Exit;
6541 }
6542
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006543 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544
6545 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006546 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 lSessionId = *sessionId;
6548 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006549 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 if (sessionId != NULL) {
6551 *sessionId = lSessionId;
6552 }
6553 }
6554 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006555 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6556 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006558 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6560 // destructor is called by the TrackBase destructor with mLock held
6561 client.clear();
6562 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563 goto Exit;
6564 }
6565
6566 // return to handle to client
6567 recordHandle = new RecordHandle(recordTrack);
6568 lStatus = NO_ERROR;
6569
6570Exit:
6571 if (status) {
6572 *status = lStatus;
6573 }
6574 return recordHandle;
6575}
6576
6577// ----------------------------------------------------------------------------
6578
6579AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6580 : BnAudioRecord(),
6581 mRecordTrack(recordTrack)
6582{
6583}
6584
6585AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006586 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006587 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588}
6589
Glenn Kasten90716c52012-01-26 13:40:12 -08006590sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6591 return mRecordTrack->getCblk();
6592}
6593
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006594status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006595 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006596 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597}
6598
6599void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006600 stop_nonvirtual();
6601}
6602
6603void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006604 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 mRecordTrack->stop();
6606}
6607
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608status_t AudioFlinger::RecordHandle::onTransact(
6609 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6610{
6611 return BnAudioRecord::onTransact(code, data, reply, flags);
6612}
6613
6614// ----------------------------------------------------------------------------
6615
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006616AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6617 AudioStreamIn *input,
6618 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006619 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006620 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006621 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006622 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006623 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006624 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006625 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006626 mReqSampleRate(sampleRate)
6627 // mBytesRead is only meaningful while active, and so is cleared in start()
6628 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629{
Glenn Kasten480b4682012-02-28 12:30:08 -08006630 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006631
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 readInputParameters();
6633}
6634
6635
6636AudioFlinger::RecordThread::~RecordThread()
6637{
6638 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006639 delete mResampler;
6640 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641}
6642
6643void AudioFlinger::RecordThread::onFirstRef()
6644{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006645 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646}
6647
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006648status_t AudioFlinger::RecordThread::readyToRun()
6649{
6650 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006651 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006652 return status;
6653}
6654
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655bool AudioFlinger::RecordThread::threadLoop()
6656{
6657 AudioBufferProvider::Buffer buffer;
6658 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006659 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660
Eric Laurent44d98482010-09-30 16:12:31 -07006661 nsecs_t lastWarning = 0;
6662
Glenn Kastene4e2a372012-07-23 12:55:09 -07006663 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006664 acquireWakeLock();
6665
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006666 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006667 bool readOnce = false;
6668
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 // start recording
6670 while (!exitPending()) {
6671
6672 processConfigEvents();
6673
6674 { // scope for mLock
6675 Mutex::Autolock _l(mLock);
6676 checkForNewParameters_l();
6677 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006678 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679
6680 if (exitPending()) break;
6681
Eric Laurentfeb0db62011-07-22 09:04:31 -07006682 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006683 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 // go to sleep
6685 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006686 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006687 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 continue;
6689 }
6690 if (mActiveTrack != 0) {
6691 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006692 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693 mActiveTrack.clear();
6694 mStartStopCond.broadcast();
6695 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6696 if (mReqChannelCount != mActiveTrack->channelCount()) {
6697 mActiveTrack.clear();
6698 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006699 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 // record start succeeds only if first read from audio input
6701 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006702 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006703 mActiveTrack->mState = TrackBase::ACTIVE;
6704 } else {
6705 mActiveTrack.clear();
6706 }
6707 mStartStopCond.broadcast();
6708 }
6709 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006710 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6711 removeTrack_l(mActiveTrack);
6712 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 }
6714 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006715 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716 }
6717
6718 if (mActiveTrack != 0) {
6719 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6720 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006721 unlockEffectChains(effectChains);
6722 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006723 continue;
6724 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006725 for (size_t i = 0; i < effectChains.size(); i ++) {
6726 effectChains[i]->process_l();
6727 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006728
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006730 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006731 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006733 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 // no resampling
6735 while (framesOut) {
6736 size_t framesIn = mFrameCount - mRsmpInIndex;
6737 if (framesIn) {
6738 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6739 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6740 if (framesIn > framesOut)
6741 framesIn = framesOut;
6742 mRsmpInIndex += framesIn;
6743 framesOut -= framesIn;
6744 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006745 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 memcpy(dst, src, framesIn * mFrameSize);
6747 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006749 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6750 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006752 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6753 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006754 }
6755 }
6756 }
6757 if (framesOut && mFrameCount == mRsmpInIndex) {
6758 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006759 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006760 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 framesOut = 0;
6762 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006763 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764 mRsmpInIndex = 0;
6765 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006766 if (mBytesRead <= 0) {
6767 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6768 {
6769 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 // Force input into standby so that it tries to
6771 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006772 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006773 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 }
6775 mRsmpInIndex = mFrameCount;
6776 framesOut = 0;
6777 buffer.frameCount = 0;
6778 }
6779 }
6780 }
6781 } else {
6782 // resampling
6783
6784 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6785 // alter output frame count as if we were expecting stereo samples
6786 if (mChannelCount == 1 && mReqChannelCount == 1) {
6787 framesOut >>= 1;
6788 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006789 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6791 // are 32 bit aligned which should be always true.
6792 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006793 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006795 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6796 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006798 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 }
6800
6801 }
Eric Laurenta011e352012-03-29 15:51:43 -07006802 if (mFramestoDrop == 0) {
6803 mActiveTrack->releaseBuffer(&buffer);
6804 } else {
6805 if (mFramestoDrop > 0) {
6806 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006807 if (mFramestoDrop <= 0) {
6808 clearSyncStartEvent();
6809 }
6810 } else {
6811 mFramestoDrop += buffer.frameCount;
6812 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6813 mSyncStartEvent->isCancelled()) {
6814 ALOGW("Synced record %s, session %d, trigger session %d",
6815 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6816 mActiveTrack->sessionId(),
6817 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6818 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006819 }
6820 }
6821 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006822 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823 }
6824 // client isn't retrieving buffers fast enough
6825 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006826 if (!mActiveTrack->setOverflow()) {
6827 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006828 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006829 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006830 lastWarning = now;
6831 }
6832 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 // Release the processor for a while before asking for a new buffer.
6834 // This will give the application more chance to read from the buffer and
6835 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006836 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 }
6838 }
Eric Laurentec437d82011-07-26 20:54:46 -07006839 // enable changes in effect chain
6840 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006841 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 }
6843
Glenn Kastene4e2a372012-07-23 12:55:09 -07006844 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845
Glenn Kasten33e6e352012-07-16 15:56:57 -07006846 {
6847 Mutex::Autolock _l(mLock);
6848 mActiveTrack.clear();
6849 mStartStopCond.broadcast();
6850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851
Eric Laurentfeb0db62011-07-22 09:04:31 -07006852 releaseWakeLock();
6853
Steve Block3856b092011-10-20 11:56:00 +01006854 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855 return false;
6856}
6857
Glenn Kastene4e2a372012-07-23 12:55:09 -07006858void AudioFlinger::RecordThread::standby()
6859{
6860 if (!mStandby) {
6861 inputStandBy();
6862 mStandby = true;
6863 }
6864}
6865
6866void AudioFlinger::RecordThread::inputStandBy()
6867{
6868 mInput->stream->common.standby(&mInput->stream->common);
6869}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006870
6871sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6872 const sp<AudioFlinger::Client>& client,
6873 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006874 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006875 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006878 IAudioFlinger::track_flags_t flags,
6879 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006880 status_t *status)
6881{
6882 sp<RecordTrack> track;
6883 status_t lStatus;
6884
6885 lStatus = initCheck();
6886 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006887 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006888 goto Exit;
6889 }
6890
Glenn Kasten1879fff2012-07-11 15:36:59 -07006891 // FIXME use flags and tid similar to createTrack_l()
6892
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006893 { // scope for mLock
6894 Mutex::Autolock _l(mLock);
6895
6896 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006897 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006898
Glenn Kasten7378ca52012-01-20 13:44:40 -08006899 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006900 lStatus = NO_MEMORY;
6901 goto Exit;
6902 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006903 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006904
Eric Laurent59bd0da2011-08-01 09:52:20 -07006905 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006906 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006907 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006908 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6909 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006910 }
6911 lStatus = NO_ERROR;
6912
6913Exit:
6914 if (status) {
6915 *status = lStatus;
6916 }
6917 return track;
6918}
6919
Eric Laurenta011e352012-03-29 15:51:43 -07006920status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006921 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006922 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923{
Glenn Kasten58912562012-04-03 10:45:00 -07006924 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006925 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006927
6928 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006929 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006930 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6931 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6932 triggerSession,
6933 recordTrack->sessionId(),
6934 syncStartEventCallback,
6935 this);
Eric Laurent29864602012-05-08 18:57:51 -07006936 // Sync event can be cancelled by the trigger session if the track is not in a
6937 // compatible state in which case we start record immediately
6938 if (mSyncStartEvent->isCancelled()) {
6939 clearSyncStartEvent();
6940 } else {
6941 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6942 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6943 }
Eric Laurenta011e352012-03-29 15:51:43 -07006944 }
6945
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006947 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 if (mActiveTrack != 0) {
6949 if (recordTrack != mActiveTrack.get()) {
6950 status = -EBUSY;
6951 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6952 mActiveTrack->mState = TrackBase::ACTIVE;
6953 }
6954 return status;
6955 }
6956
6957 recordTrack->mState = TrackBase::IDLE;
6958 mActiveTrack = recordTrack;
6959 mLock.unlock();
6960 status_t status = AudioSystem::startInput(mId);
6961 mLock.lock();
6962 if (status != NO_ERROR) {
6963 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006964 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 return status;
6966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 mRsmpInIndex = mFrameCount;
6968 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006969 if (mResampler != NULL) {
6970 mResampler->reset();
6971 }
6972 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006974 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006975 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006977 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 mActiveTrack.clear();
6979 status = INVALID_OPERATION;
6980 goto startError;
6981 }
6982 mStartStopCond.wait(mLock);
6983 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 status = BAD_VALUE;
6986 goto startError;
6987 }
Steve Block3856b092011-10-20 11:56:00 +01006988 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 return status;
6990 }
6991startError:
6992 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006993 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 return status;
6995}
6996
Eric Laurenta011e352012-03-29 15:51:43 -07006997void AudioFlinger::RecordThread::clearSyncStartEvent()
6998{
6999 if (mSyncStartEvent != 0) {
7000 mSyncStartEvent->cancel();
7001 }
7002 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007003 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007004}
7005
7006void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7007{
7008 sp<SyncEvent> strongEvent = event.promote();
7009
7010 if (strongEvent != 0) {
7011 RecordThread *me = (RecordThread *)strongEvent->cookie();
7012 me->handleSyncStartEvent(strongEvent);
7013 }
7014}
7015
7016void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7017{
Eric Laurent29864602012-05-08 18:57:51 -07007018 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007019 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7020 // from audio HAL
7021 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007022 }
7023}
7024
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007025bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007026 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007027 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7028 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007030 recordTrack->mState = TrackBase::PAUSING;
7031 // do not wait for mStartStopCond if exiting
7032 if (exitPending()) {
7033 return true;
7034 }
7035 mStartStopCond.wait(mLock);
7036 // if we have been restarted, recordTrack == mActiveTrack.get() here
7037 if (exitPending() || recordTrack != mActiveTrack.get()) {
7038 ALOGV("Record stopped OK");
7039 return true;
7040 }
7041 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042}
7043
Glenn Kasten106e8a42012-08-02 13:37:12 -07007044bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007045{
7046 return false;
7047}
7048
7049status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7050{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007051#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 -07007052 if (!isValidSyncEvent(event)) {
7053 return BAD_VALUE;
7054 }
7055
Glenn Kasten510a3d62012-07-16 14:24:34 -07007056 int eventSession = event->triggerSession();
7057 status_t ret = NAME_NOT_FOUND;
7058
Eric Laurenta011e352012-03-29 15:51:43 -07007059 Mutex::Autolock _l(mLock);
7060
Glenn Kasten510a3d62012-07-16 14:24:34 -07007061 for (size_t i = 0; i < mTracks.size(); i++) {
7062 sp<RecordTrack> track = mTracks[i];
7063 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007064 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007065 ret = NO_ERROR;
7066 }
Eric Laurenta011e352012-03-29 15:51:43 -07007067 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007068 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007069#else
7070 return BAD_VALUE;
7071#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007072}
7073
7074void AudioFlinger::RecordThread::RecordTrack::destroy()
7075{
7076 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7077 sp<RecordTrack> keep(this);
7078 {
7079 sp<ThreadBase> thread = mThread.promote();
7080 if (thread != 0) {
7081 if (mState == ACTIVE || mState == RESUMING) {
7082 AudioSystem::stopInput(thread->id());
7083 }
7084 AudioSystem::releaseInput(thread->id());
7085 Mutex::Autolock _l(thread->mLock);
7086 RecordThread *recordThread = (RecordThread *) thread.get();
7087 recordThread->destroyTrack_l(this);
7088 }
7089 }
7090}
7091
7092// destroyTrack_l() must be called with ThreadBase::mLock held
7093void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7094{
7095 track->mState = TrackBase::TERMINATED;
7096 // active tracks are removed by threadLoop()
7097 if (mActiveTrack != track) {
7098 removeTrack_l(track);
7099 }
7100}
7101
7102void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7103{
7104 mTracks.remove(track);
7105 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007106}
7107
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007108void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007110 dumpInternals(fd, args);
7111 dumpTracks(fd, args);
7112 dumpEffectChains(fd, args);
7113}
7114
7115void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7116{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 const size_t SIZE = 256;
7118 char buffer[SIZE];
7119 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120
7121 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7122 result.append(buffer);
7123
7124 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7126 result.append(buffer);
7127 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7128 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007129 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 result.append(buffer);
7131 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7132 result.append(buffer);
7133 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7134 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007136 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007138
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 write(fd, result.string(), result.size());
7140
7141 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007142}
7143
7144void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7145{
7146 const size_t SIZE = 256;
7147 char buffer[SIZE];
7148 String8 result;
7149
7150 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7151 result.append(buffer);
7152 RecordTrack::appendDumpHeader(result);
7153 for (size_t i = 0; i < mTracks.size(); ++i) {
7154 sp<RecordTrack> track = mTracks[i];
7155 if (track != 0) {
7156 track->dump(buffer, SIZE);
7157 result.append(buffer);
7158 }
7159 }
7160
7161 if (mActiveTrack != 0) {
7162 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7163 result.append(buffer);
7164 RecordTrack::appendDumpHeader(result);
7165 mActiveTrack->dump(buffer, SIZE);
7166 result.append(buffer);
7167
7168 }
7169 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170}
7171
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007172// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007173status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174{
7175 size_t framesReq = buffer->frameCount;
7176 size_t framesReady = mFrameCount - mRsmpInIndex;
7177 int channelCount;
7178
7179 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007180 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007181 if (mBytesRead <= 0) {
7182 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7183 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184 // Force input into standby so that it tries to
7185 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007186 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007187 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007189 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190 buffer->frameCount = 0;
7191 return NOT_ENOUGH_DATA;
7192 }
7193 mRsmpInIndex = 0;
7194 framesReady = mFrameCount;
7195 }
7196
7197 if (framesReq > framesReady) {
7198 framesReq = framesReady;
7199 }
7200
7201 if (mChannelCount == 1 && mReqChannelCount == 2) {
7202 channelCount = 1;
7203 } else {
7204 channelCount = 2;
7205 }
7206 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7207 buffer->frameCount = framesReq;
7208 return NO_ERROR;
7209}
7210
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007211// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7213{
7214 mRsmpInIndex += buffer->frameCount;
7215 buffer->frameCount = 0;
7216}
7217
7218bool AudioFlinger::RecordThread::checkForNewParameters_l()
7219{
7220 bool reconfig = false;
7221
7222 while (!mNewParameters.isEmpty()) {
7223 status_t status = NO_ERROR;
7224 String8 keyValuePair = mNewParameters[0];
7225 AudioParameter param = AudioParameter(keyValuePair);
7226 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007227 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 int reqSamplingRate = mReqSampleRate;
7229 int reqChannelCount = mReqChannelCount;
7230
7231 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7232 reqSamplingRate = value;
7233 reconfig = true;
7234 }
7235 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007236 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237 reconfig = true;
7238 }
7239 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007240 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241 reconfig = true;
7242 }
7243 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7244 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007245 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 // if frame count is changed after track creation
7247 if (mActiveTrack != 0) {
7248 status = INVALID_OPERATION;
7249 } else {
7250 reconfig = true;
7251 }
7252 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007253 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7254 // forward device change to effects that have requested to be
7255 // aware of attached audio device.
7256 for (size_t i = 0; i < mEffectChains.size(); i++) {
7257 mEffectChains[i]->setDevice_l(value);
7258 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007259
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007260 // store input device and output device but do not forward output device to audio HAL.
7261 // Note that status is ignored by the caller for output device
7262 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007263 if (audio_is_output_devices(value)) {
7264 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007265 status = BAD_VALUE;
7266 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007267 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007268 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007269 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007270 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7271 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007272 for (size_t i = 0; i < mTracks.size(); i++) {
7273 sp<RecordTrack> track = mTracks[i];
7274 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7275 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7276 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007277 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007278 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007279 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007280 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7281 mAudioSource != (audio_source_t)value) {
7282 // forward device change to effects that have requested to be
7283 // aware of attached audio device.
7284 for (size_t i = 0; i < mEffectChains.size(); i++) {
7285 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7286 }
7287 mAudioSource = (audio_source_t)value;
7288 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007290 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007292 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007293 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7294 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 }
7296 if (reconfig) {
7297 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007298 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007299 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007300 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007301 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007302 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303 status = NO_ERROR;
7304 }
7305 if (status == NO_ERROR) {
7306 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007307 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 }
7309 }
7310 }
7311
7312 mNewParameters.removeAt(0);
7313
7314 mParamStatus = status;
7315 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007316 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7317 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007318 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 }
7320 return reconfig;
7321}
7322
7323String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7324{
Dima Zavinfce7a472011-04-19 22:30:36 -07007325 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007326 String8 out_s8 = String8();
7327
7328 Mutex::Autolock _l(mLock);
7329 if (initCheck() != NO_ERROR) {
7330 return out_s8;
7331 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007332
Dima Zavin799a70e2011-04-18 16:57:27 -07007333 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007334 out_s8 = String8(s);
7335 free(s);
7336 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337}
7338
7339void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7340 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007341 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342
7343 switch (event) {
7344 case AudioSystem::INPUT_OPENED:
7345 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007346 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 desc.samplingRate = mSampleRate;
7348 desc.format = mFormat;
7349 desc.frameCount = mFrameCount;
7350 desc.latency = 0;
7351 param2 = &desc;
7352 break;
7353
7354 case AudioSystem::INPUT_CLOSED:
7355 default:
7356 break;
7357 }
7358 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7359}
7360
7361void AudioFlinger::RecordThread::readInputParameters()
7362{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007363 delete mRsmpInBuffer;
7364 // mRsmpInBuffer is always assigned a new[] below
7365 delete mRsmpOutBuffer;
7366 mRsmpOutBuffer = NULL;
7367 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007368 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369
Dima Zavin799a70e2011-04-18 16:57:27 -07007370 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007371 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007372 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007373 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007374 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007375 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007377 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7379
Glenn Kasten53d76db2012-03-08 12:32:47 -08007380 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381 {
7382 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007383 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7384 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 if (mChannelCount == 1 && mReqChannelCount == 2) {
7386 channelCount = 1;
7387 } else {
7388 channelCount = 2;
7389 }
7390 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7391 mResampler->setSampleRate(mSampleRate);
7392 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7393 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7394
7395 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7396 if (mChannelCount == 1 && mReqChannelCount == 1) {
7397 mFrameCount >>= 1;
7398 }
7399
7400 }
7401 mRsmpInIndex = mFrameCount;
7402}
7403
7404unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7405{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007406 Mutex::Autolock _l(mLock);
7407 if (initCheck() != NO_ERROR) {
7408 return 0;
7409 }
7410
Dima Zavin799a70e2011-04-18 16:57:27 -07007411 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412}
7413
Glenn Kasten106e8a42012-08-02 13:37:12 -07007414uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415{
7416 Mutex::Autolock _l(mLock);
7417 uint32_t result = 0;
7418 if (getEffectChain_l(sessionId) != 0) {
7419 result = EFFECT_SESSION;
7420 }
7421
Glenn Kasten510a3d62012-07-16 14:24:34 -07007422 for (size_t i = 0; i < mTracks.size(); ++i) {
7423 if (sessionId == mTracks[i]->sessionId()) {
7424 result |= TRACK_SESSION;
7425 break;
7426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007427 }
7428
7429 return result;
7430}
7431
Glenn Kasten106e8a42012-08-02 13:37:12 -07007432KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007433{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007434 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007435 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007436 for (size_t j = 0; j < mTracks.size(); ++j) {
7437 sp<RecordThread::RecordTrack> track = mTracks[j];
7438 int sessionId = track->sessionId();
7439 if (ids.indexOfKey(sessionId) < 0) {
7440 ids.add(sessionId, true);
7441 }
7442 }
7443 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007444}
7445
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007446AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7447{
7448 Mutex::Autolock _l(mLock);
7449 AudioStreamIn *input = mInput;
7450 mInput = NULL;
7451 return input;
7452}
7453
7454// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007455audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007456{
7457 if (mInput == NULL) {
7458 return NULL;
7459 }
7460 return &mInput->stream->common;
7461}
7462
7463
Mathias Agopian65ab4712010-07-14 17:59:35 -07007464// ----------------------------------------------------------------------------
7465
Eric Laurenta4c5a552012-03-29 10:12:40 -07007466audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7467{
7468 if (!settingsAllowed()) {
7469 return 0;
7470 }
7471 Mutex::Autolock _l(mLock);
7472 return loadHwModule_l(name);
7473}
7474
7475// loadHwModule_l() must be called with AudioFlinger::mLock held
7476audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7477{
7478 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7479 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7480 ALOGW("loadHwModule() module %s already loaded", name);
7481 return mAudioHwDevs.keyAt(i);
7482 }
7483 }
7484
Eric Laurenta4c5a552012-03-29 10:12:40 -07007485 audio_hw_device_t *dev;
7486
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007487 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007488 if (rc) {
7489 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7490 return 0;
7491 }
7492
7493 mHardwareStatus = AUDIO_HW_INIT;
7494 rc = dev->init_check(dev);
7495 mHardwareStatus = AUDIO_HW_IDLE;
7496 if (rc) {
7497 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7498 return 0;
7499 }
7500
John Grossmanee578c02012-07-23 17:05:46 -07007501 // Check and cache this HAL's level of support for master mute and master
7502 // volume. If this is the first HAL opened, and it supports the get
7503 // methods, use the initial values provided by the HAL as the current
7504 // master mute and volume settings.
7505
7506 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7507 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007508 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007509
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007510#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007511 if (0 == mAudioHwDevs.size()) {
7512 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7513 if (NULL != dev->get_master_volume) {
7514 float mv;
7515 if (OK == dev->get_master_volume(dev, &mv)) {
7516 mMasterVolume = mv;
7517 }
7518 }
7519
7520 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7521 if (NULL != dev->get_master_mute) {
7522 bool mm;
7523 if (OK == dev->get_master_mute(dev, &mm)) {
7524 mMasterMute = mm;
7525 }
7526 }
7527 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007528#endif
John Grossmanee578c02012-07-23 17:05:46 -07007529
Eric Laurenta4c5a552012-03-29 10:12:40 -07007530 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007531 if ((NULL != dev->set_master_volume) &&
7532 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7533 flags = static_cast<AudioHwDevice::Flags>(flags |
7534 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7535 }
7536
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007537#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007538 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7539 if ((NULL != dev->set_master_mute) &&
7540 (OK == dev->set_master_mute(dev, mMasterMute))) {
7541 flags = static_cast<AudioHwDevice::Flags>(flags |
7542 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7543 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007544#endif
John Grossmanee578c02012-07-23 17:05:46 -07007545
Eric Laurenta4c5a552012-03-29 10:12:40 -07007546 mHardwareStatus = AUDIO_HW_IDLE;
7547 }
7548
7549 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007550 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007551
7552 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007553 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007554
7555 return handle;
7556
7557}
7558
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007559// ----------------------------------------------------------------------------
7560
7561int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7562{
7563 Mutex::Autolock _l(mLock);
7564 PlaybackThread *thread = primaryPlaybackThread_l();
7565 return thread != NULL ? thread->sampleRate() : 0;
7566}
7567
7568int32_t AudioFlinger::getPrimaryOutputFrameCount()
7569{
7570 Mutex::Autolock _l(mLock);
7571 PlaybackThread *thread = primaryPlaybackThread_l();
7572 return thread != NULL ? thread->frameCountHAL() : 0;
7573}
7574
7575// ----------------------------------------------------------------------------
7576
Eric Laurenta4c5a552012-03-29 10:12:40 -07007577audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7578 audio_devices_t *pDevices,
7579 uint32_t *pSamplingRate,
7580 audio_format_t *pFormat,
7581 audio_channel_mask_t *pChannelMask,
7582 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007583 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584{
7585 status_t status;
7586 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007587 struct audio_config config = {
7588 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7589 channel_mask: pChannelMask ? *pChannelMask : 0,
7590 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7591 };
7592 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007593 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594
Eric Laurenta4c5a552012-03-29 10:12:40 -07007595 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7596 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007597 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007598 config.sample_rate,
7599 config.format,
7600 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007601 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602
7603 if (pDevices == NULL || *pDevices == 0) {
7604 return 0;
7605 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007606
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607 Mutex::Autolock _l(mLock);
7608
Eric Laurenta4c5a552012-03-29 10:12:40 -07007609 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007610 if (outHwDev == NULL)
7611 return 0;
7612
John Grossmanee578c02012-07-23 17:05:46 -07007613 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007614 audio_io_handle_t id = nextUniqueId();
7615
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007616 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007617
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007618#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007619 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007620 id,
7621 *pDevices,
7622 (audio_output_flags_t)flags,
7623 &config,
7624 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007625#else
7626 status = hwDevHal->open_output_stream(hwDevHal,
7627 *pDevices,
7628 (int *)&config.format,
7629 &config.channel_mask,
7630 &config.sample_rate,
7631 &outStream);
7632 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7633 flags = (audio_output_flags_t)newflags;
7634#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007635
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007636 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007637 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007638 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007639 config.sample_rate,
7640 config.format,
7641 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007642 status);
7643
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007644 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007645 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007646#ifdef QCOM_HARDWARE
7647 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7648 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7649 desc->mActive = true;
7650 //TODO: no stream type
7651 //desc->mStreamType = streamType;
7652 desc->mVolumeLeft = 1.0;
7653 desc->mVolumeRight = 1.0;
7654 desc->device = *pDevices;
7655 mDirectAudioTracks.add(id, desc);
7656 } else
7657#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007658 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007659 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7660 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007662 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 } else {
7664 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007665 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666 }
vivek mehta2192bc92012-12-04 11:46:08 -08007667#ifdef QCOM_HARDWARE
7668 if (thread != NULL)
7669#endif
7670 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007672 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7673 if (pFormat != NULL) *pFormat = config.format;
7674 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007675#ifdef QCOM_HARDWARE
7676 if (thread != NULL) {
7677#endif
7678 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7679 // notify client processes of the new output creation
7680 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7681#ifdef QCOM_HARDWARE
7682 }
7683 else {
7684 *pLatencyMs = 0;
7685 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7686 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7687 *pLatencyMs = desc->stream->get_latency(desc->stream);
7688 }
7689 }
7690#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007691 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007692 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007693 ALOGI("Using module %d has the primary audio interface", module);
7694 mPrimaryHardwareDev = outHwDev;
7695
7696 AutoMutex lock(mHardwareLock);
7697 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007698 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007699 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 return id;
7702 }
7703
7704 return 0;
7705}
7706
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007707audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7708 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709{
7710 Mutex::Autolock _l(mLock);
7711 MixerThread *thread1 = checkMixerThread_l(output1);
7712 MixerThread *thread2 = checkMixerThread_l(output2);
7713
7714 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007715 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716 return 0;
7717 }
7718
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007719 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7721 thread->addOutputTrack(thread2);
7722 mPlaybackThreads.add(id, thread);
7723 // notify client processes of the new output creation
7724 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7725 return id;
7726}
7727
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007728status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729{
Glenn Kastend96c5722012-04-25 13:44:49 -07007730 return closeOutput_nonvirtual(output);
7731}
7732
7733status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7734{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735 // keep strong reference on the playback thread so that
7736 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007737#ifdef QCOM_HARDWARE
7738 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7739 if (desc) {
7740 ALOGV("Closing DirectTrack output %d", output);
7741 desc->mActive = false;
7742 desc->stream->common.standby(&desc->stream->common);
7743 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7744 desc->trackRefPtr = NULL;
7745 mDirectAudioTracks.removeItem(output);
7746 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7747 delete desc;
7748 return NO_ERROR;
7749 }
7750#endif
7751
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007752 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 {
7754 Mutex::Autolock _l(mLock);
7755 thread = checkPlaybackThread_l(output);
7756 if (thread == NULL) {
7757 return BAD_VALUE;
7758 }
7759
Steve Block3856b092011-10-20 11:56:00 +01007760 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007762 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007764 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7766 dupThread->removeOutputTrack((MixerThread *)thread.get());
7767 }
7768 }
7769 }
Glenn Kastena1117922012-01-26 10:53:32 -08007770 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007771 mPlaybackThreads.removeItem(output);
7772 }
7773 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007774 // The thread entity (active unit of execution) is no longer running here,
7775 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007777 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007778 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007779 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007780 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007781 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007782 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 }
7784 return NO_ERROR;
7785}
7786
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007787status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788{
7789 Mutex::Autolock _l(mLock);
7790 PlaybackThread *thread = checkPlaybackThread_l(output);
7791
7792 if (thread == NULL) {
7793 return BAD_VALUE;
7794 }
7795
Steve Block3856b092011-10-20 11:56:00 +01007796 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 thread->suspend();
7798
7799 return NO_ERROR;
7800}
7801
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007802status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803{
7804 Mutex::Autolock _l(mLock);
7805 PlaybackThread *thread = checkPlaybackThread_l(output);
7806
7807 if (thread == NULL) {
7808 return BAD_VALUE;
7809 }
7810
Steve Block3856b092011-10-20 11:56:00 +01007811 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812
7813 thread->restore();
7814
7815 return NO_ERROR;
7816}
7817
Eric Laurenta4c5a552012-03-29 10:12:40 -07007818audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7819 audio_devices_t *pDevices,
7820 uint32_t *pSamplingRate,
7821 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007822 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823{
7824 status_t status;
7825 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007826 struct audio_config config = {
7827 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7828 channel_mask: pChannelMask ? *pChannelMask : 0,
7829 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7830 };
7831 uint32_t reqSamplingRate = config.sample_rate;
7832 audio_format_t reqFormat = config.format;
7833 audio_channel_mask_t reqChannels = config.channel_mask;
7834 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007835 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836
7837 if (pDevices == NULL || *pDevices == 0) {
7838 return 0;
7839 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007840
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841 Mutex::Autolock _l(mLock);
7842
Eric Laurenta4c5a552012-03-29 10:12:40 -07007843 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007844 if (inHwDev == NULL)
7845 return 0;
7846
John Grossmanee578c02012-07-23 17:05:46 -07007847 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007848 audio_io_handle_t id = nextUniqueId();
7849
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007850#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007851 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007852 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007853#else
7854 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7855 (int *)&config.format,
7856 &config.channel_mask,
7857 &config.sample_rate, (audio_in_acoustics_t)0,
7858 &inStream);
7859#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007860 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007861 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007862 config.sample_rate,
7863 config.format,
7864 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 status);
7866
7867 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7868 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7869 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007870 if (status == BAD_VALUE &&
7871 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7872 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007873 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007874 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007875 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007876#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007877 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007878#else
7879 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7880 (int *)&config.format,
7881 &config.channel_mask,
7882 &config.sample_rate, (audio_in_acoustics_t)0,
7883 &inStream);
7884#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 }
7886
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007887 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007888 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7889
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007890 // Start record thread
7891 // RecorThread require both input and output device indication to forward to audio
7892 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007893 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007894 thread = new RecordThread(this,
7895 input,
7896 reqSamplingRate,
7897 reqChannels,
7898 id,
7899 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007901 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007902 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007903 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007904 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 // notify client processes of the new input creation
7907 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7908 return id;
7909 }
7910
7911 return 0;
7912}
7913
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007914status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915{
Glenn Kastend96c5722012-04-25 13:44:49 -07007916 return closeInput_nonvirtual(input);
7917}
7918
7919status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7920{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921 // keep strong reference on the record thread so that
7922 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007923 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924 {
7925 Mutex::Autolock _l(mLock);
7926 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007927 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928 return BAD_VALUE;
7929 }
7930
Steve Block3856b092011-10-20 11:56:00 +01007931 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007932 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007933 mRecordThreads.removeItem(input);
7934 }
7935 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007936 // The thread entity (active unit of execution) is no longer running here,
7937 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007939 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007940 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007941 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007942 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007943 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944
7945 return NO_ERROR;
7946}
7947
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007948status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949{
7950 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007951 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952
7953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7954 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007955 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007957
7958 return NO_ERROR;
7959}
7960
7961
7962int AudioFlinger::newAudioSessionId()
7963{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007964 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965}
7966
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007967void AudioFlinger::acquireAudioSessionId(int audioSession)
7968{
7969 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007970 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007971 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007972 size_t num = mAudioSessionRefs.size();
7973 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007974 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007975 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7976 ref->mCnt++;
7977 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007978 return;
7979 }
7980 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007981 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7982 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007983}
7984
7985void AudioFlinger::releaseAudioSessionId(int audioSession)
7986{
7987 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007988 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007989 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007990 size_t num = mAudioSessionRefs.size();
7991 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007992 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007993 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7994 ref->mCnt--;
7995 ALOGV(" decremented refcount to %d", ref->mCnt);
7996 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007997 mAudioSessionRefs.removeAt(i);
7998 delete ref;
7999 purgeStaleEffects_l();
8000 }
8001 return;
8002 }
8003 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008004 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008005}
8006
8007void AudioFlinger::purgeStaleEffects_l() {
8008
Steve Block3856b092011-10-20 11:56:00 +01008009 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008010
8011 Vector< sp<EffectChain> > chains;
8012
8013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8014 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8015 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8016 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008017 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8018 chains.push(ec);
8019 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008020 }
8021 }
8022 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8023 sp<RecordThread> t = mRecordThreads.valueAt(i);
8024 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8025 sp<EffectChain> ec = t->mEffectChains[j];
8026 chains.push(ec);
8027 }
8028 }
8029
8030 for (size_t i = 0; i < chains.size(); i++) {
8031 sp<EffectChain> ec = chains[i];
8032 int sessionid = ec->sessionId();
8033 sp<ThreadBase> t = ec->mThread.promote();
8034 if (t == 0) {
8035 continue;
8036 }
8037 size_t numsessionrefs = mAudioSessionRefs.size();
8038 bool found = false;
8039 for (size_t k = 0; k < numsessionrefs; k++) {
8040 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008041 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008042 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008043 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008044 found = true;
8045 break;
8046 }
8047 }
8048 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008049 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008050 // remove all effects from the chain
8051 while (ec->mEffects.size()) {
8052 sp<EffectModule> effect = ec->mEffects[0];
8053 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008054 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008055 if (effect->purgeHandles()) {
8056 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008057 }
8058 AudioSystem::unregisterEffect(effect->id());
8059 }
8060 }
8061 }
8062 return;
8063}
8064
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008066AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008067{
Glenn Kastena1117922012-01-26 10:53:32 -08008068 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008069}
8070
8071// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008072AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073{
8074 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008075 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076}
8077
8078// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008079AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080{
Glenn Kastena1117922012-01-26 10:53:32 -08008081 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082}
8083
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008084uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008086 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087}
8088
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008089AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008090{
8091 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8092 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008093 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008094 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008095 return thread;
8096 }
8097 }
8098 return NULL;
8099}
8100
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008101audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008102{
8103 PlaybackThread *thread = primaryPlaybackThread_l();
8104
8105 if (thread == NULL) {
8106 return 0;
8107 }
8108
Eric Laurentf1c04f92012-08-28 14:26:53 -07008109 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008110}
8111
Eric Laurenta011e352012-03-29 15:51:43 -07008112sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8113 int triggerSession,
8114 int listenerSession,
8115 sync_event_callback_t callBack,
8116 void *cookie)
8117{
8118 Mutex::Autolock _l(mLock);
8119
8120 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8121 status_t playStatus = NAME_NOT_FOUND;
8122 status_t recStatus = NAME_NOT_FOUND;
8123 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8124 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8125 if (playStatus == NO_ERROR) {
8126 return event;
8127 }
8128 }
8129 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8130 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8131 if (recStatus == NO_ERROR) {
8132 return event;
8133 }
8134 }
8135 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8136 mPendingSyncEvents.add(event);
8137 } else {
8138 ALOGV("createSyncEvent() invalid event %d", event->type());
8139 event.clear();
8140 }
8141 return event;
8142}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008143
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144// ----------------------------------------------------------------------------
8145// Effect management
8146// ----------------------------------------------------------------------------
8147
8148
Glenn Kastenf587ba52012-01-26 16:25:10 -08008149status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150{
8151 Mutex::Autolock _l(mLock);
8152 return EffectQueryNumberEffects(numEffects);
8153}
8154
Glenn Kastenf587ba52012-01-26 16:25:10 -08008155status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156{
8157 Mutex::Autolock _l(mLock);
8158 return EffectQueryEffect(index, descriptor);
8159}
8160
Glenn Kasten5e92a782012-01-30 07:40:52 -08008161status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008162 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163{
8164 Mutex::Autolock _l(mLock);
8165 return EffectGetDescriptor(pUuid, descriptor);
8166}
8167
8168
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8170 effect_descriptor_t *pDesc,
8171 const sp<IEffectClient>& effectClient,
8172 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008173 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 int sessionId,
8175 status_t *status,
8176 int *id,
8177 int *enabled)
8178{
8179 status_t lStatus = NO_ERROR;
8180 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008182
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008183 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008184 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185
8186 if (pDesc == NULL) {
8187 lStatus = BAD_VALUE;
8188 goto Exit;
8189 }
8190
Eric Laurent84e9a102010-09-23 16:10:16 -07008191 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008192 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008193 lStatus = PERMISSION_DENIED;
8194 goto Exit;
8195 }
8196
Dima Zavinfce7a472011-04-19 22:30:36 -07008197 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008198 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008199 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008200 lStatus = PERMISSION_DENIED;
8201 goto Exit;
8202 }
8203
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008204 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008205 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008206 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008207 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008208 lStatus = BAD_VALUE;
8209 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008210 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008211 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008212 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008213 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008214 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008215 }
8216 }
8217
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 {
8219 Mutex::Autolock _l(mLock);
8220
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221
8222 if (!EffectIsNullUuid(&pDesc->uuid)) {
8223 // if uuid is specified, request effect descriptor
8224 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8225 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008226 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008227 goto Exit;
8228 }
8229 } else {
8230 // if uuid is not specified, look for an available implementation
8231 // of the required type in effect factory
8232 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008233 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008234 lStatus = BAD_VALUE;
8235 goto Exit;
8236 }
8237 uint32_t numEffects = 0;
8238 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008239 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008240 bool found = false;
8241
8242 lStatus = EffectQueryNumberEffects(&numEffects);
8243 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008244 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 goto Exit;
8246 }
8247 for (uint32_t i = 0; i < numEffects; i++) {
8248 lStatus = EffectQueryEffect(i, &desc);
8249 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008250 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008251 continue;
8252 }
8253 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8254 // If matching type found save effect descriptor. If the session is
8255 // 0 and the effect is not auxiliary, continue enumeration in case
8256 // an auxiliary version of this effect type is available
8257 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008258 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008259 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008260 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8261 break;
8262 }
8263 }
8264 }
8265 if (!found) {
8266 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008267 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268 goto Exit;
8269 }
8270 // For same effect type, chose auxiliary version over insert version if
8271 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008272 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008273 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008274 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008275 }
8276 }
8277
8278 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008279 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8281 lStatus = INVALID_OPERATION;
8282 goto Exit;
8283 }
8284
Eric Laurent59255e42011-07-27 19:49:51 -07008285 // check recording permission for visualizer
8286 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8287 !recordingAllowed()) {
8288 lStatus = PERMISSION_DENIED;
8289 goto Exit;
8290 }
8291
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008293 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294
8295 // If output is not specified try to find a matching audio session ID in one of the
8296 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008297 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8298 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008299 // Note: io is never 0 when creating an effect on an input
8300 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008301 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008302 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8303 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008304 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008305 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008307 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008308 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008309 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8310 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8311 io = mRecordThreads.keyAt(i);
8312 break;
8313 }
8314 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008315 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008316 // If no output thread contains the requested session ID, default to
8317 // first output. The effect chain will be moved to the correct output
8318 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008319 if (io == 0 && mPlaybackThreads.size()) {
8320 io = mPlaybackThreads.keyAt(0);
8321 }
Steve Block3856b092011-10-20 11:56:00 +01008322 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008323 }
8324 ThreadBase *thread = checkRecordThread_l(io);
8325 if (thread == NULL) {
8326 thread = checkPlaybackThread_l(io);
8327 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008328 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008329 lStatus = BAD_VALUE;
8330 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008332 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008333
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008334 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008336 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008337 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8338 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 if (handle != 0 && id != NULL) {
8340 *id = handle->id();
8341 }
8342 }
8343
8344Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008345 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346 *status = lStatus;
8347 }
8348 return handle;
8349}
8350
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008351status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8352 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008353{
Steve Block3856b092011-10-20 11:56:00 +01008354 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008355 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008356 Mutex::Autolock _l(mLock);
8357 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008358 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008359 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008360 }
Eric Laurentde070132010-07-13 04:45:46 -07008361 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8362 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008363 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008364 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 }
Eric Laurentde070132010-07-13 04:45:46 -07008366 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8367 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008368 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008369 return BAD_VALUE;
8370 }
8371
8372 Mutex::Autolock _dl(dstThread->mLock);
8373 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008374 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008375
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 return NO_ERROR;
8377}
8378
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008379// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008380status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008381 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008382 AudioFlinger::PlaybackThread *dstThread,
8383 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008384{
Steve Block3856b092011-10-20 11:56:00 +01008385 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008386 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008387
Eric Laurent59255e42011-07-27 19:49:51 -07008388 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008389 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008390 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008391 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008392 return INVALID_OPERATION;
8393 }
8394
Eric Laurent39e94f82010-07-28 01:32:47 -07008395 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008396 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008397 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008398 // removed.
8399 srcThread->removeEffectChain_l(chain);
8400
8401 // transfer all effects one by one so that new effect chain is created on new thread with
8402 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008403 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008404 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008405 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008406 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8407 while (effect != 0) {
8408 srcThread->removeEffect_l(effect);
8409 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008410 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8411 if (effect->state() == EffectModule::ACTIVE ||
8412 effect->state() == EffectModule::STOPPING) {
8413 effect->start();
8414 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008415 // if the move request is not received from audio policy manager, the effect must be
8416 // re-registered with the new strategy and output
8417 if (dstChain == 0) {
8418 dstChain = effect->chain().promote();
8419 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008420 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008421 srcThread->addEffect_l(effect);
8422 return NO_INIT;
8423 }
8424 strategy = dstChain->strategy();
8425 }
8426 if (reRegister) {
8427 AudioSystem::unregisterEffect(effect->id());
8428 AudioSystem::registerEffect(&effect->desc(),
8429 dstOutput,
8430 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008431 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008432 effect->id());
8433 }
Eric Laurentde070132010-07-13 04:45:46 -07008434 effect = chain->getEffectFromId_l(0);
8435 }
8436
8437 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008438}
8439
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008440
Mathias Agopian65ab4712010-07-14 17:59:35 -07008441// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008442sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008443 const sp<AudioFlinger::Client>& client,
8444 const sp<IEffectClient>& effectClient,
8445 int32_t priority,
8446 int sessionId,
8447 effect_descriptor_t *desc,
8448 int *enabled,
8449 status_t *status
8450 )
8451{
8452 sp<EffectModule> effect;
8453 sp<EffectHandle> handle;
8454 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008456 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457 bool effectCreated = false;
8458 bool effectRegistered = false;
8459
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008460 lStatus = initCheck();
8461 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008462 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008463 goto Exit;
8464 }
8465
8466 // Do not allow effects with session ID 0 on direct output or duplicating threads
8467 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008468 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008469 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008470 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008471 lStatus = BAD_VALUE;
8472 goto Exit;
8473 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008474 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008475 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008476 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008477 desc->name, desc->flags, mType);
8478 lStatus = BAD_VALUE;
8479 goto Exit;
8480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008481
Steve Block3856b092011-10-20 11:56:00 +01008482 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483
8484 { // scope for mLock
8485 Mutex::Autolock _l(mLock);
8486
8487 // check for existing effect chain with the requested audio session
8488 chain = getEffectChain_l(sessionId);
8489 if (chain == 0) {
8490 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008491 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492 chain = new EffectChain(this, sessionId);
8493 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008494 chain->setStrategy(getStrategyForSession_l(sessionId));
8495 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008496#ifdef QCOM_HARDWARE
8497 if(sessionId == mAudioFlinger->mLPASessionId) {
8498 // Clear reference to previous effect chain if any
8499 if(mAudioFlinger->mLPAEffectChain.get()) {
8500 mAudioFlinger->mLPAEffectChain.clear();
8501 }
8502 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8503 mAudioFlinger->mLPAEffectChain = chain;
8504 chain->setLPAFlag(true);
8505 // For LPA, the volume will be applied in DSP. No need for volume
8506 // control in the Effect chain, so setting it to unity.
8507 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8508 chain->setVolume_l(&volume,&volume);
8509 }
8510#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008512 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 }
8514
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008515 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516
8517 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008518 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008519 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008520 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521 if (lStatus != NO_ERROR) {
8522 goto Exit;
8523 }
8524 effectRegistered = true;
8525 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008526 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008527 lStatus = effect->status();
8528 if (lStatus != NO_ERROR) {
8529 goto Exit;
8530 }
Eric Laurentcab11242010-07-15 12:50:15 -07008531 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 if (lStatus != NO_ERROR) {
8533 goto Exit;
8534 }
8535 effectCreated = true;
8536
Eric Laurentf1c04f92012-08-28 14:26:53 -07008537 effect->setDevice(mOutDevice);
8538 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008539 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008540 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008541#ifdef QCOM_HARDWARE
8542 if(chain == mAudioFlinger->mLPAEffectChain) {
8543 effect->setLPAFlag(true);
8544 }
8545#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546 }
8547 // create effect handle and connect it to effect module
8548 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008549 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008550 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 *enabled = (int)effect->isEnabled();
8552 }
8553 }
8554
8555Exit:
8556 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008557 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008558 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008559 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 }
8561 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008562 AudioSystem::unregisterEffect(effect->id());
8563 }
8564 if (chainCreated) {
8565 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 }
8567 handle.clear();
8568 }
8569
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008570 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 *status = lStatus;
8572 }
8573 return handle;
8574}
8575
Eric Laurent717e1282012-06-29 16:36:52 -07008576sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8577{
8578 Mutex::Autolock _l(mLock);
8579 return getEffect_l(sessionId, effectId);
8580}
8581
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008582sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8583{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008584 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008585 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008586}
8587
Eric Laurentde070132010-07-13 04:45:46 -07008588// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8589// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008590status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008591{
8592 // check for existing effect chain with the requested audio session
8593 int sessionId = effect->sessionId();
8594 sp<EffectChain> chain = getEffectChain_l(sessionId);
8595 bool chainCreated = false;
8596
8597 if (chain == 0) {
8598 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008599 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008600 chain = new EffectChain(this, sessionId);
8601 addEffectChain_l(chain);
8602 chain->setStrategy(getStrategyForSession_l(sessionId));
8603 chainCreated = true;
8604 }
Steve Block3856b092011-10-20 11:56:00 +01008605 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008606
8607 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008608 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008609 this, effect->desc().name, chain.get());
8610 return BAD_VALUE;
8611 }
8612
8613 status_t status = chain->addEffect_l(effect);
8614 if (status != NO_ERROR) {
8615 if (chainCreated) {
8616 removeEffectChain_l(chain);
8617 }
8618 return status;
8619 }
8620
Eric Laurentf1c04f92012-08-28 14:26:53 -07008621 effect->setDevice(mOutDevice);
8622 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008623 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008624 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008625 return NO_ERROR;
8626}
8627
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008628void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008629
Steve Block3856b092011-10-20 11:56:00 +01008630 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008632 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8633 detachAuxEffect_l(effect->id());
8634 }
8635
8636 sp<EffectChain> chain = effect->chain().promote();
8637 if (chain != 0) {
8638 // remove effect chain if removing last effect
8639 if (chain->removeEffect_l(effect) == 0) {
8640 removeEffectChain_l(chain);
8641 }
8642 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008643 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008644 }
8645}
8646
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008647void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008648 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008649{
8650 effectChains = mEffectChains;
8651 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008652#ifdef QCOM_HARDWARE
8653 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8654#endif
8655 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008656 }
8657}
8658
8659void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008660 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008661{
8662 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008663#ifdef QCOM_HARDWARE
8664 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8665#endif
8666 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008667 }
8668}
8669
8670sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8671{
8672 Mutex::Autolock _l(mLock);
8673 return getEffectChain_l(sessionId);
8674}
8675
Glenn Kasten106e8a42012-08-02 13:37:12 -07008676sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008677{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008678 size_t size = mEffectChains.size();
8679 for (size_t i = 0; i < size; i++) {
8680 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008681 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008682 }
8683 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008684 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008685}
8686
Glenn Kastenf78aee72012-01-04 11:00:47 -08008687void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008688{
8689 Mutex::Autolock _l(mLock);
8690 size_t size = mEffectChains.size();
8691 for (size_t i = 0; i < size; i++) {
8692 mEffectChains[i]->setMode_l(mode);
8693 }
8694}
8695
8696void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008697 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008698 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008699
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008701 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008702 // delete the effect module if removing last handle on it
8703 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008704 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008705 removeEffect_l(effect);
8706 AudioSystem::unregisterEffect(effect->id());
8707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708 }
8709}
8710
8711status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8712{
8713 int session = chain->sessionId();
8714 int16_t *buffer = mMixBuffer;
8715 bool ownsBuffer = false;
8716
Steve Block3856b092011-10-20 11:56:00 +01008717 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718 if (session > 0) {
8719 // Only one effect chain can be present in direct output thread and it uses
8720 // the mix buffer as input
8721 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008722 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723 buffer = new int16_t[numSamples];
8724 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008725 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 ownsBuffer = true;
8727 }
8728
8729 // Attach all tracks with same session ID to this chain.
8730 for (size_t i = 0; i < mTracks.size(); ++i) {
8731 sp<Track> track = mTracks[i];
8732 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008733 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008734 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008735 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008736 }
8737 }
8738
8739 // indicate all active tracks in the chain
8740 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8741 sp<Track> track = mActiveTracks[i].promote();
8742 if (track == 0) continue;
8743 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008744 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008745 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746 }
8747 }
8748 }
8749
8750 chain->setInBuffer(buffer, ownsBuffer);
8751 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008752 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008753 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008754 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8755 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008757 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8758 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008759 // Effect chain for other sessions are inserted at beginning of effect
8760 // chains list to be processed before output mix effects. Relative order between other
8761 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762 size_t size = mEffectChains.size();
8763 size_t i = 0;
8764 for (i = 0; i < size; i++) {
8765 if (mEffectChains[i]->sessionId() < session) break;
8766 }
8767 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008768 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008769
8770 return NO_ERROR;
8771}
8772
8773size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8774{
8775 int session = chain->sessionId();
8776
Steve Block3856b092011-10-20 11:56:00 +01008777 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008778
8779 for (size_t i = 0; i < mEffectChains.size(); i++) {
8780 if (chain == mEffectChains[i]) {
8781 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008782 // detach all active tracks from the chain
8783 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8784 sp<Track> track = mActiveTracks[i].promote();
8785 if (track == 0) continue;
8786 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008787 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008788 chain.get(), session);
8789 chain->decActiveTrackCnt();
8790 }
8791 }
8792
Mathias Agopian65ab4712010-07-14 17:59:35 -07008793 // detach all tracks with same session ID from this chain
8794 for (size_t i = 0; i < mTracks.size(); ++i) {
8795 sp<Track> track = mTracks[i];
8796 if (session == track->sessionId()) {
8797 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008798 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799 }
8800 }
Eric Laurentde070132010-07-13 04:45:46 -07008801 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008802 }
8803 }
8804 return mEffectChains.size();
8805}
8806
Eric Laurentde070132010-07-13 04:45:46 -07008807status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8808 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008809{
8810 Mutex::Autolock _l(mLock);
8811 return attachAuxEffect_l(track, EffectId);
8812}
8813
Eric Laurentde070132010-07-13 04:45:46 -07008814status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8815 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816{
8817 status_t status = NO_ERROR;
8818
8819 if (EffectId == 0) {
8820 track->setAuxBuffer(0, NULL);
8821 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008822 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8823 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824 if (effect != 0) {
8825 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8826 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8827 } else {
8828 status = INVALID_OPERATION;
8829 }
8830 } else {
8831 status = BAD_VALUE;
8832 }
8833 }
8834 return status;
8835}
8836
8837void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8838{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008839 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 sp<Track> track = mTracks[i];
8841 if (track->auxEffectId() == effectId) {
8842 attachAuxEffect_l(track, 0);
8843 }
8844 }
8845}
8846
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008847status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8848{
8849 // only one chain per input thread
8850 if (mEffectChains.size() != 0) {
8851 return INVALID_OPERATION;
8852 }
Steve Block3856b092011-10-20 11:56:00 +01008853 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008854
8855 chain->setInBuffer(NULL);
8856 chain->setOutBuffer(NULL);
8857
Eric Laurent59255e42011-07-27 19:49:51 -07008858 checkSuspendOnAddEffectChain_l(chain);
8859
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008860 mEffectChains.add(chain);
8861
8862 return NO_ERROR;
8863}
8864
8865size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8866{
Steve Block3856b092011-10-20 11:56:00 +01008867 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008868 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008869 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8870 chain.get(), mEffectChains.size(), this);
8871 if (mEffectChains.size() == 1) {
8872 mEffectChains.removeAt(0);
8873 }
8874 return 0;
8875}
8876
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877// ----------------------------------------------------------------------------
8878// EffectModule implementation
8879// ----------------------------------------------------------------------------
8880
8881#undef LOG_TAG
8882#define LOG_TAG "AudioFlinger::EffectModule"
8883
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008884AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 const wp<AudioFlinger::EffectChain>& chain,
8886 effect_descriptor_t *desc,
8887 int id,
8888 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008889 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8890 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008891 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008892 // mConfig is set by configure() and not used before then
8893 mEffectInterface(NULL),
8894 mStatus(NO_INIT), mState(IDLE),
8895 // mMaxDisableWaitCnt is set by configure() and not used before then
8896 // mDisableWaitCnt is set by process() and updateState() and not used before then
8897 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08008898#ifdef QCOM_HARDWARE
8899 ,mIsForLPA(false)
8900#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008901{
Steve Block3856b092011-10-20 11:56:00 +01008902 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904
8905 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008906 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008907
8908 if (mStatus != NO_ERROR) {
8909 return;
8910 }
8911 lStatus = init();
8912 if (lStatus < 0) {
8913 mStatus = lStatus;
8914 goto Error;
8915 }
8916
Steve Block3856b092011-10-20 11:56:00 +01008917 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918 return;
8919Error:
8920 EffectRelease(mEffectInterface);
8921 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008922 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008923}
8924
8925AudioFlinger::EffectModule::~EffectModule()
8926{
Steve Block3856b092011-10-20 11:56:00 +01008927 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008929 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8930 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8931 sp<ThreadBase> thread = mThread.promote();
8932 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008933 audio_stream_t *stream = thread->stream();
8934 if (stream != NULL) {
8935 stream->remove_audio_effect(stream, mEffectInterface);
8936 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008937 }
8938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 // release effect engine
8940 EffectRelease(mEffectInterface);
8941 }
8942}
8943
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008944status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945{
8946 status_t status;
8947
8948 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949 int priority = handle->priority();
8950 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008951 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952 size_t i;
8953 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008954 EffectHandle *h = mHandles[i];
8955 if (h == NULL || h->destroyed_l()) continue;
8956 // first non destroyed handle is considered in control
8957 if (controlHandle == NULL)
8958 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959 if (h->priority() <= priority) break;
8960 }
8961 // if inserted in first place, move effect control from previous owner to this handle
8962 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008963 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008964 if (controlHandle != NULL) {
8965 enabled = controlHandle->enabled();
8966 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967 }
Eric Laurent59255e42011-07-27 19:49:51 -07008968 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969 status = NO_ERROR;
8970 } else {
8971 status = ALREADY_EXISTS;
8972 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008973 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974 mHandles.insertAt(handle, i);
8975 return status;
8976}
8977
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008978size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008979{
8980 Mutex::Autolock _l(mLock);
8981 size_t size = mHandles.size();
8982 size_t i;
8983 for (i = 0; i < size; i++) {
8984 if (mHandles[i] == handle) break;
8985 }
8986 if (i == size) {
8987 return size;
8988 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008989 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008990
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008992 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008993 if (i == 0) {
8994 EffectHandle *h = controlHandle_l();
8995 if (h != NULL) {
8996 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997 }
8998 }
8999
Eric Laurentec437d82011-07-26 20:54:46 -07009000 // Prevent calls to process() and other functions on effect interface from now on.
9001 // The effect engine will be released by the destructor when the last strong reference on
9002 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009003 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009004 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009005 }
9006
Eric Laurente65c8912012-07-20 15:57:23 -07009007 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008}
9009
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009010// must be called with EffectModule::mLock held
9011AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009012{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009013 // the first valid handle in the list has control over the module
9014 for (size_t i = 0; i < mHandles.size(); i++) {
9015 EffectHandle *h = mHandles[i];
9016 if (h != NULL && !h->destroyed_l()) {
9017 return h;
9018 }
9019 }
9020
9021 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009022}
9023
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009024size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025{
vivek mehta2192bc92012-12-04 11:46:08 -08009026#ifdef QCOM_HARDWARE
9027 setEnabled(false);
9028#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009029 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 // keep a strong reference on this EffectModule to avoid calling the
9031 // destructor before we exit
9032 sp<EffectModule> keep(this);
9033 {
9034 sp<ThreadBase> thread = mThread.promote();
9035 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009036 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009037 }
9038 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009039 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009040}
9041
9042void AudioFlinger::EffectModule::updateState() {
9043 Mutex::Autolock _l(mLock);
9044
9045 switch (mState) {
9046 case RESTART:
9047 reset_l();
9048 // FALL THROUGH
9049
9050 case STARTING:
9051 // clear auxiliary effect input buffer for next accumulation
9052 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9053 memset(mConfig.inputCfg.buffer.raw,
9054 0,
9055 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9056 }
9057 start_l();
9058 mState = ACTIVE;
9059 break;
9060 case STOPPING:
9061 stop_l();
9062 mDisableWaitCnt = mMaxDisableWaitCnt;
9063 mState = STOPPED;
9064 break;
9065 case STOPPED:
9066 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9067 // turn off sequence.
9068 if (--mDisableWaitCnt == 0) {
9069 reset_l();
9070 mState = IDLE;
9071 }
9072 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009073 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009074 break;
9075 }
9076}
9077
9078void AudioFlinger::EffectModule::process()
9079{
9080 Mutex::Autolock _l(mLock);
9081
Eric Laurentec437d82011-07-26 20:54:46 -07009082 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083 mConfig.inputCfg.buffer.raw == NULL ||
9084 mConfig.outputCfg.buffer.raw == NULL) {
9085 return;
9086 }
9087
Eric Laurent8f45bd72010-08-31 13:50:07 -07009088 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9090 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009091 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009092 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009093 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 }
9095
9096 // do the actual processing in the effect engine
9097 int ret = (*mEffectInterface)->process(mEffectInterface,
9098 &mConfig.inputCfg.buffer,
9099 &mConfig.outputCfg.buffer);
9100
9101 // force transition to IDLE state when engine is ready
9102 if (mState == STOPPED && ret == -ENODATA) {
9103 mDisableWaitCnt = 1;
9104 }
9105
9106 // clear auxiliary effect input buffer for next accumulation
9107 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009108 memset(mConfig.inputCfg.buffer.raw, 0,
9109 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110 }
9111 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009112 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9113 // If an insert effect is idle and input buffer is different from output buffer,
9114 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009116 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009117 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9118 int16_t *in = mConfig.inputCfg.buffer.s16;
9119 int16_t *out = mConfig.outputCfg.buffer.s16;
9120 for (size_t i = 0; i < frameCnt; i++) {
9121 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123 }
9124 }
9125}
9126
9127void AudioFlinger::EffectModule::reset_l()
9128{
9129 if (mEffectInterface == NULL) {
9130 return;
9131 }
9132 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9133}
9134
vivek mehta2192bc92012-12-04 11:46:08 -08009135#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009136status_t AudioFlinger::EffectModule::configure()
9137{
vivek mehta2192bc92012-12-04 11:46:08 -08009138#else
9139status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9140{
9141 uint32_t channels;
9142
9143 // Acquire lock here to make sure that any other thread does not delete
9144 // the effect handle and release the effect module.
9145 Mutex::Autolock _l(mLock);
9146#endif
9147
Mathias Agopian65ab4712010-07-14 17:59:35 -07009148 if (mEffectInterface == NULL) {
9149 return NO_INIT;
9150 }
9151
9152 sp<ThreadBase> thread = mThread.promote();
9153 if (thread == 0) {
9154 return DEAD_OBJECT;
9155 }
9156
9157 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009158 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009159#ifdef QCOM_HARDWARE
9160 mIsForLPA = isForLPA;
9161 if(isForLPA) {
9162 if (channelCount == 1) {
9163 channels = AUDIO_CHANNEL_OUT_MONO;
9164 } else {
9165 channels = AUDIO_CHANNEL_OUT_STEREO;
9166 }
9167 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9168 } else {
9169 if (thread->channelCount() == 1) {
9170 channels = AUDIO_CHANNEL_OUT_MONO;
9171 } else {
9172 channels = AUDIO_CHANNEL_OUT_STEREO;
9173 }
9174 }
9175#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009176
9177 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009178 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009180 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181 }
Glenn Kasten254af182012-07-03 14:59:05 -07009182 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009183 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9184 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009185#ifdef QCOM_HARDWARE
9186 if(isForLPA){
9187 mConfig.inputCfg.samplingRate = sampleRate;
9188 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9189 } else
9190#endif
9191 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9193 mConfig.inputCfg.bufferProvider.cookie = NULL;
9194 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9195 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9196 mConfig.outputCfg.bufferProvider.cookie = NULL;
9197 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9198 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9199 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9200 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009201 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009202 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009203 // - in other sessions:
9204 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9205 // other effect: overwrites output buffer: input buffer == output buffer
9206 // Auxiliary effect:
9207 // accumulates in output buffer: input buffer != output buffer
9208 // Therefore: accumulate <=> input buffer != output buffer
9209 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9210 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9211 } else {
9212 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9213 }
9214 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9215 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009216#ifdef QCOM_HARDWARE
9217 if(isForLPA) {
9218 mConfig.inputCfg.buffer.frameCount = frameCount;
9219 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9220 } else
9221#endif
9222 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009223 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9224
Steve Block3856b092011-10-20 11:56:00 +01009225 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009226 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9227
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009229 uint32_t size = sizeof(int);
9230 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009231 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009232 sizeof(effect_config_t),
9233 &mConfig,
9234 &size,
9235 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236 if (status == 0) {
9237 status = cmdStatus;
9238 }
9239
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009240 if (status == 0 &&
9241 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9242 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9243 effect_param_t *p = (effect_param_t *)buf32;
9244
9245 p->psize = sizeof(uint32_t);
9246 p->vsize = sizeof(uint32_t);
9247 size = sizeof(int);
9248 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9249
9250 uint32_t latency = 0;
9251 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9252 if (pbt != NULL) {
9253 latency = pbt->latency_l();
9254 }
9255
9256 *((int32_t *)p->data + 1)= latency;
9257 (*mEffectInterface)->command(mEffectInterface,
9258 EFFECT_CMD_SET_PARAM,
9259 sizeof(effect_param_t) + 8,
9260 &buf32,
9261 &size,
9262 &cmdStatus);
9263 }
9264
Mathias Agopian65ab4712010-07-14 17:59:35 -07009265 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9266 (1000 * mConfig.outputCfg.buffer.frameCount);
9267
9268 return status;
9269}
9270
9271status_t AudioFlinger::EffectModule::init()
9272{
9273 Mutex::Autolock _l(mLock);
9274 if (mEffectInterface == NULL) {
9275 return NO_INIT;
9276 }
9277 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009278 uint32_t size = sizeof(status_t);
9279 status_t status = (*mEffectInterface)->command(mEffectInterface,
9280 EFFECT_CMD_INIT,
9281 0,
9282 NULL,
9283 &size,
9284 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009285 if (status == 0) {
9286 status = cmdStatus;
9287 }
9288 return status;
9289}
9290
Eric Laurentec35a142011-10-05 17:42:25 -07009291status_t AudioFlinger::EffectModule::start()
9292{
9293 Mutex::Autolock _l(mLock);
9294 return start_l();
9295}
9296
Mathias Agopian65ab4712010-07-14 17:59:35 -07009297status_t AudioFlinger::EffectModule::start_l()
9298{
9299 if (mEffectInterface == NULL) {
9300 return NO_INIT;
9301 }
9302 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009303 uint32_t size = sizeof(status_t);
9304 status_t status = (*mEffectInterface)->command(mEffectInterface,
9305 EFFECT_CMD_ENABLE,
9306 0,
9307 NULL,
9308 &size,
9309 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009310 if (status == 0) {
9311 status = cmdStatus;
9312 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009313 if (status == 0 &&
9314 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9315 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9316 sp<ThreadBase> thread = mThread.promote();
9317 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009318 audio_stream_t *stream = thread->stream();
9319 if (stream != NULL) {
9320 stream->add_audio_effect(stream, mEffectInterface);
9321 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009322 }
9323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009324 return status;
9325}
9326
Eric Laurentec437d82011-07-26 20:54:46 -07009327status_t AudioFlinger::EffectModule::stop()
9328{
9329 Mutex::Autolock _l(mLock);
9330 return stop_l();
9331}
9332
Mathias Agopian65ab4712010-07-14 17:59:35 -07009333status_t AudioFlinger::EffectModule::stop_l()
9334{
9335 if (mEffectInterface == NULL) {
9336 return NO_INIT;
9337 }
9338 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009339 uint32_t size = sizeof(status_t);
9340 status_t status = (*mEffectInterface)->command(mEffectInterface,
9341 EFFECT_CMD_DISABLE,
9342 0,
9343 NULL,
9344 &size,
9345 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346 if (status == 0) {
9347 status = cmdStatus;
9348 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009349 if (status == 0 &&
9350 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9351 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9352 sp<ThreadBase> thread = mThread.promote();
9353 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009354 audio_stream_t *stream = thread->stream();
9355 if (stream != NULL) {
9356 stream->remove_audio_effect(stream, mEffectInterface);
9357 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009358 }
9359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009360 return status;
9361}
9362
Eric Laurent25f43952010-07-28 05:40:18 -07009363status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9364 uint32_t cmdSize,
9365 void *pCmdData,
9366 uint32_t *replySize,
9367 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009368{
9369 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009370// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009371
Eric Laurentec437d82011-07-26 20:54:46 -07009372 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373 return NO_INIT;
9374 }
Eric Laurent25f43952010-07-28 05:40:18 -07009375 status_t status = (*mEffectInterface)->command(mEffectInterface,
9376 cmdCode,
9377 cmdSize,
9378 pCmdData,
9379 replySize,
9380 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009381 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009382 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009384 EffectHandle *h = mHandles[i];
9385 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009386 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9387 }
9388 }
9389 }
9390 return status;
9391}
9392
9393status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9394{
9395 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009396 return setEnabled_l(enabled);
9397}
9398
9399// must be called with EffectModule::mLock held
9400status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9401{
vivek mehta2192bc92012-12-04 11:46:08 -08009402#ifdef QCOM_HARDWARE
9403 bool effectStateChanged = false;
9404#endif
Steve Block3856b092011-10-20 11:56:00 +01009405 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009406
9407 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009408#ifdef QCOM_HARDWARE
9409 effectStateChanged = true;
9410#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009411 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9412 if (enabled && status != NO_ERROR) {
9413 return status;
9414 }
9415
Mathias Agopian65ab4712010-07-14 17:59:35 -07009416 switch (mState) {
9417 // going from disabled to enabled
9418 case IDLE:
9419 mState = STARTING;
9420 break;
9421 case STOPPED:
9422 mState = RESTART;
9423 break;
9424 case STOPPING:
9425 mState = ACTIVE;
9426 break;
9427
9428 // going from enabled to disabled
9429 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009430 mState = STOPPED;
9431 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009432 case STARTING:
9433 mState = IDLE;
9434 break;
9435 case ACTIVE:
9436 mState = STOPPING;
9437 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009438 case DESTROYED:
9439 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009440 }
9441 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009442 EffectHandle *h = mHandles[i];
9443 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009444 h->setEnabled(enabled);
9445 }
9446 }
9447 }
vivek mehta2192bc92012-12-04 11:46:08 -08009448#ifdef QCOM_HARDWARE
9449 /*
9450 Send notification event to LPA Player when an effect for
9451 LPA output is enabled or disabled.
9452 */
9453 if (effectStateChanged && mIsForLPA) {
9454 sp<ThreadBase> thread = mThread.promote();
9455 thread->effectConfigChanged();
9456 }
9457#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009458 return NO_ERROR;
9459}
9460
Glenn Kastenc59c0042012-02-02 14:06:11 -08009461bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009462{
9463 switch (mState) {
9464 case RESTART:
9465 case STARTING:
9466 case ACTIVE:
9467 return true;
9468 case IDLE:
9469 case STOPPING:
9470 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009471 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009472 default:
9473 return false;
9474 }
9475}
9476
Glenn Kastenc59c0042012-02-02 14:06:11 -08009477bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009478{
9479 switch (mState) {
9480 case RESTART:
9481 case ACTIVE:
9482 case STOPPING:
9483 case STOPPED:
9484 return true;
9485 case IDLE:
9486 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009487 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009488 default:
9489 return false;
9490 }
9491}
9492
Mathias Agopian65ab4712010-07-14 17:59:35 -07009493status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9494{
9495 Mutex::Autolock _l(mLock);
9496 status_t status = NO_ERROR;
9497
9498 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9499 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009500 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009501 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9502 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009503 status_t cmdStatus;
9504 uint32_t volume[2];
9505 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009506 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009507 volume[0] = *left;
9508 volume[1] = *right;
9509 if (controller) {
9510 pVolume = volume;
9511 }
Eric Laurent25f43952010-07-28 05:40:18 -07009512 status = (*mEffectInterface)->command(mEffectInterface,
9513 EFFECT_CMD_SET_VOLUME,
9514 size,
9515 volume,
9516 &size,
9517 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009518 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9519 *left = volume[0];
9520 *right = volume[1];
9521 }
9522 }
9523 return status;
9524}
9525
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009526status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009527{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009528 if (device == AUDIO_DEVICE_NONE) {
9529 return NO_ERROR;
9530 }
9531
Mathias Agopian65ab4712010-07-14 17:59:35 -07009532 Mutex::Autolock _l(mLock);
9533 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009534 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009535 status_t cmdStatus;
9536 uint32_t size = sizeof(status_t);
9537 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9538 EFFECT_CMD_SET_INPUT_DEVICE;
9539 status = (*mEffectInterface)->command(mEffectInterface,
9540 cmd,
9541 sizeof(uint32_t),
9542 &device,
9543 &size,
9544 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009545 }
9546 return status;
9547}
9548
Glenn Kastenf78aee72012-01-04 11:00:47 -08009549status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009550{
9551 Mutex::Autolock _l(mLock);
9552 status_t status = NO_ERROR;
9553 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009555 uint32_t size = sizeof(status_t);
9556 status = (*mEffectInterface)->command(mEffectInterface,
9557 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009558 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009559 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009560 &size,
9561 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009562 if (status == NO_ERROR) {
9563 status = cmdStatus;
9564 }
9565 }
9566 return status;
9567}
9568
Eric Laurent57b2dd12012-08-31 17:44:06 -07009569status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9570{
9571 Mutex::Autolock _l(mLock);
9572 status_t status = NO_ERROR;
9573 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9574 uint32_t size = 0;
9575 status = (*mEffectInterface)->command(mEffectInterface,
9576 EFFECT_CMD_SET_AUDIO_SOURCE,
9577 sizeof(audio_source_t),
9578 &source,
9579 &size,
9580 NULL);
9581 }
9582 return status;
9583}
9584
Eric Laurent59255e42011-07-27 19:49:51 -07009585void AudioFlinger::EffectModule::setSuspended(bool suspended)
9586{
9587 Mutex::Autolock _l(mLock);
9588 mSuspended = suspended;
9589}
Glenn Kastena3a85482012-01-04 11:01:11 -08009590
9591bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009592{
9593 Mutex::Autolock _l(mLock);
9594 return mSuspended;
9595}
9596
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009597bool AudioFlinger::EffectModule::purgeHandles()
9598{
9599 bool enabled = false;
9600 Mutex::Autolock _l(mLock);
9601 for (size_t i = 0; i < mHandles.size(); i++) {
9602 EffectHandle *handle = mHandles[i];
9603 if (handle != NULL && !handle->destroyed_l()) {
9604 handle->effect().clear();
9605 if (handle->hasControl()) {
9606 enabled = handle->enabled();
9607 }
9608 }
9609 }
9610 return enabled;
9611}
9612
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009613void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009614{
9615 const size_t SIZE = 256;
9616 char buffer[SIZE];
9617 String8 result;
9618
9619 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9620 result.append(buffer);
9621
9622 bool locked = tryLock(mLock);
9623 // failed to lock - AudioFlinger is probably deadlocked
9624 if (!locked) {
9625 result.append("\t\tCould not lock Fx mutex:\n");
9626 }
9627
9628 result.append("\t\tSession Status State Engine:\n");
9629 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9630 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9631 result.append(buffer);
9632
9633 result.append("\t\tDescriptor:\n");
9634 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9635 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9636 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9637 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9638 result.append(buffer);
9639 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9640 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9641 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9642 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9643 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009644 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009645 mDescriptor.apiVersion,
9646 mDescriptor.flags);
9647 result.append(buffer);
9648 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9649 mDescriptor.name);
9650 result.append(buffer);
9651 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9652 mDescriptor.implementor);
9653 result.append(buffer);
9654
9655 result.append("\t\t- Input configuration:\n");
9656 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9657 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9658 (uint32_t)mConfig.inputCfg.buffer.raw,
9659 mConfig.inputCfg.buffer.frameCount,
9660 mConfig.inputCfg.samplingRate,
9661 mConfig.inputCfg.channels,
9662 mConfig.inputCfg.format);
9663 result.append(buffer);
9664
9665 result.append("\t\t- Output configuration:\n");
9666 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9667 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9668 (uint32_t)mConfig.outputCfg.buffer.raw,
9669 mConfig.outputCfg.buffer.frameCount,
9670 mConfig.outputCfg.samplingRate,
9671 mConfig.outputCfg.channels,
9672 mConfig.outputCfg.format);
9673 result.append(buffer);
9674
9675 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9676 result.append(buffer);
9677 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9678 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009679 EffectHandle *handle = mHandles[i];
9680 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009681 handle->dump(buffer, SIZE);
9682 result.append(buffer);
9683 }
9684 }
9685
9686 result.append("\n");
9687
9688 write(fd, result.string(), result.length());
9689
9690 if (locked) {
9691 mLock.unlock();
9692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009693}
9694
9695// ----------------------------------------------------------------------------
9696// EffectHandle implementation
9697// ----------------------------------------------------------------------------
9698
9699#undef LOG_TAG
9700#define LOG_TAG "AudioFlinger::EffectHandle"
9701
9702AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9703 const sp<AudioFlinger::Client>& client,
9704 const sp<IEffectClient>& effectClient,
9705 int32_t priority)
9706 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009707 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009708 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009709{
Steve Block3856b092011-10-20 11:56:00 +01009710 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009711
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009712 if (client == 0) {
9713 return;
9714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009715 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9716 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9717 if (mCblkMemory != 0) {
9718 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9719
Glenn Kastena0d68332012-01-27 16:47:15 -08009720 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009721 new(mCblk) effect_param_cblk_t();
9722 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009724 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009725 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009726 return;
9727 }
9728}
9729
9730AudioFlinger::EffectHandle::~EffectHandle()
9731{
Steve Block3856b092011-10-20 11:56:00 +01009732 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009733
9734 if (mEffect == 0) {
9735 mDestroyed = true;
9736 return;
9737 }
9738 mEffect->lock();
9739 mDestroyed = true;
9740 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009741 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009742}
9743
9744status_t AudioFlinger::EffectHandle::enable()
9745{
Steve Block3856b092011-10-20 11:56:00 +01009746 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009747 if (!mHasControl) return INVALID_OPERATION;
9748 if (mEffect == 0) return DEAD_OBJECT;
9749
Eric Laurentdb7c0792011-08-10 10:37:50 -07009750 if (mEnabled) {
9751 return NO_ERROR;
9752 }
9753
Eric Laurent59255e42011-07-27 19:49:51 -07009754 mEnabled = true;
9755
9756 sp<ThreadBase> thread = mEffect->thread().promote();
9757 if (thread != 0) {
9758 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9759 }
9760
9761 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9762 if (mEffect->suspended()) {
9763 return NO_ERROR;
9764 }
9765
Eric Laurentdb7c0792011-08-10 10:37:50 -07009766 status_t status = mEffect->setEnabled(true);
9767 if (status != NO_ERROR) {
9768 if (thread != 0) {
9769 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9770 }
9771 mEnabled = false;
9772 }
9773 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009774}
9775
9776status_t AudioFlinger::EffectHandle::disable()
9777{
Steve Block3856b092011-10-20 11:56:00 +01009778 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009779 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009780 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009781
Eric Laurentdb7c0792011-08-10 10:37:50 -07009782 if (!mEnabled) {
9783 return NO_ERROR;
9784 }
Eric Laurent59255e42011-07-27 19:49:51 -07009785 mEnabled = false;
9786
9787 if (mEffect->suspended()) {
9788 return NO_ERROR;
9789 }
9790
9791 status_t status = mEffect->setEnabled(false);
9792
9793 sp<ThreadBase> thread = mEffect->thread().promote();
9794 if (thread != 0) {
9795 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9796 }
9797
9798 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009799}
9800
9801void AudioFlinger::EffectHandle::disconnect()
9802{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009803 disconnect(true);
9804}
9805
Glenn Kasten58123c32012-02-03 10:32:24 -08009806void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009807{
Glenn Kasten58123c32012-02-03 10:32:24 -08009808 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009809 if (mEffect == 0) {
9810 return;
9811 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009812 // restore suspended effects if the disconnected handle was enabled and the last one.
9813 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009814 sp<ThreadBase> thread = mEffect->thread().promote();
9815 if (thread != 0) {
9816 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9817 }
Eric Laurent59255e42011-07-27 19:49:51 -07009818 }
9819
Mathias Agopian65ab4712010-07-14 17:59:35 -07009820 // release sp on module => module destructor can be called now
9821 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009822 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009823 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009824 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009825 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9826 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009827 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009828 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009829 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9830 mClient.clear();
9831 }
9832}
9833
Eric Laurent25f43952010-07-28 05:40:18 -07009834status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9835 uint32_t cmdSize,
9836 void *pCmdData,
9837 uint32_t *replySize,
9838 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009839{
Steve Block3856b092011-10-20 11:56:00 +01009840// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009841// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009842
9843 // only get parameter command is permitted for applications not controlling the effect
9844 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9845 return INVALID_OPERATION;
9846 }
9847 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009848 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009849
9850 // handle commands that are not forwarded transparently to effect engine
9851 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9852 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9853 // no risk to block the whole media server process or mixer threads is we are stuck here
9854 Mutex::Autolock _l(mCblk->lock);
9855 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9856 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9857 mCblk->serverIndex = 0;
9858 mCblk->clientIndex = 0;
9859 return BAD_VALUE;
9860 }
9861 status_t status = NO_ERROR;
9862 while (mCblk->serverIndex < mCblk->clientIndex) {
9863 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009864 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009865 int *p = (int *)(mBuffer + mCblk->serverIndex);
9866 int size = *p++;
9867 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009868 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009869 break;
9870 }
9871 effect_param_t *param = (effect_param_t *)p;
9872 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009873 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009874 mCblk->serverIndex += size;
9875 continue;
9876 }
Eric Laurent25f43952010-07-28 05:40:18 -07009877 uint32_t psize = sizeof(effect_param_t) +
9878 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9879 param->vsize;
9880 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9881 psize,
9882 p,
9883 &rsize,
9884 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009885 // stop at first error encountered
9886 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009887 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009888 *(int *)pReplyData = reply;
9889 break;
9890 } else if (reply != NO_ERROR) {
9891 *(int *)pReplyData = reply;
9892 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009893 }
9894 mCblk->serverIndex += size;
9895 }
9896 mCblk->serverIndex = 0;
9897 mCblk->clientIndex = 0;
9898 return status;
9899 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009900 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009901 return enable();
9902 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009903 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009904 return disable();
9905 }
9906
vivek mehta2192bc92012-12-04 11:46:08 -08009907#ifdef QCOM_HARDWARE
9908 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
9909 if(mEffect->isOnLPA() &&
9910 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
9911 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
9912 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
9913 // Notify Direct track for the change in Effect module
9914 // TODO: check if it is required to send mLPAHandle
9915 ALOGV("Notifying Direct Track for the change in effect config");
9916 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
9917 }
9918#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009919 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9920}
9921
Eric Laurent59255e42011-07-27 19:49:51 -07009922void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009923{
Steve Block3856b092011-10-20 11:56:00 +01009924 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009925
9926 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009927 mEnabled = enabled;
9928
Mathias Agopian65ab4712010-07-14 17:59:35 -07009929 if (signal && mEffectClient != 0) {
9930 mEffectClient->controlStatusChanged(hasControl);
9931 }
9932}
9933
Eric Laurent25f43952010-07-28 05:40:18 -07009934void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9935 uint32_t cmdSize,
9936 void *pCmdData,
9937 uint32_t replySize,
9938 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009939{
9940 if (mEffectClient != 0) {
9941 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9942 }
9943}
9944
9945
9946
9947void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9948{
9949 if (mEffectClient != 0) {
9950 mEffectClient->enableStatusChanged(enabled);
9951 }
9952}
9953
9954status_t AudioFlinger::EffectHandle::onTransact(
9955 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9956{
9957 return BnEffect::onTransact(code, data, reply, flags);
9958}
9959
9960
9961void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9962{
Glenn Kastena0d68332012-01-27 16:47:15 -08009963 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009964
9965 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009966 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009967 mPriority,
9968 mHasControl,
9969 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009970 mCblk ? mCblk->clientIndex : 0,
9971 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009972 );
9973
9974 if (locked) {
9975 mCblk->lock.unlock();
9976 }
9977}
9978
9979#undef LOG_TAG
9980#define LOG_TAG "AudioFlinger::EffectChain"
9981
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009982AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009983 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009984 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009985 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9986 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -08009987#ifdef QCOM_HARDWARE
9988 ,mIsForLPATrack(false)
9989#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009990{
Dima Zavinfce7a472011-04-19 22:30:36 -07009991 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009992 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009993 return;
9994 }
9995 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9996 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009997}
9998
9999AudioFlinger::EffectChain::~EffectChain()
10000{
10001 if (mOwnInBuffer) {
10002 delete mInBuffer;
10003 }
10004
10005}
10006
Eric Laurent59255e42011-07-27 19:49:51 -070010007// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010008sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010009{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010010 size_t size = mEffects.size();
10011
10012 for (size_t i = 0; i < size; i++) {
10013 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010014 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010015 }
10016 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010017 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010018}
10019
Eric Laurent59255e42011-07-27 19:49:51 -070010020// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010021sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010022{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010023 size_t size = mEffects.size();
10024
10025 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010026 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10027 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010028 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010029 }
10030 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010031 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010032}
10033
vivek mehta2192bc92012-12-04 11:46:08 -080010034#ifdef QCOM_HARDWARE
10035sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10036{
10037 sp<EffectModule> effect = NULL;
10038 if(idx < 0 || idx >= mEffects.size()) {
10039 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10040 }
10041 if(mEffects.size() > 0){
10042 effect = mEffects[idx];
10043 }
10044 return effect;
10045}
10046#endif
10047
Eric Laurent59255e42011-07-27 19:49:51 -070010048// getEffectFromType_l() must be called with ThreadBase::mLock held
10049sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10050 const effect_uuid_t *type)
10051{
Eric Laurent59255e42011-07-27 19:49:51 -070010052 size_t size = mEffects.size();
10053
10054 for (size_t i = 0; i < size; i++) {
10055 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010056 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010057 }
10058 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010059 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010060}
10061
Eric Laurent91b14c42012-05-30 12:30:29 -070010062void AudioFlinger::EffectChain::clearInputBuffer()
10063{
10064 Mutex::Autolock _l(mLock);
10065 sp<ThreadBase> thread = mThread.promote();
10066 if (thread == 0) {
10067 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10068 return;
10069 }
10070 clearInputBuffer_l(thread);
10071}
10072
10073// Must be called with EffectChain::mLock locked
10074void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10075{
10076 size_t numSamples = thread->frameCount() * thread->channelCount();
10077 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10078
10079}
10080
Mathias Agopian65ab4712010-07-14 17:59:35 -070010081// Must be called with EffectChain::mLock locked
10082void AudioFlinger::EffectChain::process_l()
10083{
Eric Laurentdac69112010-09-28 14:09:57 -070010084 sp<ThreadBase> thread = mThread.promote();
10085 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010086 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010087 return;
10088 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010089 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10090 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010091 // always process effects unless no more tracks are on the session and the effect tail
10092 // has been rendered
10093 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010094 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010095 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010096
Eric Laurent544fe9b2011-11-11 15:42:52 -080010097 if (!tracksOnSession && mTailBufferCount == 0) {
10098 doProcess = false;
10099 }
10100
10101 if (activeTrackCnt() == 0) {
10102 // if no track is active and the effect tail has not been rendered,
10103 // the input buffer must be cleared here as the mixer process will not do it
10104 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010105 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010106 if (mTailBufferCount > 0) {
10107 mTailBufferCount--;
10108 }
10109 }
10110 }
Eric Laurentdac69112010-09-28 14:09:57 -070010111 }
10112
Mathias Agopian65ab4712010-07-14 17:59:35 -070010113 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010114#ifdef QCOM_HARDWARE
10115 if (doProcess || isForLPATrack()) {
10116#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010117 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010118#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010119 for (size_t i = 0; i < size; i++) {
10120 mEffects[i]->process();
10121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010122 }
10123 for (size_t i = 0; i < size; i++) {
10124 mEffects[i]->updateState();
10125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010126}
10127
Eric Laurentcab11242010-07-15 12:50:15 -070010128// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010129status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010130{
10131 effect_descriptor_t desc = effect->desc();
10132 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10133
10134 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010135 effect->setChain(this);
10136 sp<ThreadBase> thread = mThread.promote();
10137 if (thread == 0) {
10138 return NO_INIT;
10139 }
10140 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010141
10142 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10143 // Auxiliary effects are inserted at the beginning of mEffects vector as
10144 // they are processed first and accumulated in chain input buffer
10145 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010146
Mathias Agopian65ab4712010-07-14 17:59:35 -070010147 // the input buffer for auxiliary effect contains mono samples in
10148 // 32 bit format. This is to avoid saturation in AudoMixer
10149 // accumulation stage. Saturation is done in EffectModule::process() before
10150 // calling the process in effect engine
10151 size_t numSamples = thread->frameCount();
10152 int32_t *buffer = new int32_t[numSamples];
10153 memset(buffer, 0, numSamples * sizeof(int32_t));
10154 effect->setInBuffer((int16_t *)buffer);
10155 // auxiliary effects output samples to chain input buffer for further processing
10156 // by insert effects
10157 effect->setOutBuffer(mInBuffer);
10158 } else {
10159 // Insert effects are inserted at the end of mEffects vector as they are processed
10160 // after track and auxiliary effects.
10161 // Insert effect order as a function of indicated preference:
10162 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10163 // another effect is present
10164 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10165 // last effect claiming first position
10166 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10167 // first effect claiming last position
10168 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10169 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10170 // already present
10171
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010172 size_t size = mEffects.size();
10173 size_t idx_insert = size;
10174 ssize_t idx_insert_first = -1;
10175 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010176
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010177 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010178 effect_descriptor_t d = mEffects[i]->desc();
10179 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10180 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10181 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10182 // check invalid effect chaining combinations
10183 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10184 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010185 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010186 return INVALID_OPERATION;
10187 }
10188 // remember position of first insert effect and by default
10189 // select this as insert position for new effect
10190 if (idx_insert == size) {
10191 idx_insert = i;
10192 }
10193 // remember position of last insert effect claiming
10194 // first position
10195 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10196 idx_insert_first = i;
10197 }
10198 // remember position of first insert effect claiming
10199 // last position
10200 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10201 idx_insert_last == -1) {
10202 idx_insert_last = i;
10203 }
10204 }
10205 }
10206
10207 // modify idx_insert from first position if needed
10208 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10209 if (idx_insert_last != -1) {
10210 idx_insert = idx_insert_last;
10211 } else {
10212 idx_insert = size;
10213 }
10214 } else {
10215 if (idx_insert_first != -1) {
10216 idx_insert = idx_insert_first + 1;
10217 }
10218 }
10219
10220 // always read samples from chain input buffer
10221 effect->setInBuffer(mInBuffer);
10222
10223 // if last effect in the chain, output samples to chain
10224 // output buffer, otherwise to chain input buffer
10225 if (idx_insert == size) {
10226 if (idx_insert != 0) {
10227 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10228 mEffects[idx_insert-1]->configure();
10229 }
10230 effect->setOutBuffer(mOutBuffer);
10231 } else {
10232 effect->setOutBuffer(mInBuffer);
10233 }
10234 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010235
Steve Block3856b092011-10-20 11:56:00 +010010236 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010237 }
10238 effect->configure();
10239 return NO_ERROR;
10240}
10241
Eric Laurentcab11242010-07-15 12:50:15 -070010242// removeEffect_l() must be called with PlaybackThread::mLock held
10243size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010244{
10245 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010246 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010247 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10248
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010249 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010250 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010251 // calling stop here will remove pre-processing effect from the audio HAL.
10252 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10253 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010254 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10255 mEffects[i]->state() == EffectModule::STOPPING) {
10256 mEffects[i]->stop();
10257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010258 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10259 delete[] effect->inBuffer();
10260 } else {
10261 if (i == size - 1 && i != 0) {
10262 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10263 mEffects[i - 1]->configure();
10264 }
10265 }
10266 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010267 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010268 break;
10269 }
10270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010271
10272 return mEffects.size();
10273}
10274
Eric Laurentcab11242010-07-15 12:50:15 -070010275// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010276void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010277{
10278 size_t size = mEffects.size();
10279 for (size_t i = 0; i < size; i++) {
10280 mEffects[i]->setDevice(device);
10281 }
10282}
10283
Eric Laurentcab11242010-07-15 12:50:15 -070010284// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010285void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010286{
10287 size_t size = mEffects.size();
10288 for (size_t i = 0; i < size; i++) {
10289 mEffects[i]->setMode(mode);
10290 }
10291}
10292
Eric Laurent57b2dd12012-08-31 17:44:06 -070010293// setAudioSource_l() must be called with PlaybackThread::mLock held
10294void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10295{
10296 size_t size = mEffects.size();
10297 for (size_t i = 0; i < size; i++) {
10298 mEffects[i]->setAudioSource(source);
10299 }
10300}
10301
Eric Laurentcab11242010-07-15 12:50:15 -070010302// setVolume_l() must be called with PlaybackThread::mLock held
10303bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010304{
10305 uint32_t newLeft = *left;
10306 uint32_t newRight = *right;
10307 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010308 int ctrlIdx = -1;
10309 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010310
Eric Laurentcab11242010-07-15 12:50:15 -070010311 // first update volume controller
10312 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010313 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010314 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10315 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010316 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010317 break;
10318 }
10319 }
10320
10321 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010322 if (hasControl) {
10323 *left = mNewLeftVolume;
10324 *right = mNewRightVolume;
10325 }
10326 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010327 }
10328
10329 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010330 mLeftVolume = newLeft;
10331 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010332
10333 // second get volume update from volume controller
10334 if (ctrlIdx >= 0) {
10335 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010336 mNewLeftVolume = newLeft;
10337 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010338 }
10339 // then indicate volume to all other effects in chain.
10340 // Pass altered volume to effects before volume controller
10341 // and requested volume to effects after controller
10342 uint32_t lVol = newLeft;
10343 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010344
Mathias Agopian65ab4712010-07-14 17:59:35 -070010345 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010346 if ((int)i == ctrlIdx) continue;
10347 // this also works for ctrlIdx == -1 when there is no volume controller
10348 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010349 lVol = *left;
10350 rVol = *right;
10351 }
10352 mEffects[i]->setVolume(&lVol, &rVol, false);
10353 }
10354 *left = newLeft;
10355 *right = newRight;
10356
10357 return hasControl;
10358}
10359
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010360void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010361{
10362 const size_t SIZE = 256;
10363 char buffer[SIZE];
10364 String8 result;
10365
10366 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10367 result.append(buffer);
10368
10369 bool locked = tryLock(mLock);
10370 // failed to lock - AudioFlinger is probably deadlocked
10371 if (!locked) {
10372 result.append("\tCould not lock mutex:\n");
10373 }
10374
Eric Laurentcab11242010-07-15 12:50:15 -070010375 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10376 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010377 mEffects.size(),
10378 (uint32_t)mInBuffer,
10379 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010380 mActiveTrackCnt);
10381 result.append(buffer);
10382 write(fd, result.string(), result.size());
10383
10384 for (size_t i = 0; i < mEffects.size(); ++i) {
10385 sp<EffectModule> effect = mEffects[i];
10386 if (effect != 0) {
10387 effect->dump(fd, args);
10388 }
10389 }
10390
10391 if (locked) {
10392 mLock.unlock();
10393 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010394}
10395
Eric Laurent59255e42011-07-27 19:49:51 -070010396// must be called with ThreadBase::mLock held
10397void AudioFlinger::EffectChain::setEffectSuspended_l(
10398 const effect_uuid_t *type, bool suspend)
10399{
10400 sp<SuspendedEffectDesc> desc;
10401 // use effect type UUID timelow as key as there is no real risk of identical
10402 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010403 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010404 if (suspend) {
10405 if (index >= 0) {
10406 desc = mSuspendedEffects.valueAt(index);
10407 } else {
10408 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010409 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010410 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010411 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010412 }
10413 if (desc->mRefCount++ == 0) {
10414 sp<EffectModule> effect = getEffectIfEnabled(type);
10415 if (effect != 0) {
10416 desc->mEffect = effect;
10417 effect->setSuspended(true);
10418 effect->setEnabled(false);
10419 }
10420 }
10421 } else {
10422 if (index < 0) {
10423 return;
10424 }
10425 desc = mSuspendedEffects.valueAt(index);
10426 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010427 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010428 desc->mRefCount = 1;
10429 }
10430 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010431 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010432 if (desc->mEffect != 0) {
10433 sp<EffectModule> effect = desc->mEffect.promote();
10434 if (effect != 0) {
10435 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010436 effect->lock();
10437 EffectHandle *handle = effect->controlHandle_l();
10438 if (handle != NULL && !handle->destroyed_l()) {
10439 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010440 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010441 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010442 }
10443 desc->mEffect.clear();
10444 }
10445 mSuspendedEffects.removeItemsAt(index);
10446 }
10447 }
10448}
10449
10450// must be called with ThreadBase::mLock held
10451void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10452{
10453 sp<SuspendedEffectDesc> desc;
10454
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010455 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010456 if (suspend) {
10457 if (index >= 0) {
10458 desc = mSuspendedEffects.valueAt(index);
10459 } else {
10460 desc = new SuspendedEffectDesc();
10461 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010462 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010463 }
10464 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010465 Vector< sp<EffectModule> > effects;
10466 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010467 for (size_t i = 0; i < effects.size(); i++) {
10468 setEffectSuspended_l(&effects[i]->desc().type, true);
10469 }
10470 }
10471 } else {
10472 if (index < 0) {
10473 return;
10474 }
10475 desc = mSuspendedEffects.valueAt(index);
10476 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010477 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010478 desc->mRefCount = 1;
10479 }
10480 if (--desc->mRefCount == 0) {
10481 Vector<const effect_uuid_t *> types;
10482 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10483 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10484 continue;
10485 }
10486 types.add(&mSuspendedEffects.valueAt(i)->mType);
10487 }
10488 for (size_t i = 0; i < types.size(); i++) {
10489 setEffectSuspended_l(types[i], false);
10490 }
Steve Block3856b092011-10-20 11:56:00 +010010491 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010492 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10493 }
10494 }
10495}
10496
Eric Laurent6bffdb82011-09-23 08:40:41 -070010497
10498// The volume effect is used for automated tests only
10499#ifndef OPENSL_ES_H_
10500static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10501 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10502const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10503#endif //OPENSL_ES_H_
10504
Eric Laurentdb7c0792011-08-10 10:37:50 -070010505bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10506{
10507 // auxiliary effects and visualizer are never suspended on output mix
10508 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10509 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010510 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10511 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010512 return false;
10513 }
10514 return true;
10515}
10516
Glenn Kastend0539712012-01-30 12:56:03 -080010517void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010518{
Glenn Kastend0539712012-01-30 12:56:03 -080010519 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010520 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010521 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10522 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010523 }
Eric Laurent59255e42011-07-27 19:49:51 -070010524 }
Eric Laurent59255e42011-07-27 19:49:51 -070010525}
10526
10527sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10528 const effect_uuid_t *type)
10529{
Glenn Kasten090f0192012-01-30 13:00:02 -080010530 sp<EffectModule> effect = getEffectFromType_l(type);
10531 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010532}
10533
10534void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10535 bool enabled)
10536{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010537 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010538 if (enabled) {
10539 if (index < 0) {
10540 // if the effect is not suspend check if all effects are suspended
10541 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10542 if (index < 0) {
10543 return;
10544 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010545 if (!isEffectEligibleForSuspend(effect->desc())) {
10546 return;
10547 }
Eric Laurent59255e42011-07-27 19:49:51 -070010548 setEffectSuspended_l(&effect->desc().type, enabled);
10549 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010550 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010551 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010552 return;
10553 }
Eric Laurent59255e42011-07-27 19:49:51 -070010554 }
Steve Block3856b092011-10-20 11:56:00 +010010555 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010556 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010557 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10558 // if effect is requested to suspended but was not yet enabled, supend it now.
10559 if (desc->mEffect == 0) {
10560 desc->mEffect = effect;
10561 effect->setEnabled(false);
10562 effect->setSuspended(true);
10563 }
10564 } else {
10565 if (index < 0) {
10566 return;
10567 }
Steve Block3856b092011-10-20 11:56:00 +010010568 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010569 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010570 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10571 desc->mEffect.clear();
10572 effect->setSuspended(false);
10573 }
10574}
10575
Mathias Agopian65ab4712010-07-14 17:59:35 -070010576#undef LOG_TAG
10577#define LOG_TAG "AudioFlinger"
10578
10579// ----------------------------------------------------------------------------
10580
10581status_t AudioFlinger::onTransact(
10582 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10583{
10584 return BnAudioFlinger::onTransact(code, data, reply, flags);
10585}
10586
Mathias Agopian65ab4712010-07-14 17:59:35 -070010587}; // namespace android