blob: 88da88c03be450691dd9fa139dbc273a618a0d84 [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
Mingming Yin84f109b2012-12-27 17:43:05 -08004** Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
vivek mehta2192bc92012-12-04 11:46:08 -08005**
vivek mehta2192bc92012-12-04 11:46:08 -08006** Not a Contribution, Apache license notifications and license are retained
7** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07008**
9** Licensed under the Apache License, Version 2.0 (the "License");
10** you may not use this file except in compliance with the License.
11** You may obtain a copy of the License at
12**
13** http://www.apache.org/licenses/LICENSE-2.0
14**
15** Unless required by applicable law or agreed to in writing, software
16** distributed under the License is distributed on an "AS IS" BASIS,
17** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18** See the License for the specific language governing permissions and
19** limitations under the License.
20*/
21
22
23#define LOG_TAG "AudioFlinger"
24//#define LOG_NDEBUG 0
25
26#include <math.h>
27#include <signal.h>
28#include <sys/time.h>
29#include <sys/resource.h>
30
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
37#include <utils/String16.h>
38#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070039#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Dima Zavinfce7a472011-04-19 22:30:36 -070041#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080043#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#undef ADD_BATTERY_DATA
46
47#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080048#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080049#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070050#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
52#include <private/media/AudioTrackShared.h>
53#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070054
Dima Zavin64760242011-05-11 14:15:23 -070055#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070056#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
58#include "AudioMixer.h"
59#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080060#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Mathias Agopian65ab4712010-07-14 17:59:35 -070062#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070063#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070064#include <audio_effects/effect_ns.h>
65#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Glenn Kasten3b21c502011-12-15 09:52:39 -080067#include <audio_utils/primitives.h>
68
Eric Laurentfeb0db62011-07-22 09:04:31 -070069#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080070
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080072#ifdef DEBUG_CPU_USAGE
73#include <cpustats/CentralTendencyStatistics.h>
74#include <cpustats/ThreadCpuUsage.h>
75#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070076
John Grossman4ff14ba2012-02-08 16:37:41 -080077#include <common_time/cc_helper.h>
78#include <common_time/local_clock.h>
79
Glenn Kasten58912562012-04-03 10:45:00 -070080#include "FastMixer.h"
81
82// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070083#include <media/nbaio/AudioStreamOutSink.h>
84#include <media/nbaio/MonoPipe.h>
85#include <media/nbaio/MonoPipeReader.h>
86#include <media/nbaio/Pipe.h>
87#include <media/nbaio/PipeReader.h>
88#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070089
Glenn Kasten1dc28b72012-04-24 10:01:03 -070090#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070091
Mathias Agopian65ab4712010-07-14 17:59:35 -070092// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
John Grossman1c345192012-03-27 14:00:17 -070094// Note: the following macro is used for extremely verbose logging message. In
95// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
96// 0; but one side effect of this is to turn all LOGV's as well. Some messages
97// are so verbose that we want to suppress them even when we have ALOG_ASSERT
98// turned on. Do not uncomment the #def below unless you really know what you
99// are doing and want to see all of the extremely verbose messages.
100//#define VERY_VERY_VERBOSE_LOGGING
101#ifdef VERY_VERY_VERBOSE_LOGGING
102#define ALOGVV ALOGV
103#else
104#define ALOGVV(a...) do { } while(0)
105#endif
Eric Laurentde070132010-07-13 04:45:46 -0700106
vivek mehta2192bc92012-12-04 11:46:08 -0800107#ifdef QCOM_HARDWARE
108#define DIRECT_TRACK_EOS 1
Ravishankar Sarawadi20017912013-02-27 18:47:54 +0100109#define DIRECT_TRACK_HW_FAIL 6
vivek mehta2192bc92012-12-04 11:46:08 -0800110static 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;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800258#ifdef QCOM_HARDWARE
259 mA2DPHandle = -1;
260#endif
Dima Zavinfce7a472011-04-19 22:30:36 -0700261
Eric Laurent93575202011-01-18 18:39:02 -0800262 Mutex::Autolock _l(mLock);
263
Dima Zavin799a70e2011-04-18 16:57:27 -0700264 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800265#ifdef QCOM_HARDWARE
266 mLPASessionId = -2; // -2 is invalid session ID
267 mIsEffectConfigChanged = false;
268 mLPAEffectChain = NULL;
269#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800270 char val_str[PROPERTY_VALUE_MAX] = { 0 };
271 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
272 uint32_t int_val;
273 if (1 == sscanf(val_str, "%u", &int_val)) {
274 mStandbyTimeInNsecs = milliseconds(int_val);
275 ALOGI("Using %u mSec as standby time.", int_val);
276 } else {
277 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
278 ALOGI("Using default %u mSec as standby time.",
279 (uint32_t)(mStandbyTimeInNsecs / 1000000));
280 }
281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700282
Eric Laurenta4c5a552012-03-29 10:12:40 -0700283 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700284}
285
286AudioFlinger::~AudioFlinger()
287{
288 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700289 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700290 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700291 }
292 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700293 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700294 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700295 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700296
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800297 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
298 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
300 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301 }
302}
303
Eric Laurenta4c5a552012-03-29 10:12:40 -0700304static const char * const audio_interfaces[] = {
305 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
306 AUDIO_HARDWARE_MODULE_ID_A2DP,
307 AUDIO_HARDWARE_MODULE_ID_USB,
308};
309#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
310
John Grossmanee578c02012-07-23 17:05:46 -0700311AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
312 audio_module_handle_t module,
313 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700314{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700315 // if module is 0, the request comes from an old policy manager and we should load
316 // well known modules
317 if (module == 0) {
318 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
319 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
320 loadHwModule_l(audio_interfaces[i]);
321 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700322 // then try to find a module supporting the requested device.
323 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
324 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
325 audio_hw_device_t *dev = audioHwDevice->hwDevice();
326 if ((dev->get_supported_devices != NULL) &&
327 (dev->get_supported_devices(dev) & devices) == devices)
328 return audioHwDevice;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800329#ifdef ICS_AUDIO_BLOB
330 else if (dev->get_supported_devices == NULL && i != 0 &&
331 devices == 0x80)
332 // Reasonably safe assumption: A non-primary HAL without
333 // get_supported_devices is a locally-built A2DP binary
334 return audioHwDevice;
335#endif
Eric Laurentf1c04f92012-08-28 14:26:53 -0700336 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700337 } else {
338 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700339 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
340 if (audioHwDevice != NULL) {
341 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700342 }
343 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700344
Dima Zavin799a70e2011-04-18 16:57:27 -0700345 return NULL;
346}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700348void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349{
350 const size_t SIZE = 256;
351 char buffer[SIZE];
352 String8 result;
353
354 result.append("Clients:\n");
355 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800356 sp<Client> client = mClients.valueAt(i).promote();
357 if (client != 0) {
358 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
359 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360 }
361 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700362
363 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800364 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700365 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
366 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800367 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700368 result.append(buffer);
369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371}
372
373
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700374void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375{
376 const size_t SIZE = 256;
377 char buffer[SIZE];
378 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800379 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380
John Grossman4ff14ba2012-02-08 16:37:41 -0800381 snprintf(buffer, SIZE, "Hardware status: %d\n"
382 "Standby Time mSec: %u\n",
383 hardwareStatus,
384 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 result.append(buffer);
386 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387}
388
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700389void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390{
391 const size_t SIZE = 256;
392 char buffer[SIZE];
393 String8 result;
394 snprintf(buffer, SIZE, "Permission Denial: "
395 "can't dump AudioFlinger from pid=%d, uid=%d\n",
396 IPCThreadState::self()->getCallingPid(),
397 IPCThreadState::self()->getCallingUid());
398 result.append(buffer);
399 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400}
401
402static bool tryLock(Mutex& mutex)
403{
404 bool locked = false;
405 for (int i = 0; i < kDumpLockRetries; ++i) {
406 if (mutex.tryLock() == NO_ERROR) {
407 locked = true;
408 break;
409 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800410 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 return locked;
413}
414
415status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
416{
Glenn Kasten44deb052012-02-05 18:09:08 -0800417 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418 dumpPermissionDenial(fd, args);
419 } else {
420 // get state of hardware lock
421 bool hardwareLocked = tryLock(mHardwareLock);
422 if (!hardwareLocked) {
423 String8 result(kHardwareLockedString);
424 write(fd, result.string(), result.size());
425 } else {
426 mHardwareLock.unlock();
427 }
428
429 bool locked = tryLock(mLock);
430
431 // failed to lock - AudioFlinger is probably deadlocked
432 if (!locked) {
433 String8 result(kDeadlockedString);
434 write(fd, result.string(), result.size());
435 }
436
437 dumpClients(fd, args);
438 dumpInternals(fd, args);
439
440 // dump playback threads
441 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
442 mPlaybackThreads.valueAt(i)->dump(fd, args);
443 }
444
445 // dump record threads
446 for (size_t i = 0; i < mRecordThreads.size(); i++) {
447 mRecordThreads.valueAt(i)->dump(fd, args);
448 }
449
Dima Zavin799a70e2011-04-18 16:57:27 -0700450 // dump all hardware devs
451 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700452 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700453 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 }
455 if (locked) mLock.unlock();
456 }
457 return NO_ERROR;
458}
459
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800460sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
461{
462 // If pid is already in the mClients wp<> map, then use that entry
463 // (for which promote() is always != 0), otherwise create a new entry and Client.
464 sp<Client> client = mClients.valueFor(pid).promote();
465 if (client == 0) {
466 client = new Client(this, pid);
467 mClients.add(pid, client);
468 }
469
470 return client;
471}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
473// IAudioFlinger interface
474
475
476sp<IAudioTrack> AudioFlinger::createTrack(
477 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800478 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800480 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700481 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800483 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800485 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800486 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 int *sessionId,
488 status_t *status)
489{
490 sp<PlaybackThread::Track> track;
491 sp<TrackHandle> trackHandle;
492 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 status_t lStatus;
494 int lSessionId;
495
Glenn Kasten263709e2012-01-06 08:40:01 -0800496 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
497 // but if someone uses binder directly they could bypass that and cause us to crash
498 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000499 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 lStatus = BAD_VALUE;
501 goto Exit;
502 }
503
504 {
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700507 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000509 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 lStatus = BAD_VALUE;
511 goto Exit;
512 }
513
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800514 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515
Steve Block3856b092011-10-20 11:56:00 +0100516 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700517 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700518 // check if an effect chain with the same session ID is present on another
519 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700520 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700521 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
522 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700523 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700524 if (sessions & PlaybackThread::EFFECT_SESSION) {
525 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700526 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700527 }
Eric Laurentde070132010-07-13 04:45:46 -0700528 }
529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 lSessionId = *sessionId;
531 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700532 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700533 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 if (sessionId != NULL) {
535 *sessionId = lSessionId;
536 }
537 }
Steve Block3856b092011-10-20 11:56:00 +0100538 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539
540 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800541 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700542
543 // move effect chain to this output thread if an effect on same session was waiting
544 // for a track to be created
545 if (lStatus == NO_ERROR && effectThread != NULL) {
546 Mutex::Autolock _dl(thread->mLock);
547 Mutex::Autolock _sl(effectThread->mLock);
548 moveEffectChain_l(lSessionId, effectThread, thread, true);
549 }
Eric Laurenta011e352012-03-29 15:51:43 -0700550
551 // Look for sync events awaiting for a session to be used.
552 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
553 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
554 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700555 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700556 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700557 } else {
558 mPendingSyncEvents[i]->cancel();
559 }
Eric Laurenta011e352012-03-29 15:51:43 -0700560 mPendingSyncEvents.removeAt(i);
561 i--;
562 }
563 }
564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 if (lStatus == NO_ERROR) {
567 trackHandle = new TrackHandle(track);
568 } else {
569 // remove local strong reference to Client before deleting the Track so that the Client
570 // destructor is called by the TrackBase destructor with mLock held
571 client.clear();
572 track.clear();
573 }
574
575Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700576 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 *status = lStatus;
578 }
579 return trackHandle;
580}
581
vivek mehta2192bc92012-12-04 11:46:08 -0800582#ifdef QCOM_HARDWARE
583sp<IDirectTrack> AudioFlinger::createDirectTrack(
584 pid_t pid,
585 uint32_t sampleRate,
586 audio_channel_mask_t channelMask,
587 audio_io_handle_t output,
588 int *sessionId,
589 IDirectTrackClient *client,
590 audio_stream_type_t streamType,
591 status_t *status)
592{
593 *status = NO_ERROR;
594 status_t lStatus = NO_ERROR;
595 sp<IDirectTrack> track = NULL;
596 DirectAudioTrack* directTrack = NULL;
597 Mutex::Autolock _l(mLock);
598
599 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
600 *sessionId, sampleRate, channelMask);
601 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
602 if(desc == NULL) {
603 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
604 lStatus = BAD_VALUE;
605 goto Exit;
606 }
607 desc->mStreamType = streamType;
608 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
609 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
610 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
611 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
612 // Check if the session ID is already associated with a track
613 uint32_t sessions = t->hasAudioSession(*sessionId);
614
615 // check if an effect with same session ID is waiting for a ssession to be created
616 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
617 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
618 // Clear reference to previous effect chain if any
619 t->mLock.lock();
620 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
621 mLPAEffectChain = t->getEffectChain_l(*sessionId);
622 t->mLock.unlock();
623 }
624 }
625 mLPASessionId = *sessionId;
626 if (mLPAEffectChain != NULL) {
627 mLPAEffectChain->setLPAFlag(true);
628 // For LPA, the volume will be applied in DSP. No need for volume
629 // control in the Effect chain, so setting it to unity.
630 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
631 mLPAEffectChain->setVolume_l(&volume,&volume);
632 } else {
633 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
634 }
635 mLPASampleRate = sampleRate;
636 mLPANumChannels = popcount(channelMask);
637 } else {
638 if(sessionId != NULL) {
639 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
640 }
641 }
642 }
643 mLock.unlock();
644 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
645 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
646 mLock.lock();
647 if (directTrack != 0) {
648 track = dynamic_cast<IDirectTrack *>(directTrack);
649 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
650 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
651 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
652 } else {
653 lStatus = BAD_VALUE;
654 }
655Exit:
656 if(lStatus) {
657 if (track != NULL) {
658 track.clear();
659 }
660 *status = lStatus;
661 }
662 return track;
663}
664
665void AudioFlinger::deleteEffectSession()
666{
667 Mutex::Autolock _l(mLock);
668 ALOGV("deleteSession");
669 // -2 is invalid session ID
670 mLPASessionId = -2;
671 if (mLPAEffectChain != NULL) {
672 mLPAEffectChain->setLPAFlag(false);
673 size_t i, numEffects = mLPAEffectChain->getNumEffects();
674 for(i = 0; i < numEffects; i++) {
675 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
676 effect->setInBuffer(mLPAEffectChain->inBuffer());
677 if (i == numEffects-1) {
678 effect->setOutBuffer(mLPAEffectChain->outBuffer());
679 } else {
680 effect->setOutBuffer(mLPAEffectChain->inBuffer());
681 }
682 effect->configure();
683 }
684 mLPAEffectChain.clear();
685 mLPAEffectChain = NULL;
686 }
687}
688
689// ToDo: Should we go ahead with this frameCount?
690#define DEAFULT_FRAME_COUNT 1200
691void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
692{
693 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
694 // This might be the first buffer to apply effects after effect config change
695 // should not skip effects processing
696 mIsEffectConfigChanged = false;
697
698 volatile size_t numEffects = 0;
699 if(mLPAEffectChain != NULL) {
700 numEffects = mLPAEffectChain->getNumEffects();
701 }
702
703 if( numEffects > 0) {
704 size_t i = 0;
705 int16_t *pIn = inBuffer;
706 int16_t *pOut = outBuffer;
707
708 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
709
710 while(frameCount > 0) {
711 if(mLPAEffectChain == NULL) {
712 ALOGV("LPA Effect Chain is removed - No effects processing !!");
713 numEffects = 0;
714 break;
715 }
716 mLPAEffectChain->lock();
717
718 numEffects = mLPAEffectChain->getNumEffects();
719 if(!numEffects) {
720 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
721 mLPAEffectChain->unlock();
722 break;
723 }
724
725 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
726 bool isEffectEnabled = false;
727 for(i = 0; i < numEffects; i++) {
728 // If effect configuration is changed while applying effects do not process further
729 if(mIsEffectConfigChanged) {
730 mLPAEffectChain->unlock();
731 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
732 return;
733 }
734 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
735 if(effect == NULL) {
736 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
737 mLPAEffectChain->unlock();
738 return;
739 }
740 if(i == 0) {
741 // For the first set input and output buffers different
742 isEffectEnabled = effect->isProcessEnabled();
743 effect->setInBuffer(pIn);
744 effect->setOutBuffer(pOut);
745 } else {
746 // For the remaining use previous effect's output buffer as input buffer
747 effect->setInBuffer(pOut);
748 effect->setOutBuffer(pOut);
749 }
750 // true indicates that it is being applied on LPA output
751 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
752 }
753
754 if(isEffectEnabled) {
755 // Clear the output buffer
756 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
757 } else {
758 // Copy input buffer content to the output buffer
759 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
760 }
761
762 mLPAEffectChain->process_l();
763
764 mLPAEffectChain->unlock();
765
766 // Update input and output buffer pointers
767 pIn += (outFrameCount * mLPANumChannels);
768 pOut += (outFrameCount * mLPANumChannels);
769 frameCount -= outFrameCount;
770 }
771 }
772
773 if (!numEffects) {
774 ALOGV("applyEffectsOn: There are no effects to be applied");
775 if(inBuffer != outBuffer) {
776 // No effect applied so just copy input buffer to output buffer
777 memcpy(outBuffer, inBuffer, size);
778 }
779 }
780}
781#endif
782
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800783uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784{
785 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800786#ifdef QCOM_HARDWARE
787 if (!mDirectAudioTracks.isEmpty()) {
788 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
789 if(desc != NULL) {
790 return desc->stream->common.get_sample_rate(&desc->stream->common);
791 }
792 }
793#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 PlaybackThread *thread = checkPlaybackThread_l(output);
795 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000796 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 return 0;
798 }
799 return thread->sampleRate();
800}
801
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800802int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803{
804 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800805#ifdef QCOM_HARDWARE
806 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
807 if(desc != NULL) {
808 return desc->stream->common.get_channels(&desc->stream->common);
809 }
810#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 PlaybackThread *thread = checkPlaybackThread_l(output);
812 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000813 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return 0;
815 }
816 return thread->channelCount();
817}
818
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800819audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
821 Mutex::Autolock _l(mLock);
822 PlaybackThread *thread = checkPlaybackThread_l(output);
823 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000824 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800825 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 }
827 return thread->format();
828}
829
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800830size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
832 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800833#ifdef QCOM_HARDWARE
834 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
835 if(desc != NULL) {
836 return desc->stream->common.get_buffer_size(&desc->stream->common);
837 }
838#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 PlaybackThread *thread = checkPlaybackThread_l(output);
840 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000841 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return 0;
843 }
Glenn Kasten58912562012-04-03 10:45:00 -0700844 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
845 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 return thread->frameCount();
847}
848
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800849uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
851 Mutex::Autolock _l(mLock);
852 PlaybackThread *thread = checkPlaybackThread_l(output);
853 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000854 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855 return 0;
856 }
857 return thread->latency();
858}
859
860status_t AudioFlinger::setMasterVolume(float value)
861{
Eric Laurenta1884f92011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
Dorian Snyderf32d5702013-03-01 14:25:46 -0800872#ifdef QCOM_HARDWARE
873 mA2DPHandle = -1;
874#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -0700875 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700876 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700877
John Grossmanee578c02012-07-23 17:05:46 -0700878 // Set master volume in the HALs which support it.
879 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
880 AutoMutex lock(mHardwareLock);
881 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800882
John Grossmanee578c02012-07-23 17:05:46 -0700883 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
884 if (dev->canSetMasterVolume()) {
885 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800886 }
John Grossmanee578c02012-07-23 17:05:46 -0700887 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889
John Grossmanee578c02012-07-23 17:05:46 -0700890 // Now set the master volume in each playback thread. Playback threads
891 // assigned to HALs which do not have master volume support will apply
892 // master volume during the mix operation. Threads with HALs which do
893 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800894 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700895 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896
897 return NO_ERROR;
898}
899
Glenn Kastenf78aee72012-01-04 11:00:47 -0800900status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901{
Eric Laurenta1884f92011-08-23 08:25:03 -0700902 status_t ret = initCheck();
903 if (ret != NO_ERROR) {
904 return ret;
905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906
907 // check calling permissions
908 if (!settingsAllowed()) {
909 return PERMISSION_DENIED;
910 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800911 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000912 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 return BAD_VALUE;
914 }
915
916 { // scope for the lock
917 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700918 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700920 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 mHardwareStatus = AUDIO_HW_IDLE;
922 }
923
924 if (NO_ERROR == ret) {
925 Mutex::Autolock _l(mLock);
926 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800927 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700928 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 }
930
931 return ret;
932}
933
934status_t AudioFlinger::setMicMute(bool state)
935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return ret;
939 }
940
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 // check calling permissions
942 if (!settingsAllowed()) {
943 return PERMISSION_DENIED;
944 }
945
946 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700947 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700949 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 mHardwareStatus = AUDIO_HW_IDLE;
951 return ret;
952}
953
954bool AudioFlinger::getMicMute() const
955{
Eric Laurenta1884f92011-08-23 08:25:03 -0700956 status_t ret = initCheck();
957 if (ret != NO_ERROR) {
958 return false;
959 }
960
Dima Zavinfce7a472011-04-19 22:30:36 -0700961 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800962 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700963 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700965 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 mHardwareStatus = AUDIO_HW_IDLE;
967 return state;
968}
969
970status_t AudioFlinger::setMasterMute(bool muted)
971{
John Grossmand8f178d2012-07-20 14:51:35 -0700972 status_t ret = initCheck();
973 if (ret != NO_ERROR) {
974 return ret;
975 }
976
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 // check calling permissions
978 if (!settingsAllowed()) {
979 return PERMISSION_DENIED;
980 }
981
John Grossmanee578c02012-07-23 17:05:46 -0700982 Mutex::Autolock _l(mLock);
983 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700984
John Grossmanee578c02012-07-23 17:05:46 -0700985 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100986#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700987 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
988 AutoMutex lock(mHardwareLock);
989 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700990
John Grossmanee578c02012-07-23 17:05:46 -0700991 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
992 if (dev->canSetMasterMute()) {
993 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700994 }
John Grossmanee578c02012-07-23 17:05:46 -0700995 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700996 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100997#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700998
John Grossmanee578c02012-07-23 17:05:46 -0700999 // Now set the master mute in each playback thread. Playback threads
1000 // assigned to HALs which do not have master mute support will apply master
1001 // mute during the mix operation. Threads with HALs which do support master
1002 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001003 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -07001004 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005
1006 return NO_ERROR;
1007}
1008
1009float AudioFlinger::masterVolume() const
1010{
Glenn Kasten98067102011-12-13 11:47:54 -08001011 Mutex::Autolock _l(mLock);
1012 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
1015bool AudioFlinger::masterMute() const
1016{
Glenn Kasten98067102011-12-13 11:47:54 -08001017 Mutex::Autolock _l(mLock);
1018 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019}
1020
John Grossman4ff14ba2012-02-08 16:37:41 -08001021float AudioFlinger::masterVolume_l() const
1022{
John Grossman4ff14ba2012-02-08 16:37:41 -08001023 return mMasterVolume;
1024}
1025
John Grossmand8f178d2012-07-20 14:51:35 -07001026bool AudioFlinger::masterMute_l() const
1027{
John Grossmanee578c02012-07-23 17:05:46 -07001028 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001029}
1030
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001031status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1032 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033{
1034 // check calling permissions
1035 if (!settingsAllowed()) {
1036 return PERMISSION_DENIED;
1037 }
1038
Glenn Kasten263709e2012-01-06 08:40:01 -08001039 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001040 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 return BAD_VALUE;
1042 }
1043
1044 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001045#ifdef QCOM_HARDWARE
1046 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1047 AudioSessionDescriptor *desc = NULL;
1048 if (!mDirectAudioTracks.isEmpty()) {
1049 desc = mDirectAudioTracks.valueFor(output);
1050 if (desc != NULL) {
1051 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1052 if (desc->mStreamType == stream) {
1053 mStreamTypes[stream].volume = value;
Dorian Snyderf32d5702013-03-01 14:25:46 -08001054 desc->mVolumeScale = value;
vivek mehta2192bc92012-12-04 11:46:08 -08001055 desc->stream->set_volume(desc->stream,
1056 desc->mVolumeLeft * mStreamTypes[stream].volume,
1057 desc->mVolumeRight* mStreamTypes[stream].volume);
1058 return NO_ERROR;
1059 }
1060 }
1061 }
1062#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 PlaybackThread *thread = NULL;
1064 if (output) {
1065 thread = checkPlaybackThread_l(output);
1066 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001067#ifdef QCOM_HARDWARE
1068 if (desc != NULL) {
1069 return NO_ERROR;
1070 }
1071#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 return BAD_VALUE;
1073 }
vivek mehta2192bc92012-12-04 11:46:08 -08001074
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
1076
1077 mStreamTypes[stream].volume = value;
1078
1079 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001080 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001081 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 }
1083 } else {
1084 thread->setStreamVolume(stream, value);
1085 }
1086
1087 return NO_ERROR;
1088}
1089
Glenn Kastenfff6d712012-01-12 16:38:12 -08001090status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 // check calling permissions
1093 if (!settingsAllowed()) {
1094 return PERMISSION_DENIED;
1095 }
1096
Glenn Kasten263709e2012-01-06 08:40:01 -08001097 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001098 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001099 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 return BAD_VALUE;
1101 }
1102
Eric Laurent93575202011-01-18 18:39:02 -08001103 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 mStreamTypes[stream].mute = muted;
1105 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001106 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107
1108 return NO_ERROR;
1109}
1110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001111float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
Glenn Kasten263709e2012-01-06 08:40:01 -08001113 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 return 0.0f;
1115 }
1116
1117 AutoMutex lock(mLock);
1118 float volume;
1119 if (output) {
1120 PlaybackThread *thread = checkPlaybackThread_l(output);
1121 if (thread == NULL) {
1122 return 0.0f;
1123 }
1124 volume = thread->streamVolume(stream);
1125 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001126 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
1128
1129 return volume;
1130}
1131
Glenn Kastenfff6d712012-01-12 16:38:12 -08001132bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133{
Glenn Kasten263709e2012-01-06 08:40:01 -08001134 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 return true;
1136 }
1137
Glenn Kasten6637baa2012-01-09 09:40:36 -08001138 AutoMutex lock(mLock);
1139 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140}
1141
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001142status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001144 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1146 // check calling permissions
1147 if (!settingsAllowed()) {
1148 return PERMISSION_DENIED;
1149 }
1150
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 // ioHandle == 0 means the parameters are global to the audio hardware interface
1152 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001153 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001154 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001155 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001156 AutoMutex lock(mHardwareLock);
1157 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1158 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1159 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1160 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1161 final_result = result ?: final_result;
1162 }
1163 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001164 }
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001165#ifdef QCOM_HARDWARE
1166 AudioParameter param = AudioParameter(keyValuePairs);
1167 String8 value, key;
1168 int i = 0;
1169
1170 key = String8(AudioParameter::keyADSPStatus);
1171 if (param.get(key, value) == NO_ERROR) {
1172 ALOGV("Set keyADSPStatus:%s", value.string());
1173 if (value == "ONLINE" || value == "OFFLINE") {
1174 if (!mDirectAudioTracks.isEmpty()) {
1175 for (i=0; i < mDirectAudioTracks.size(); i++) {
1176 mDirectAudioTracks.valueAt(i)->stream->common.set_parameters(
1177 &mDirectAudioTracks.valueAt(i)->stream->common, keyValuePairs.string());
1178 }
1179 }
1180 }
1181 }
1182#else
Eric Laurent59bd0da2011-08-01 09:52:20 -07001183 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1184 AudioParameter param = AudioParameter(keyValuePairs);
1185 String8 value;
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001186#endif
1187
Eric Laurent59bd0da2011-08-01 09:52:20 -07001188 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001189 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1190 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001191 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1192 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001193 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001194 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1195 // collect all of the thread's session IDs
1196 KeyedVector<int, bool> ids = thread->sessionIds();
1197 // suspend effects associated with those session IDs
1198 for (size_t j = 0; j < ids.size(); ++j) {
1199 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001200 thread->setEffectSuspended(FX_IID_AEC,
1201 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001202 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001203 thread->setEffectSuspended(FX_IID_NS,
1204 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001205 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001206 }
1207 }
Eric Laurentbee53372011-08-29 12:42:48 -07001208 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001209 }
1210 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001211 String8 screenState;
1212 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1213 bool isOff = screenState == "off";
1214 if (isOff != (gScreenState & 1)) {
1215 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1216 }
1217 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001218 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 }
1220
vivek mehta2192bc92012-12-04 11:46:08 -08001221#ifdef QCOM_HARDWARE
1222 AudioSessionDescriptor *desc = NULL;
1223 if (!mDirectAudioTracks.isEmpty()) {
1224 desc = mDirectAudioTracks.valueFor(ioHandle);
1225 if (desc != NULL) {
1226 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1227 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
Mingming Yin9b3dd172013-01-10 18:42:38 -08001228 AudioParameter param = AudioParameter(keyValuePairs);
1229 String8 key = String8(AudioParameter::keyRouting);
1230 int device;
1231 if (param.getInt(key, device) == NO_ERROR) {
1232 if(mLPAEffectChain != NULL){
1233 mLPAEffectChain->setDevice_l(device);
1234 audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1235 }
1236 }
vivek mehta2192bc92012-12-04 11:46:08 -08001237 }
1238 }
1239#endif
1240
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1242 // and the thread is exited once the lock is released
1243 sp<ThreadBase> thread;
1244 {
1245 Mutex::Autolock _l(mLock);
1246 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001247 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001249 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001250 // indicate output device change to all input threads for pre processing
1251 AudioParameter param = AudioParameter(keyValuePairs);
1252 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001253 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1254 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001255 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1256 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001257 for (size_t i = 0; i < recordThreads.size(); i++) {
1258 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001259 }
1260 }
vivek mehta2192bc92012-12-04 11:46:08 -08001261 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 }
vivek mehta2192bc92012-12-04 11:46:08 -08001263 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001265 if (thread != 0) {
1266 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 }
1268 return BAD_VALUE;
1269}
1270
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001271String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001273// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1275
Eric Laurenta4c5a552012-03-29 10:12:40 -07001276 Mutex::Autolock _l(mLock);
1277
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001279 String8 out_s8;
1280
Dima Zavin799a70e2011-04-18 16:57:27 -07001281 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001282 char *s;
1283 {
1284 AutoMutex lock(mHardwareLock);
1285 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001286 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001287 s = dev->get_parameters(dev, keys.string());
1288 mHardwareStatus = AUDIO_HW_IDLE;
1289 }
John Grossmanef7740b2012-02-09 11:28:36 -08001290 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001291 free(s);
1292 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001293 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294 }
1295
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1297 if (playbackThread != NULL) {
1298 return playbackThread->getParameters(keys);
1299 }
1300 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1301 if (recordThread != NULL) {
1302 return recordThread->getParameters(keys);
1303 }
1304 return String8("");
1305}
1306
Glenn Kastendd8104c2012-07-02 12:42:44 -07001307size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1308 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309{
Eric Laurenta1884f92011-08-23 08:25:03 -07001310 status_t ret = initCheck();
1311 if (ret != NO_ERROR) {
1312 return 0;
1313 }
1314
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001315 AutoMutex lock(mHardwareLock);
1316 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001317 struct audio_config config = {
1318 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001319 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001320 format: format,
1321 };
John Grossmanee578c02012-07-23 17:05:46 -07001322 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001323#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001324 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001325#else
1326 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1327#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001328 mHardwareStatus = AUDIO_HW_IDLE;
1329 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330}
1331
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001332unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334 Mutex::Autolock _l(mLock);
1335
1336 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1337 if (recordThread != NULL) {
1338 return recordThread->getInputFramesLost();
1339 }
1340 return 0;
1341}
1342
1343status_t AudioFlinger::setVoiceVolume(float value)
1344{
Eric Laurenta1884f92011-08-23 08:25:03 -07001345 status_t ret = initCheck();
1346 if (ret != NO_ERROR) {
1347 return ret;
1348 }
1349
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350 // check calling permissions
1351 if (!settingsAllowed()) {
1352 return PERMISSION_DENIED;
1353 }
1354
1355 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001356 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001357 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001358 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359 mHardwareStatus = AUDIO_HW_IDLE;
1360
1361 return ret;
1362}
1363
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001364status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1365 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366{
1367 status_t status;
1368
1369 Mutex::Autolock _l(mLock);
1370
1371 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1372 if (playbackThread != NULL) {
1373 return playbackThread->getRenderPosition(halFrames, dspFrames);
1374 }
1375
1376 return BAD_VALUE;
1377}
1378
Mingming Yin84f109b2012-12-27 17:43:05 -08001379#ifdef QCOM_FM_ENABLED
1380status_t AudioFlinger::setFmVolume(float value)
1381{
1382 status_t ret = initCheck();
1383 if (ret != NO_ERROR) {
1384 return ret;
1385 }
1386
1387 // check calling permissions
1388 if (!settingsAllowed()) {
1389 return PERMISSION_DENIED;
1390 }
1391
1392 AutoMutex lock(mHardwareLock);
1393 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1394 mHardwareStatus = AUDIO_SET_FM_VOLUME;
1395 ret = dev->set_fm_volume(dev, value);
1396 mHardwareStatus = AUDIO_HW_IDLE;
1397
1398 return ret;
1399}
1400#endif
1401
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1403{
1404
1405 Mutex::Autolock _l(mLock);
1406
vivek mehta2192bc92012-12-04 11:46:08 -08001407 sp<IBinder> binder = client->asBinder();
1408 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409 sp<NotificationClient> notificationClient = new NotificationClient(this,
1410 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001411 binder);
Dorian Snyderf32d5702013-03-01 14:25:46 -08001412 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413
vivek mehta2192bc92012-12-04 11:46:08 -08001414 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415
1416 sp<IBinder> binder = client->asBinder();
1417 binder->linkToDeath(notificationClient);
1418
1419 // the config change is always sent from playback or record threads to avoid deadlock
1420 // with AudioSystem::gLock
1421 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001422 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 }
1424
1425 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001426 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 }
1428 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08001429#ifdef QCOM_HARDWARE
1430 // Send the notification to the client only once.
1431 if (mA2DPHandle != -1) {
1432 ALOGV("A2DP active. Notifying the registered client");
1433 client->ioConfigChanged(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
1434 }
1435#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
vivek mehta2192bc92012-12-04 11:46:08 -08001438#ifdef QCOM_HARDWARE
1439status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1440{
1441 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1442 Mutex::Autolock _l(mLock);
1443
1444 sp<IBinder> binder = client->asBinder();
1445 int index = mNotificationClients.indexOfKey(binder);
1446 if (index >= 0) {
1447 mNotificationClients.removeItemsAt(index);
1448 return true;
1449 }
1450
1451 return false;
1452}
1453#endif
1454
1455void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456{
1457 Mutex::Autolock _l(mLock);
1458
vivek mehta2192bc92012-12-04 11:46:08 -08001459 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001460
vivek mehta2192bc92012-12-04 11:46:08 -08001461 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001463 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001464 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001465 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001466 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001467 ALOGV(" pid %d @ %d", ref->mPid, i);
1468 if (ref->mPid == pid) {
1469 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001470 mAudioSessionRefs.removeAt(i);
1471 delete ref;
1472 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001473 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001474 } else {
1475 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001476 }
1477 }
1478 if (removed) {
1479 purgeStaleEffects_l();
1480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481}
1482
1483// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001484void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485{
vivek mehta2192bc92012-12-04 11:46:08 -08001486#ifdef QCOM_HARDWARE
1487 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1488 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1489 mIsEffectConfigChanged = true;
1490 }
1491#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492 size_t size = mNotificationClients.size();
1493 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001494 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1495 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
1497}
1498
1499// removeClient_l() must be called with AudioFlinger::mLock held
1500void AudioFlinger::removeClient_l(pid_t pid)
1501{
Steve Block3856b092011-10-20 11:56:00 +01001502 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 mClients.removeItem(pid);
1504}
1505
Eric Laurent717e1282012-06-29 16:36:52 -07001506// getEffectThread_l() must be called with AudioFlinger::mLock held
1507sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1508{
1509 sp<PlaybackThread> thread;
1510
1511 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1512 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1513 ALOG_ASSERT(thread == 0);
1514 thread = mPlaybackThreads.valueAt(i);
1515 }
1516 }
1517
1518 return thread;
1519}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520
1521// ----------------------------------------------------------------------------
1522
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001523AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001524 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001525 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001526 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001527 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001528 // mChannelMask
1529 mChannelCount(0),
1530 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1531 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001532 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1533 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001534 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001535 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536{
1537}
1538
1539AudioFlinger::ThreadBase::~ThreadBase()
1540{
1541 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001542 // do not lock the mutex in destructor
1543 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001544 if (mPowerManager != 0) {
1545 sp<IBinder> binder = mPowerManager->asBinder();
1546 binder->unlinkToDeath(mDeathRecipient);
1547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548}
1549
1550void AudioFlinger::ThreadBase::exit()
1551{
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001553 // do any cleanup required for exit to succeed
1554 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001556 // This lock prevents the following race in thread (uniprocessor for illustration):
1557 // if (!exitPending()) {
1558 // // context switch from here to exit()
1559 // // exit() calls requestExit(), what exitPending() observes
1560 // // exit() calls signal(), which is dropped since no waiters
1561 // // context switch back from exit() to here
1562 // mWaitWorkCV.wait(...);
1563 // // now thread is hung
1564 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001565 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001567 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001569 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1570 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 requestExitAndWait();
1572}
1573
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1575{
1576 status_t status;
1577
Steve Block3856b092011-10-20 11:56:00 +01001578 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 Mutex::Autolock _l(mLock);
1580
1581 mNewParameters.add(keyValuePairs);
1582 mWaitWorkCV.signal();
1583 // wait condition with timeout in case the thread loop has exited
1584 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001585 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 status = mParamStatus;
1587 mWaitWorkCV.signal();
1588 } else {
1589 status = TIMED_OUT;
1590 }
1591 return status;
1592}
1593
vivek mehta2192bc92012-12-04 11:46:08 -08001594#ifdef QCOM_HARDWARE
1595void AudioFlinger::ThreadBase::effectConfigChanged() {
1596 mAudioFlinger->mLock.lock();
1597 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1598 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1599 mAudioFlinger->mLock.unlock();
1600}
1601#endif
1602
Eric Laurent896adcd2012-09-13 11:18:23 -07001603void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604{
1605 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001606 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607}
1608
Eric Laurent896adcd2012-09-13 11:18:23 -07001609// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1610void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611{
Eric Laurent896adcd2012-09-13 11:18:23 -07001612 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1613 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1614 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1615 mWaitWorkCV.signal();
1616}
1617
1618// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1619void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1620{
1621 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1622 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1623 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1624 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 mWaitWorkCV.signal();
1626}
1627
1628void AudioFlinger::ThreadBase::processConfigEvents()
1629{
1630 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001631 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001632 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001633 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 mConfigEvents.removeAt(0);
1635 // release mLock before locking AudioFlinger mLock: lock order is always
1636 // AudioFlinger then ThreadBase to avoid cross deadlock
1637 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001638 switch(event->type()) {
1639 case CFG_EVENT_PRIO: {
1640 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1641 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1642 if (err != 0) {
1643 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1644 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1645 }
1646 } break;
1647 case CFG_EVENT_IO: {
1648 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1649 mAudioFlinger->mLock.lock();
1650 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1651 mAudioFlinger->mLock.unlock();
1652 } break;
1653 default:
1654 ALOGE("processConfigEvents() unknown event type %d", event->type());
1655 break;
1656 }
1657 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 mLock.lock();
1659 }
1660 mLock.unlock();
1661}
1662
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001663void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664{
1665 const size_t SIZE = 256;
1666 char buffer[SIZE];
1667 String8 result;
1668
1669 bool locked = tryLock(mLock);
1670 if (!locked) {
1671 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1672 write(fd, buffer, strlen(buffer));
1673 }
1674
Eric Laurent612bbb52012-03-14 15:03:26 -07001675 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1676 result.append(buffer);
1677 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1678 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1680 result.append(buffer);
1681 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1682 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001683 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1684 result.append(buffer);
1685 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 result.append(buffer);
1687 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1688 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001689 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1690 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1692 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001693 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 result.append(buffer);
1695
1696 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1697 result.append(buffer);
1698 result.append(" Index Command");
1699 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1700 snprintf(buffer, SIZE, "\n %02d ", i);
1701 result.append(buffer);
1702 result.append(mNewParameters[i]);
1703 }
1704
1705 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1706 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001708 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 result.append(buffer);
1710 }
1711 result.append("\n");
1712
1713 write(fd, result.string(), result.size());
1714
1715 if (locked) {
1716 mLock.unlock();
1717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718}
1719
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001720void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001721{
1722 const size_t SIZE = 256;
1723 char buffer[SIZE];
1724 String8 result;
1725
1726 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1727 write(fd, buffer, strlen(buffer));
1728
1729 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1730 sp<EffectChain> chain = mEffectChains[i];
1731 if (chain != 0) {
1732 chain->dump(fd, args);
1733 }
1734 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001735}
1736
Eric Laurentfeb0db62011-07-22 09:04:31 -07001737void AudioFlinger::ThreadBase::acquireWakeLock()
1738{
1739 Mutex::Autolock _l(mLock);
1740 acquireWakeLock_l();
1741}
1742
1743void AudioFlinger::ThreadBase::acquireWakeLock_l()
1744{
1745 if (mPowerManager == 0) {
1746 // use checkService() to avoid blocking if power service is not up yet
1747 sp<IBinder> binder =
1748 defaultServiceManager()->checkService(String16("power"));
1749 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001750 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001751 } else {
1752 mPowerManager = interface_cast<IPowerManager>(binder);
1753 binder->linkToDeath(mDeathRecipient);
1754 }
1755 }
1756 if (mPowerManager != 0) {
1757 sp<IBinder> binder = new BBinder();
1758 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1759 binder,
1760 String16(mName));
1761 if (status == NO_ERROR) {
1762 mWakeLockToken = binder;
1763 }
Steve Block3856b092011-10-20 11:56:00 +01001764 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001765 }
1766}
1767
1768void AudioFlinger::ThreadBase::releaseWakeLock()
1769{
1770 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001771 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001772}
1773
1774void AudioFlinger::ThreadBase::releaseWakeLock_l()
1775{
1776 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001777 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001778 if (mPowerManager != 0) {
1779 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1780 }
1781 mWakeLockToken.clear();
1782 }
1783}
1784
1785void AudioFlinger::ThreadBase::clearPowerManager()
1786{
1787 Mutex::Autolock _l(mLock);
1788 releaseWakeLock_l();
1789 mPowerManager.clear();
1790}
1791
1792void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1793{
1794 sp<ThreadBase> thread = mThread.promote();
1795 if (thread != 0) {
1796 thread->clearPowerManager();
1797 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001798 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001799}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001800
Eric Laurent59255e42011-07-27 19:49:51 -07001801void AudioFlinger::ThreadBase::setEffectSuspended(
1802 const effect_uuid_t *type, bool suspend, int sessionId)
1803{
1804 Mutex::Autolock _l(mLock);
1805 setEffectSuspended_l(type, suspend, sessionId);
1806}
1807
1808void AudioFlinger::ThreadBase::setEffectSuspended_l(
1809 const effect_uuid_t *type, bool suspend, int sessionId)
1810{
Glenn Kasten090f0192012-01-30 13:00:02 -08001811 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001812 if (chain != 0) {
1813 if (type != NULL) {
1814 chain->setEffectSuspended_l(type, suspend);
1815 } else {
1816 chain->setEffectSuspendedAll_l(suspend);
1817 }
1818 }
1819
1820 updateSuspendedSessions_l(type, suspend, sessionId);
1821}
1822
1823void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1824{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001825 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001826 if (index < 0) {
1827 return;
1828 }
1829
Glenn Kasten0a7af182012-07-09 16:09:19 -07001830 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1831 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001832
1833 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001834 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001835 for (int j = 0; j < desc->mRefCount; j++) {
1836 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1837 chain->setEffectSuspendedAll_l(true);
1838 } else {
Steve Block3856b092011-10-20 11:56:00 +01001839 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001840 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001841 chain->setEffectSuspended_l(&desc->mType, true);
1842 }
1843 }
1844 }
1845}
1846
Eric Laurent59255e42011-07-27 19:49:51 -07001847void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1848 bool suspend,
1849 int sessionId)
1850{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001851 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001852
1853 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1854
1855 if (suspend) {
1856 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001857 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001858 } else {
1859 mSuspendedSessions.add(sessionId, sessionEffects);
1860 }
1861 } else {
1862 if (index < 0) {
1863 return;
1864 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001865 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001866 }
1867
1868
1869 int key = EffectChain::kKeyForSuspendAll;
1870 if (type != NULL) {
1871 key = type->timeLow;
1872 }
1873 index = sessionEffects.indexOfKey(key);
1874
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001875 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001876 if (suspend) {
1877 if (index >= 0) {
1878 desc = sessionEffects.valueAt(index);
1879 } else {
1880 desc = new SuspendedSessionDesc();
1881 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001882 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001883 }
1884 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001885 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001886 }
1887 desc->mRefCount++;
1888 } else {
1889 if (index < 0) {
1890 return;
1891 }
1892 desc = sessionEffects.valueAt(index);
1893 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001894 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001895 sessionEffects.removeItemsAt(index);
1896 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001898 sessionId);
1899 mSuspendedSessions.removeItem(sessionId);
1900 }
1901 }
1902 }
1903 if (!sessionEffects.isEmpty()) {
1904 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1905 }
1906}
1907
1908void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1909 bool enabled,
1910 int sessionId)
1911{
1912 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001913 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1914}
Eric Laurent59255e42011-07-27 19:49:51 -07001915
Eric Laurenta85a74a2011-10-19 11:44:54 -07001916void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1917 bool enabled,
1918 int sessionId)
1919{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001920 if (mType != RECORD) {
1921 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1922 // another session. This gives the priority to well behaved effect control panels
1923 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001924 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1925 // global effects
1926 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001927 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1928 }
1929 }
Eric Laurent59255e42011-07-27 19:49:51 -07001930
1931 sp<EffectChain> chain = getEffectChain_l(sessionId);
1932 if (chain != 0) {
1933 chain->checkSuspendOnEffectEnabled(effect, enabled);
1934 }
1935}
1936
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937// ----------------------------------------------------------------------------
1938
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001939AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1940 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001941 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001942 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001943 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001944 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001945 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001946 // mStreamTypes[] initialized in constructor body
1947 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001948 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001949 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001950 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001951 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001952 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001953 // index 0 is reserved for normal mixer's submix
1954 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955{
Glenn Kasten480b4682012-02-28 12:30:08 -08001956 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001957
John Grossmanee578c02012-07-23 17:05:46 -07001958 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1959 // it would be safer to explicitly pass initial masterVolume/masterMute as
1960 // parameter.
1961 //
1962 // If the HAL we are using has support for master volume or master mute,
1963 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1964 // and the mute set to false).
1965 mMasterVolume = audioFlinger->masterVolume_l();
1966 mMasterMute = audioFlinger->masterMute_l();
1967 if (mOutput && mOutput->audioHwDev) {
1968 if (mOutput->audioHwDev->canSetMasterVolume()) {
1969 mMasterVolume = 1.0;
1970 }
1971
1972 if (mOutput->audioHwDev->canSetMasterMute()) {
1973 mMasterMute = false;
1974 }
1975 }
1976
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 readOutputParameters();
1978
Glenn Kasten263709e2012-01-06 08:40:01 -08001979 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001980 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1981 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1982 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001983 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1984 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001986 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1987 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988}
1989
1990AudioFlinger::PlaybackThread::~PlaybackThread()
1991{
1992 delete [] mMixBuffer;
1993}
1994
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001995void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996{
1997 dumpInternals(fd, args);
1998 dumpTracks(fd, args);
1999 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000}
2001
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002002void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003{
2004 const size_t SIZE = 256;
2005 char buffer[SIZE];
2006 String8 result;
2007
Glenn Kasten58912562012-04-03 10:45:00 -07002008 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
2009 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2010 const stream_type_t *st = &mStreamTypes[i];
2011 if (i > 0) {
2012 result.appendFormat(", ");
2013 }
2014 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2015 if (st->mute) {
2016 result.append("M");
2017 }
2018 }
2019 result.append("\n");
2020 write(fd, result.string(), result.length());
2021 result.clear();
2022
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
2024 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002025 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 for (size_t i = 0; i < mTracks.size(); ++i) {
2027 sp<Track> track = mTracks[i];
2028 if (track != 0) {
2029 track->dump(buffer, SIZE);
2030 result.append(buffer);
2031 }
2032 }
2033
2034 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
2035 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002036 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08002038 sp<Track> track = mActiveTracks[i].promote();
2039 if (track != 0) {
2040 track->dump(buffer, SIZE);
2041 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 }
2043 }
2044 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07002045
2046 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2047 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
2048 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
2049 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050}
2051
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002052void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053{
2054 const size_t SIZE = 256;
2055 char buffer[SIZE];
2056 String8 result;
2057
2058 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
2059 result.append(buffer);
2060 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
2061 result.append(buffer);
2062 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
2063 result.append(buffer);
2064 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
2065 result.append(buffer);
2066 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
2067 result.append(buffer);
2068 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
2069 result.append(buffer);
2070 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
2071 result.append(buffer);
2072 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002073 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074
2075 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076}
2077
2078// Thread virtuals
2079status_t AudioFlinger::PlaybackThread::readyToRun()
2080{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002081 status_t status = initCheck();
2082 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002083 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002084 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002085 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002087 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088}
2089
2090void AudioFlinger::PlaybackThread::onFirstRef()
2091{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002092 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093}
2094
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002095// ThreadBase virtuals
2096void AudioFlinger::PlaybackThread::preExit()
2097{
2098 ALOGV(" preExit()");
2099 // FIXME this is using hard-coded strings but in the future, this functionality will be
2100 // converted to use audio HAL extensions required to support tunneling
2101 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2102}
2103
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002105sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002107 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002109 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002110 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 int frameCount,
2112 const sp<IMemory>& sharedBuffer,
2113 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002114 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002115 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116 status_t *status)
2117{
2118 sp<Track> track;
2119 status_t lStatus;
2120
Glenn Kasten73d22752012-03-19 13:38:30 -07002121 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2122
2123 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002124 if (flags & IAudioFlinger::TRACK_FAST) {
2125 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002126 // not timed
2127 (!isTimed) &&
2128 // either of these use cases:
2129 (
2130 // use case 1: shared buffer with any frame count
2131 (
2132 (sharedBuffer != 0)
2133 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002134 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002135 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002136 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002137 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002138 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002139 )
2140 ) &&
2141 // PCM data
2142 audio_is_linear_pcm(format) &&
2143 // mono or stereo
2144 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2145 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002146#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002147 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002148 (sampleRate == mSampleRate) &&
2149#endif
2150 // normal mixer has an associated fast mixer
2151 hasFastMixer() &&
2152 // there are sufficient fast track slots available
2153 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002154 // FIXME test that MixerThread for this fast track has a capable output HAL
2155 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002156 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002157 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2158 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002159 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002160 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002161 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002162 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002163 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002164 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002165 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002166 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2167 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2168 audio_is_linear_pcm(format),
2169 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002170 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002171 // For compatibility with AudioTrack calculation, buffer depth is forced
2172 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2173 // This is probably too conservative, but legacy application code may depend on it.
2174 // If you change this calculation, also review the start threshold which is related.
2175 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2176 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2177 if (minBufCount < 2) {
2178 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002179 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002180 int minFrameCount = mNormalFrameCount * minBufCount;
2181 if (frameCount < minFrameCount) {
2182 frameCount = minFrameCount;
2183 }
2184 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002185 }
2186
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002188 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2189 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002190 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002191 "for output %p with format %d",
2192 sampleRate, format, channelMask, mOutput, mFormat);
2193 lStatus = BAD_VALUE;
2194 goto Exit;
2195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 }
2197 } else {
2198 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2199 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002200 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 lStatus = BAD_VALUE;
2202 goto Exit;
2203 }
2204 }
2205
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002206 lStatus = initCheck();
2207 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002208 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 goto Exit;
2210 }
2211
2212 { // scope for mLock
2213 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002214
2215 // all tracks in same audio session must share the same routing strategy otherwise
2216 // conflicts will happen when tracks are moved from one output to another by audio policy
2217 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002218 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002219 for (size_t i = 0; i < mTracks.size(); ++i) {
2220 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002221 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002222 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002223 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002224 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002225 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002226 lStatus = BAD_VALUE;
2227 goto Exit;
2228 }
2229 }
2230 }
2231
John Grossman4ff14ba2012-02-08 16:37:41 -08002232 if (!isTimed) {
2233 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002234 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002235 } else {
2236 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2237 channelMask, frameCount, sharedBuffer, sessionId);
2238 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002239 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 lStatus = NO_MEMORY;
2241 goto Exit;
2242 }
2243 mTracks.add(track);
2244
2245 sp<EffectChain> chain = getEffectChain_l(sessionId);
2246 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002247 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002249 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002250 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002252
Eric Laurent896adcd2012-09-13 11:18:23 -07002253 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2254 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2255 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2256 // so ask activity manager to do this on our behalf
2257 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002258 }
2259 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002260
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 lStatus = NO_ERROR;
2262
2263Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002264 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 *status = lStatus;
2266 }
2267 return track;
2268}
2269
Eric Laurente737cda2012-05-22 18:55:44 -07002270uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2271{
2272 if (mFastMixer != NULL) {
2273 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2274 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2275 }
2276 return latency;
2277}
2278
2279uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2280{
2281 return latency;
2282}
2283
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284uint32_t AudioFlinger::PlaybackThread::latency() const
2285{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002286 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002287 return latency_l();
2288}
2289uint32_t AudioFlinger::PlaybackThread::latency_l() const
2290{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002291 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002292 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002293 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 return 0;
2295 }
2296}
2297
Glenn Kasten6637baa2012-01-09 09:40:36 -08002298void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002300 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002301 // Don't apply master volume in SW if our HAL can do it for us.
2302 if (mOutput && mOutput->audioHwDev &&
2303 mOutput->audioHwDev->canSetMasterVolume()) {
2304 mMasterVolume = 1.0;
2305 } else {
2306 mMasterVolume = value;
2307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308}
2309
Glenn Kasten6637baa2012-01-09 09:40:36 -08002310void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002312 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002313 // Don't apply master mute in SW if our HAL can do it for us.
2314 if (mOutput && mOutput->audioHwDev &&
2315 mOutput->audioHwDev->canSetMasterMute()) {
2316 mMasterMute = false;
2317 } else {
2318 mMasterMute = muted;
2319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320}
2321
Glenn Kasten6637baa2012-01-09 09:40:36 -08002322void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002324 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326}
2327
Glenn Kasten6637baa2012-01-09 09:40:36 -08002328void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002330 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332}
2333
Glenn Kastenfff6d712012-01-12 16:38:12 -08002334float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002336 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 return mStreamTypes[stream].volume;
2338}
2339
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340// addTrack_l() must be called with ThreadBase::mLock held
2341status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2342{
2343 status_t status = ALREADY_EXISTS;
2344
2345 // set retry count for buffer fill
2346 track->mRetryCount = kMaxTrackStartupRetries;
2347 if (mActiveTracks.indexOf(track) < 0) {
2348 // the track is newly added, make sure it fills up all its
2349 // buffers before playing. This is to ensure the client will
2350 // effectively get the latency it requested.
2351 track->mFillingUpStatus = Track::FS_FILLING;
2352 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002353 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 mActiveTracks.add(track);
2355 if (track->mainBuffer() != mMixBuffer) {
2356 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2357 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002358 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002359 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 }
2361 }
2362
2363 status = NO_ERROR;
2364 }
2365
Steve Block3856b092011-10-20 11:56:00 +01002366 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 mWaitWorkCV.broadcast();
2368
2369 return status;
2370}
2371
2372// destroyTrack_l() must be called with ThreadBase::mLock held
2373void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2374{
2375 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002376 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002378 removeTrack_l(track);
2379 }
2380}
2381
2382void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2383{
Eric Laurent29864602012-05-08 18:57:51 -07002384 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002385 mTracks.remove(track);
2386 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002387 // redundant as track is about to be destroyed, for dumpsys only
2388 track->mName = -1;
2389 if (track->isFastTrack()) {
2390 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002391 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002392 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2393 mFastTrackAvailMask |= 1 << index;
2394 // redundant as track is about to be destroyed, for dumpsys only
2395 track->mFastIndex = -1;
2396 }
Eric Laurentb469b942011-05-09 12:09:06 -07002397 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2398 if (chain != 0) {
2399 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 }
2401}
2402
2403String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2404{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002405 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002406 char *s;
2407
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002408 Mutex::Autolock _l(mLock);
2409 if (initCheck() != NO_ERROR) {
2410 return out_s8;
2411 }
2412
Dima Zavin799a70e2011-04-18 16:57:27 -07002413 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002414 out_s8 = String8(s);
2415 free(s);
2416 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417}
2418
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002419// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2421 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002422 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423
Steve Block3856b092011-10-20 11:56:00 +01002424 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425
2426 switch (event) {
2427 case AudioSystem::OUTPUT_OPENED:
2428 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002429 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 desc.samplingRate = mSampleRate;
2431 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002432 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 desc.latency = latency();
2434 param2 = &desc;
2435 break;
2436
2437 case AudioSystem::STREAM_CONFIG_CHANGED:
2438 param2 = &param;
2439 case AudioSystem::OUTPUT_CLOSED:
2440 default:
2441 break;
2442 }
2443 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2444}
2445
2446void AudioFlinger::PlaybackThread::readOutputParameters()
2447{
Dima Zavin799a70e2011-04-18 16:57:27 -07002448 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002449 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2450 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002451 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002452 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002453 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002454 if (mFrameCount & 15) {
2455 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2456 mFrameCount);
2457 }
2458
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002459 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002460 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002461 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002462 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002463 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2464 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2465 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2466 maxNormalFrameCount = maxNormalFrameCount & ~15;
2467 if (maxNormalFrameCount < minNormalFrameCount) {
2468 maxNormalFrameCount = minNormalFrameCount;
2469 }
2470 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2471 if (multiplier <= 1.0) {
2472 multiplier = 1.0;
2473 } else if (multiplier <= 2.0) {
2474 if (2 * mFrameCount <= maxNormalFrameCount) {
2475 multiplier = 2.0;
2476 } else {
2477 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2478 }
2479 } else {
2480 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2481 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2482 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2483 // FIXME this rounding up should not be done if no HAL SRC
2484 uint32_t truncMult = (uint32_t) multiplier;
2485 if ((truncMult & 1)) {
2486 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2487 ++truncMult;
2488 }
2489 }
2490 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002491 }
Glenn Kasten58912562012-04-03 10:45:00 -07002492 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002493 mNormalFrameCount = multiplier * mFrameCount;
2494 // round up to nearest 16 frames to satisfy AudioMixer
2495 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002496 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497
Glenn Kastene9dd0172012-01-27 18:08:45 -08002498 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002499 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2500 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501
Eric Laurentde070132010-07-13 04:45:46 -07002502 // force reconfiguration of effect chains and engines to take new buffer size and audio
2503 // parameters into account
2504 // Note that mLock is not held when readOutputParameters() is called from the constructor
2505 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2506 // matter.
2507 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2508 Vector< sp<EffectChain> > effectChains = mEffectChains;
2509 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002510 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512}
2513
Eric Laurente737cda2012-05-22 18:55:44 -07002514
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2516{
Glenn Kastena0d68332012-01-27 16:47:15 -08002517 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 return BAD_VALUE;
2519 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002520 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002521 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522 return INVALID_OPERATION;
2523 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002524 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525
Eric Laurent1afc26d2012-09-23 15:20:50 -07002526 if (isSuspended()) {
2527 // return an estimation of rendered frames when the output is suspended
2528 int32_t frames = mBytesWritten - latency_l();
2529 if (frames < 0) {
2530 frames = 0;
2531 }
2532 *dspFrames = (uint32_t)frames;
2533 return NO_ERROR;
2534 } else {
2535 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2536 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537}
2538
Glenn Kasten106e8a42012-08-02 13:37:12 -07002539uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540{
2541 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002542 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002544 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
2546
2547 for (size_t i = 0; i < mTracks.size(); ++i) {
2548 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002549 if (sessionId == track->sessionId() &&
2550 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002551 result |= TRACK_SESSION;
2552 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 }
2554 }
2555
Eric Laurent39e94f82010-07-28 01:32:47 -07002556 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557}
2558
Eric Laurentde070132010-07-13 04:45:46 -07002559uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2560{
Dima Zavinfce7a472011-04-19 22:30:36 -07002561 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002562 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002563 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2564 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002565 }
2566 for (size_t i = 0; i < mTracks.size(); i++) {
2567 sp<Track> track = mTracks[i];
2568 if (sessionId == track->sessionId() &&
2569 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002570 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002571 }
2572 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002573 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002574}
2575
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576
Glenn Kastenaed850d2012-01-26 09:46:34 -08002577AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002578{
2579 Mutex::Autolock _l(mLock);
2580 return mOutput;
2581}
2582
2583AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2584{
2585 Mutex::Autolock _l(mLock);
2586 AudioStreamOut *output = mOutput;
2587 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002588 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2589 // must push a NULL and wait for ack
2590 mOutputSink.clear();
2591 mPipeSink.clear();
2592 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002593 return output;
2594}
2595
2596// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002597audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002598{
2599 if (mOutput == NULL) {
2600 return NULL;
2601 }
2602 return &mOutput->stream->common;
2603}
2604
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002605uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002606{
Eric Laurentab9071b2012-06-04 13:45:29 -07002607 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002608}
2609
Eric Laurenta011e352012-03-29 15:51:43 -07002610status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2611{
2612 if (!isValidSyncEvent(event)) {
2613 return BAD_VALUE;
2614 }
2615
2616 Mutex::Autolock _l(mLock);
2617
2618 for (size_t i = 0; i < mTracks.size(); ++i) {
2619 sp<Track> track = mTracks[i];
2620 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002621 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002622 return NO_ERROR;
2623 }
2624 }
2625
2626 return NAME_NOT_FOUND;
2627}
2628
Glenn Kasten106e8a42012-08-02 13:37:12 -07002629bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002630{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002631 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002632}
2633
Eric Laurent44a957f2012-05-15 15:26:05 -07002634void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2635{
2636 size_t count = tracksToRemove.size();
2637 if (CC_UNLIKELY(count)) {
2638 for (size_t i = 0 ; i < count ; i++) {
2639 const sp<Track>& track = tracksToRemove.itemAt(i);
2640 if ((track->sharedBuffer() != 0) &&
2641 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2642 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2643 }
2644 }
2645 }
2646
2647}
2648
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649// ----------------------------------------------------------------------------
2650
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002651AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002652 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002653 : PlaybackThread(audioFlinger, output, id, device, type),
2654 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002655 // mFastMixer below
2656 mFastMixerFutex(0)
2657 // mOutputSink below
2658 // mPipeSink below
2659 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002661 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002662 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002663 "mFrameCount=%d, mNormalFrameCount=%d",
2664 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2665 mNormalFrameCount);
2666 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2667
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002669 if (mChannelCount != FCC_2) {
2670 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 }
Glenn Kasten58912562012-04-03 10:45:00 -07002672
2673 // create an NBAIO sink for the HAL output stream, and negotiate
2674 mOutputSink = new AudioStreamOutSink(output->stream);
2675 size_t numCounterOffers = 0;
2676 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2677 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2678 ALOG_ASSERT(index == 0);
2679
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002680 // initialize fast mixer depending on configuration
2681 bool initFastMixer;
2682 switch (kUseFastMixer) {
2683 case FastMixer_Never:
2684 initFastMixer = false;
2685 break;
2686 case FastMixer_Always:
2687 initFastMixer = true;
2688 break;
2689 case FastMixer_Static:
2690 case FastMixer_Dynamic:
2691 initFastMixer = mFrameCount < mNormalFrameCount;
2692 break;
2693 }
2694 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002695
2696 // create a MonoPipe to connect our submix to FastMixer
2697 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002698 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2699 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2700 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2701 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002702 const NBAIO_Format offers[1] = {format};
2703 size_t numCounterOffers = 0;
2704 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2705 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002706 monoPipe->setAvgFrames((mScreenState & 1) ?
2707 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002708 mPipeSink = monoPipe;
2709
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002710#ifdef TEE_SINK_FRAMES
2711 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2712 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2713 numCounterOffers = 0;
2714 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2715 ALOG_ASSERT(index == 0);
2716 mTeeSink = teeSink;
2717 PipeReader *teeSource = new PipeReader(*teeSink);
2718 numCounterOffers = 0;
2719 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2720 ALOG_ASSERT(index == 0);
2721 mTeeSource = teeSource;
2722#endif
2723
Glenn Kasten58912562012-04-03 10:45:00 -07002724 // create fast mixer and configure it initially with just one fast track for our submix
2725 mFastMixer = new FastMixer();
2726 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002727#ifdef STATE_QUEUE_DUMP
2728 sq->setObserverDump(&mStateQueueObserverDump);
2729 sq->setMutatorDump(&mStateQueueMutatorDump);
2730#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002731 FastMixerState *state = sq->begin();
2732 FastTrack *fastTrack = &state->mFastTracks[0];
2733 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2734 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2735 fastTrack->mVolumeProvider = NULL;
2736 fastTrack->mGeneration++;
2737 state->mFastTracksGen++;
2738 state->mTrackMask = 1;
2739 // fast mixer will use the HAL output sink
2740 state->mOutputSink = mOutputSink.get();
2741 state->mOutputSinkGen++;
2742 state->mFrameCount = mFrameCount;
2743 state->mCommand = FastMixerState::COLD_IDLE;
2744 // already done in constructor initialization list
2745 //mFastMixerFutex = 0;
2746 state->mColdFutexAddr = &mFastMixerFutex;
2747 state->mColdGen++;
2748 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002749 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002750 sq->end();
2751 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2752
2753 // start the fast mixer
2754 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002755 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002756 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002757 if (err != 0) {
2758 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002759 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002760 }
Glenn Kasten58912562012-04-03 10:45:00 -07002761
Glenn Kastenc15d6652012-05-30 14:52:57 -07002762#ifdef AUDIO_WATCHDOG
2763 // create and start the watchdog
2764 mAudioWatchdog = new AudioWatchdog();
2765 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2766 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2767 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002768 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002769 if (err != 0) {
2770 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002771 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002772 }
2773#endif
2774
Glenn Kasten58912562012-04-03 10:45:00 -07002775 } else {
2776 mFastMixer = NULL;
2777 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002778
2779 switch (kUseFastMixer) {
2780 case FastMixer_Never:
2781 case FastMixer_Dynamic:
2782 mNormalSink = mOutputSink;
2783 break;
2784 case FastMixer_Always:
2785 mNormalSink = mPipeSink;
2786 break;
2787 case FastMixer_Static:
2788 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2789 break;
2790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791}
2792
2793AudioFlinger::MixerThread::~MixerThread()
2794{
Glenn Kasten58912562012-04-03 10:45:00 -07002795 if (mFastMixer != NULL) {
2796 FastMixerStateQueue *sq = mFastMixer->sq();
2797 FastMixerState *state = sq->begin();
2798 if (state->mCommand == FastMixerState::COLD_IDLE) {
2799 int32_t old = android_atomic_inc(&mFastMixerFutex);
2800 if (old == -1) {
2801 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2802 }
2803 }
2804 state->mCommand = FastMixerState::EXIT;
2805 sq->end();
2806 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2807 mFastMixer->join();
2808 // Though the fast mixer thread has exited, it's state queue is still valid.
2809 // We'll use that extract the final state which contains one remaining fast track
2810 // corresponding to our sub-mix.
2811 state = sq->begin();
2812 ALOG_ASSERT(state->mTrackMask == 1);
2813 FastTrack *fastTrack = &state->mFastTracks[0];
2814 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2815 delete fastTrack->mBufferProvider;
2816 sq->end(false /*didModify*/);
2817 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002818#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002819 if (mAudioWatchdog != 0) {
2820 mAudioWatchdog->requestExit();
2821 mAudioWatchdog->requestExitAndWait();
2822 mAudioWatchdog.clear();
2823 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002824#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002825 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 delete mAudioMixer;
2827}
2828
Glenn Kasten83efdd02012-02-24 07:21:32 -08002829class CpuStats {
2830public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002831 CpuStats();
2832 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002833#ifdef DEBUG_CPU_USAGE
2834private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002835 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2836 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2837
2838 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2839
2840 int mCpuNum; // thread's current CPU number
2841 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002842#endif
2843};
2844
Glenn Kasten190a46f2012-03-06 11:27:10 -08002845CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002846#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002847 : mCpuNum(-1), mCpukHz(-1)
2848#endif
2849{
2850}
2851
2852void CpuStats::sample(const String8 &title) {
2853#ifdef DEBUG_CPU_USAGE
2854 // get current thread's delta CPU time in wall clock ns
2855 double wcNs;
2856 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2857
2858 // record sample for wall clock statistics
2859 if (valid) {
2860 mWcStats.sample(wcNs);
2861 }
2862
2863 // get the current CPU number
2864 int cpuNum = sched_getcpu();
2865
2866 // get the current CPU frequency in kHz
2867 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2868
2869 // check if either CPU number or frequency changed
2870 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2871 mCpuNum = cpuNum;
2872 mCpukHz = cpukHz;
2873 // ignore sample for purposes of cycles
2874 valid = false;
2875 }
2876
2877 // if no change in CPU number or frequency, then record sample for cycle statistics
2878 if (valid && mCpukHz > 0) {
2879 double cycles = wcNs * cpukHz * 0.000001;
2880 mHzStats.sample(cycles);
2881 }
2882
2883 unsigned n = mWcStats.n();
2884 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002885 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002886 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002887 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2888 double perLoop = elapsed / (double) n;
2889 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002890 double perLoop1k = perLoop * 0.001;
2891 double mean = mWcStats.mean();
2892 double stddev = mWcStats.stddev();
2893 double minimum = mWcStats.minimum();
2894 double maximum = mWcStats.maximum();
2895 double meanCycles = mHzStats.mean();
2896 double stddevCycles = mHzStats.stddev();
2897 double minCycles = mHzStats.minimum();
2898 double maxCycles = mHzStats.maximum();
2899 mCpuUsage.resetElapsed();
2900 mWcStats.reset();
2901 mHzStats.reset();
2902 ALOGD("CPU usage for %s over past %.1f secs\n"
2903 " (%u mixer loops at %.1f mean ms per loop):\n"
2904 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2905 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2906 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2907 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002908 elapsed * .000000001, n, perLoop * .000001,
2909 mean * .001,
2910 stddev * .001,
2911 minimum * .001,
2912 maximum * .001,
2913 mean / perLoop100,
2914 stddev / perLoop100,
2915 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002916 maximum / perLoop100,
2917 meanCycles / perLoop1k,
2918 stddevCycles / perLoop1k,
2919 minCycles / perLoop1k,
2920 maxCycles / perLoop1k);
2921
Glenn Kasten83efdd02012-02-24 07:21:32 -08002922 }
2923 }
2924#endif
2925};
2926
Glenn Kasten37d825e2012-02-24 07:21:48 -08002927void AudioFlinger::PlaybackThread::checkSilentMode_l()
2928{
2929 if (!mMasterMute) {
2930 char value[PROPERTY_VALUE_MAX];
2931 if (property_get("ro.audio.silent", value, "0") > 0) {
2932 char *endptr;
2933 unsigned long ul = strtoul(value, &endptr, 0);
2934 if (*endptr == '\0' && ul != 0) {
2935 ALOGD("Silence is golden");
2936 // The setprop command will not allow a property to be changed after
2937 // the first time it is set, so we don't have to worry about un-muting.
2938 setMasterMute_l(true);
2939 }
2940 }
2941 }
2942}
2943
Glenn Kasten000f0e32012-03-01 17:10:56 -08002944bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945{
2946 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002947
Glenn Kasten000f0e32012-03-01 17:10:56 -08002948 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002949
2950 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002952
Glenn Kasten000f0e32012-03-01 17:10:56 -08002953 // DUPLICATING
2954 // FIXME could this be made local to while loop?
2955 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002956
Glenn Kasten66fcab92012-02-24 14:59:21 -08002957 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002958 sleepTime = idleSleepTime;
2959
Glenn Kasten9f34a362012-03-20 16:46:41 -07002960 if (mType == MIXER) {
2961 sleepTimeShift = 0;
2962 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002963
Glenn Kasten83efdd02012-02-24 07:21:32 -08002964 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002965 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966
Eric Laurentfeb0db62011-07-22 09:04:31 -07002967 acquireWakeLock();
2968
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 while (!exitPending())
2970 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002971 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002972
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002973 Vector< sp<EffectChain> > effectChains;
2974
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 processConfigEvents();
2976
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 { // scope for mLock
2978
2979 Mutex::Autolock _l(mLock);
2980
2981 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002982 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 }
2984
Glenn Kastenfa26a852012-03-06 11:28:04 -08002985 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002986
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002988 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002989 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002991
2992 threadLoop_standby();
2993
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995 }
2996
Glenn Kasten3e074702012-02-28 18:40:35 -08002997 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 // we're about to wait, flush the binder command buffer
2999 IPCThreadState::self()->flushCommands();
3000
Glenn Kastenfa26a852012-03-06 11:28:04 -08003001 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003002
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003 if (exitPending()) break;
3004
Eric Laurentfeb0db62011-07-22 09:04:31 -07003005 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08003007 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08003009 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003010 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011
Eric Laurentda747442012-04-25 18:53:13 -07003012 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07003013 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07003014 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003015
Glenn Kasten37d825e2012-02-24 07:21:48 -08003016 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017
Glenn Kasten000f0e32012-03-01 17:10:56 -08003018 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003020 if (mType == MIXER) {
3021 sleepTimeShift = 0;
3022 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003023
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 continue;
3025 }
3026 }
3027
Glenn Kasten81028042012-04-30 18:15:12 -07003028 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07003029 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030
3031 // prevent any changes in effect chain list and in each effect chain
3032 // during mixing and effect process as the audio buffers could be deleted
3033 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003034 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08003035 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036
Glenn Kastenfec279f2012-03-08 07:47:15 -08003037 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003038 threadLoop_mix();
3039 } else {
3040 threadLoop_sleepTime();
3041 }
3042
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003043 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003044 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07003045 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003046 }
3047
3048 // only process effects if we're going to write
3049 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003050 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08003051#ifdef QCOM_HARDWARE
3052 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
3053#endif
3054 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003055 }
3056 }
3057
3058 // enable changes in effect chain
3059 unlockEffectChains(effectChains);
3060
3061 // sleepTime == 0 means we must write to audio hardware
3062 if (sleepTime == 0) {
3063
3064 threadLoop_write();
3065
3066if (mType == MIXER) {
3067 // write blocked detection
3068 nsecs_t now = systemTime();
3069 nsecs_t delta = now - mLastWriteTime;
3070 if (!mStandby && delta > maxPeriod) {
3071 mNumDelayedWrites++;
3072 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003073#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003074 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003075#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003076 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3077 ns2ms(delta), mNumDelayedWrites, this);
3078 lastWarning = now;
3079 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003080 }
3081}
3082
3083 mStandby = false;
3084 } else {
3085 usleep(sleepTime);
3086 }
3087
Glenn Kasten58912562012-04-03 10:45:00 -07003088 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003089 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003090 // same lock. This will also mutate and push a new fast mixer state.
3091 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003092 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003093
Glenn Kastenfa26a852012-03-06 11:28:04 -08003094 // FIXME I don't understand the need for this here;
3095 // it was in the original code but maybe the
3096 // assignment in saveOutputTracks() makes this unnecessary?
3097 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003098
3099 // Effect chains will be actually deleted here if they were removed from
3100 // mEffectChains list during mixing or effects processing
3101 effectChains.clear();
3102
3103 // FIXME Note that the above .clear() is no longer necessary since effectChains
3104 // is now local to this block, but will keep it for now (at least until merge done).
3105 }
3106
Glenn Kasten9f34a362012-03-20 16:46:41 -07003107 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3108 if (mType == MIXER || mType == DIRECT) {
3109 // put output stream into standby mode
3110 if (!mStandby) {
3111 mOutput->stream->common.standby(&mOutput->stream->common);
3112 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003113 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003114
3115 releaseWakeLock();
3116
3117 ALOGV("Thread %p type %d exiting", this, mType);
3118 return false;
3119}
3120
Glenn Kasten58912562012-04-03 10:45:00 -07003121void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3122{
Glenn Kasten58912562012-04-03 10:45:00 -07003123 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3124}
3125
3126void AudioFlinger::MixerThread::threadLoop_write()
3127{
3128 // FIXME we should only do one push per cycle; confirm this is true
3129 // Start the fast mixer if it's not already running
3130 if (mFastMixer != NULL) {
3131 FastMixerStateQueue *sq = mFastMixer->sq();
3132 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003133 if (state->mCommand != FastMixerState::MIX_WRITE &&
3134 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003135 if (state->mCommand == FastMixerState::COLD_IDLE) {
3136 int32_t old = android_atomic_inc(&mFastMixerFutex);
3137 if (old == -1) {
3138 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3139 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003140#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003141 if (mAudioWatchdog != 0) {
3142 mAudioWatchdog->resume();
3143 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003144#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003145 }
3146 state->mCommand = FastMixerState::MIX_WRITE;
3147 sq->end();
3148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003149 if (kUseFastMixer == FastMixer_Dynamic) {
3150 mNormalSink = mPipeSink;
3151 }
Glenn Kasten58912562012-04-03 10:45:00 -07003152 } else {
3153 sq->end(false /*didModify*/);
3154 }
3155 }
3156 PlaybackThread::threadLoop_write();
3157}
3158
Glenn Kasten000f0e32012-03-01 17:10:56 -08003159// shared by MIXER and DIRECT, overridden by DUPLICATING
3160void AudioFlinger::PlaybackThread::threadLoop_write()
3161{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003162 // FIXME rewrite to reduce number of system calls
3163 mLastWriteTime = systemTime();
3164 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003165 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003166
Eric Laurent67c0a582012-05-01 19:31:12 -07003167 // If an NBAIO sink is present, use it to write the normal mixer's submix
3168 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003169#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003170 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003171#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003172 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003173#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003174 // update the setpoint when gScreenState changes
3175 uint32_t screenState = gScreenState;
3176 if (screenState != mScreenState) {
3177 mScreenState = screenState;
3178 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3179 if (pipe != NULL) {
3180 pipe->setAvgFrames((mScreenState & 1) ?
3181 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3182 }
3183 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003184 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003185#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003186 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003187#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003188 if (framesWritten > 0) {
3189 bytesWritten = framesWritten << mBitShift;
3190 } else {
3191 bytesWritten = framesWritten;
3192 }
3193 // otherwise use the HAL / AudioStreamOut directly
3194 } else {
3195 // Direct output thread.
3196 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003197 }
3198
Eric Laurent67c0a582012-05-01 19:31:12 -07003199 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003200 mNumWrites++;
3201 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003202}
3203
Glenn Kasten58912562012-04-03 10:45:00 -07003204void AudioFlinger::MixerThread::threadLoop_standby()
3205{
3206 // Idle the fast mixer if it's currently running
3207 if (mFastMixer != NULL) {
3208 FastMixerStateQueue *sq = mFastMixer->sq();
3209 FastMixerState *state = sq->begin();
3210 if (!(state->mCommand & FastMixerState::IDLE)) {
3211 state->mCommand = FastMixerState::COLD_IDLE;
3212 state->mColdFutexAddr = &mFastMixerFutex;
3213 state->mColdGen++;
3214 mFastMixerFutex = 0;
3215 sq->end();
3216 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3217 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003218 if (kUseFastMixer == FastMixer_Dynamic) {
3219 mNormalSink = mOutputSink;
3220 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003221#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003222 if (mAudioWatchdog != 0) {
3223 mAudioWatchdog->pause();
3224 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003225#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003226 } else {
3227 sq->end(false /*didModify*/);
3228 }
3229 }
3230 PlaybackThread::threadLoop_standby();
3231}
3232
Glenn Kasten000f0e32012-03-01 17:10:56 -08003233// shared by MIXER and DIRECT, overridden by DUPLICATING
3234void AudioFlinger::PlaybackThread::threadLoop_standby()
3235{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003236 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003237 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003238}
3239
3240void AudioFlinger::MixerThread::threadLoop_mix()
3241{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003242 // obtain the presentation timestamp of the next output buffer
3243 int64_t pts;
3244 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003245
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003246#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003247 if (mNormalSink != 0) {
3248 status = mNormalSink->getNextWriteTimestamp(&pts);
3249 } else {
3250 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003251 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003252#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003253
Glenn Kasten952eeb22012-03-06 11:30:57 -08003254 if (status != NO_ERROR) {
3255 pts = AudioBufferProvider::kInvalidPTS;
3256 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003257
Glenn Kasten952eeb22012-03-06 11:30:57 -08003258 // mix buffers...
3259 mAudioMixer->process(pts);
3260 // increase sleep time progressively when application underrun condition clears.
3261 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3262 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3263 // such that we would underrun the audio HAL.
3264 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3265 sleepTimeShift--;
3266 }
3267 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003268 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003269 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003270}
3271
3272void AudioFlinger::MixerThread::threadLoop_sleepTime()
3273{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003274 // If no tracks are ready, sleep once for the duration of an output
3275 // buffer size, then write 0s to the output
3276 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003277 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003278 sleepTime = activeSleepTime >> sleepTimeShift;
3279 if (sleepTime < kMinThreadSleepTimeUs) {
3280 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003282 // reduce sleep time in case of consecutive application underruns to avoid
3283 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3284 // duration we would end up writing less data than needed by the audio HAL if
3285 // the condition persists.
3286 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3287 sleepTimeShift++;
3288 }
3289 } else {
3290 sleepTime = idleSleepTime;
3291 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003292 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003293 memset (mMixBuffer, 0, mixBufferSize);
3294 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003295 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003296 }
3297 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298}
3299
3300// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003301AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003302 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303{
3304
Glenn Kasten29c23c32012-01-26 13:37:52 -08003305 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003307 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 size_t mixedTracks = 0;
3309 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003310 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003311 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003312 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313
3314 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003315 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316
Eric Laurent571d49c2010-08-11 05:20:11 -07003317 if (masterMute) {
3318 masterVolume = 0;
3319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003321 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003323 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003324 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 masterVolume = (float)((v + (1 << 23)) >> 24);
3326 chain.clear();
3327 }
3328
Glenn Kasten288ed212012-04-25 17:52:27 -07003329 // prepare a new state to push
3330 FastMixerStateQueue *sq = NULL;
3331 FastMixerState *state = NULL;
3332 bool didModify = false;
3333 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3334 if (mFastMixer != NULL) {
3335 sq = mFastMixer->sq();
3336 state = sq->begin();
3337 }
3338
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003340 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 if (t == 0) continue;
3342
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003343 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003345
Glenn Kasten288ed212012-04-25 17:52:27 -07003346 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003347 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003348
3349 // It's theoretically possible (though unlikely) for a fast track to be created
3350 // and then removed within the same normal mix cycle. This is not a problem, as
3351 // the track never becomes active so it's fast mixer slot is never touched.
3352 // The converse, of removing an (active) track and then creating a new track
3353 // at the identical fast mixer slot within the same normal mix cycle,
3354 // is impossible because the slot isn't marked available until the end of each cycle.
3355 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003356 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3357 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003358 FastTrack *fastTrack = &state->mFastTracks[j];
3359
3360 // Determine whether the track is currently in underrun condition,
3361 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003362 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3363 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003364 uint32_t recentFull = (underruns.mBitFields.mFull -
3365 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3366 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3367 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3368 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3369 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3370 uint32_t recentUnderruns = recentPartial + recentEmpty;
3371 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003372 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003373 // or stopped which can occur when flush() is called while active
3374 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003375 track->mUnderrunCount += recentUnderruns;
3376 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003377
Glenn Kastend08f48c2012-05-01 18:14:02 -07003378 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003379 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003380 bool isActive = true;
3381 switch (track->mState) {
3382 case TrackBase::STOPPING_1:
3383 // track stays active in STOPPING_1 state until first underrun
3384 if (recentUnderruns > 0) {
3385 track->mState = TrackBase::STOPPING_2;
3386 }
3387 break;
3388 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003389 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003390 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003391 break;
3392 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003393 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003394 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003395 break;
3396 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003397 if (recentFull > 0 || recentPartial > 0) {
3398 // track has provided at least some frames recently: reset retry count
3399 track->mRetryCount = kMaxTrackRetries;
3400 }
3401 if (recentUnderruns == 0) {
3402 // no recent underruns: stay active
3403 break;
3404 }
3405 // there has recently been an underrun of some kind
3406 if (track->sharedBuffer() == 0) {
3407 // were any of the recent underruns "empty" (no frames available)?
3408 if (recentEmpty == 0) {
3409 // no, then ignore the partial underruns as they are allowed indefinitely
3410 break;
3411 }
3412 // there has recently been an "empty" underrun: decrement the retry counter
3413 if (--(track->mRetryCount) > 0) {
3414 break;
3415 }
3416 // indicate to client process that the track was disabled because of underrun;
3417 // it will then automatically call start() when data is available
3418 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3419 // remove from active list, but state remains ACTIVE [confusing but true]
3420 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003421 break;
3422 }
3423 // fall through
3424 case TrackBase::STOPPING_2:
3425 case TrackBase::PAUSED:
3426 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003427 case TrackBase::STOPPED:
3428 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003429 // Check for presentation complete if track is inactive
3430 // We have consumed all the buffers of this track.
3431 // This would be incomplete if we auto-paused on underrun
3432 {
3433 size_t audioHALFrames =
3434 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3435 size_t framesWritten =
3436 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003437 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003438 // track stays in active list until presentation is complete
3439 break;
3440 }
3441 }
3442 if (track->isStopping_2()) {
3443 track->mState = TrackBase::STOPPED;
3444 }
3445 if (track->isStopped()) {
3446 // Can't reset directly, as fast mixer is still polling this track
3447 // track->reset();
3448 // So instead mark this track as needing to be reset after push with ack
3449 resetMask |= 1 << i;
3450 }
3451 isActive = false;
3452 break;
3453 case TrackBase::IDLE:
3454 default:
3455 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003456 }
3457
3458 if (isActive) {
3459 // was it previously inactive?
3460 if (!(state->mTrackMask & (1 << j))) {
3461 ExtendedAudioBufferProvider *eabp = track;
3462 VolumeProvider *vp = track;
3463 fastTrack->mBufferProvider = eabp;
3464 fastTrack->mVolumeProvider = vp;
3465 fastTrack->mSampleRate = track->mSampleRate;
3466 fastTrack->mChannelMask = track->mChannelMask;
3467 fastTrack->mGeneration++;
3468 state->mTrackMask |= 1 << j;
3469 didModify = true;
3470 // no acknowledgement required for newly active tracks
3471 }
3472 // cache the combined master volume and stream type volume for fast mixer; this
3473 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3474 track->mCachedVolume = track->isMuted() ?
3475 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3476 ++fastTracks;
3477 } else {
3478 // was it previously active?
3479 if (state->mTrackMask & (1 << j)) {
3480 fastTrack->mBufferProvider = NULL;
3481 fastTrack->mGeneration++;
3482 state->mTrackMask &= ~(1 << j);
3483 didModify = true;
3484 // If any fast tracks were removed, we must wait for acknowledgement
3485 // because we're about to decrement the last sp<> on those tracks.
3486 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003487 } else {
3488 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003489 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003490 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003491 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003492 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003493 }
3494 continue;
3495 }
3496
3497 { // local variable scope to avoid goto warning
3498
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 audio_track_cblk_t* cblk = track->cblk();
3500
3501 // The first time a track is added we wait
3502 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003503 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003504 // make sure that we have enough frames to mix one full buffer.
3505 // enforce this condition only once to enable draining the buffer in case the client
3506 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003507 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003508 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003509 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003510 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003511 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003512 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003513 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003514 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003515 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003516 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003517 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003518 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003519 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3520 // the minimum track buffer size is normally twice the number of frames necessary
3521 // to fill one buffer and the resampler should not leave more than one buffer worth
3522 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003523 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003524 }
3525 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003526 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 !track->isPaused() && !track->isTerminated())
3528 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003529 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530
3531 mixedTracks++;
3532
3533 // track->mainBuffer() != mMixBuffer means there is an effect chain
3534 // connected to the track
3535 chain.clear();
3536 if (track->mainBuffer() != mMixBuffer) {
3537 chain = getEffectChain_l(track->sessionId());
3538 // Delegate volume control to effect in track effect chain if needed
3539 if (chain != 0) {
3540 tracksWithEffect++;
3541 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003542 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003543 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 }
3545 }
3546
3547
3548 int param = AudioMixer::VOLUME;
3549 if (track->mFillingUpStatus == Track::FS_FILLED) {
3550 // no ramp for the first volume setting
3551 track->mFillingUpStatus = Track::FS_ACTIVE;
3552 if (track->mState == TrackBase::RESUMING) {
3553 track->mState = TrackBase::ACTIVE;
3554 param = AudioMixer::RAMP_VOLUME;
3555 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003556 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557 } else if (cblk->server != 0) {
3558 // If the track is stopped before the first frame was mixed,
3559 // do not apply ramp
3560 param = AudioMixer::RAMP_VOLUME;
3561 }
3562
3563 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003564 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003565 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003566 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003567 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 if (track->isPausing()) {
3569 track->setPaused();
3570 }
3571 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003572
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003574 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003576 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003577 vl = vlr & 0xFFFF;
3578 vr = vlr >> 16;
3579 // track volumes come from shared memory, so can't be trusted and must be clamped
3580 if (vl > MAX_GAIN_INT) {
3581 ALOGV("Track left volume out of range: %04X", vl);
3582 vl = MAX_GAIN_INT;
3583 }
3584 if (vr > MAX_GAIN_INT) {
3585 ALOGV("Track right volume out of range: %04X", vr);
3586 vr = MAX_GAIN_INT;
3587 }
3588 // now apply the master volume and stream type volume
3589 vl = (uint32_t)(v * vl) << 12;
3590 vr = (uint32_t)(v * vr) << 12;
3591 // assuming master volume and stream type volume each go up to 1.0,
3592 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593
Glenn Kasten05632a52012-01-03 14:22:33 -08003594 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3595 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003596 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003597 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003598 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003599 }
3600 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003602 // Delegate volume control to effect in track effect chain if needed
3603 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3604 // Do not ramp volume if volume is controlled by effect
3605 param = AudioMixer::VOLUME;
3606 track->mHasVolumeController = true;
3607 } else {
3608 // force no volume ramp when volume controller was just disabled or removed
3609 // from effect chain to avoid volume spike
3610 if (track->mHasVolumeController) {
3611 param = AudioMixer::VOLUME;
3612 }
3613 track->mHasVolumeController = false;
3614 }
3615
3616 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003617 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003618 vl = (vl + (1 << 11)) >> 12;
3619 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3620 vr = (vr + (1 << 11)) >> 12;
3621 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003622
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003623 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 -07003624
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003626 mAudioMixer->setBufferProvider(name, track);
3627 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003629 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3630 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3631 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003633 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 AudioMixer::TRACK,
3635 AudioMixer::FORMAT, (void *)track->format());
3636 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003637 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003639 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003641 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 AudioMixer::RESAMPLE,
3643 AudioMixer::SAMPLE_RATE,
3644 (void *)(cblk->sampleRate));
3645 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003646 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647 AudioMixer::TRACK,
3648 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3649 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003650 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 AudioMixer::TRACK,
3652 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3653
3654 // reset retry count
3655 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003656
Eric Laurent27741442012-01-17 19:20:12 -08003657 // If one track is ready, set the mixer ready if:
3658 // - the mixer was not ready during previous round OR
3659 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003660 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003661 mixerStatus != MIXER_TRACKS_ENABLED) {
3662 mixerStatus = MIXER_TRACKS_READY;
3663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003665 // clear effect chain input buffer if an active track underruns to avoid sending
3666 // previous audio buffer again to effects
3667 chain = getEffectChain_l(track->sessionId());
3668 if (chain != 0) {
3669 chain->clearInputBuffer();
3670 }
3671
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003672 //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 -07003673 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003674 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 // We have consumed all the buffers of this track.
3676 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003677 // TODO: use actual buffer filling status instead of latency when available from
3678 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003679 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003680 size_t framesWritten =
3681 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003682 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003683 if (track->isStopped()) {
3684 track->reset();
3685 }
Eric Laurenta011e352012-03-29 15:51:43 -07003686 tracksToRemove->add(track);
3687 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003689 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 // No buffers for this track. Give it a few chances to
3691 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003692 if (--(track->mRetryCount) <= 0) {
3693 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003695 // indicate to client process that the track was disabled because of underrun;
3696 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003697 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003698 // If one track is not ready, mark the mixer also not ready if:
3699 // - the mixer was ready during previous round OR
3700 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003701 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003702 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703 mixerStatus = MIXER_TRACKS_ENABLED;
3704 }
3705 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003706 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707 }
Glenn Kasten58912562012-04-03 10:45:00 -07003708
3709 } // local variable scope to avoid goto warning
3710track_is_ready: ;
3711
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 }
3713
Glenn Kasten288ed212012-04-25 17:52:27 -07003714 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003715 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003716 if (didModify) {
3717 state->mFastTracksGen++;
3718 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3719 if (kUseFastMixer == FastMixer_Dynamic &&
3720 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3721 state->mCommand = FastMixerState::COLD_IDLE;
3722 state->mColdFutexAddr = &mFastMixerFutex;
3723 state->mColdGen++;
3724 mFastMixerFutex = 0;
3725 if (kUseFastMixer == FastMixer_Dynamic) {
3726 mNormalSink = mOutputSink;
3727 }
3728 // If we go into cold idle, need to wait for acknowledgement
3729 // so that fast mixer stops doing I/O.
3730 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003731 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003732 }
3733 sq->end();
3734 }
3735 if (sq != NULL) {
3736 sq->end(didModify);
3737 sq->push(block);
3738 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003739#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003740 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3741 mAudioWatchdog->pause();
3742 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003743#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003744
3745 // Now perform the deferred reset on fast tracks that have stopped
3746 while (resetMask != 0) {
3747 size_t i = __builtin_ctz(resetMask);
3748 ALOG_ASSERT(i < count);
3749 resetMask &= ~(1 << i);
3750 sp<Track> t = mActiveTracks[i].promote();
3751 if (t == 0) continue;
3752 Track* track = t.get();
3753 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3754 track->reset();
3755 }
Glenn Kasten58912562012-04-03 10:45:00 -07003756
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 // remove all the tracks that need to be...
3758 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003759 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 for (size_t i=0 ; i<count ; i++) {
3761 const sp<Track>& track = tracksToRemove->itemAt(i);
3762 mActiveTracks.remove(track);
3763 if (track->mainBuffer() != mMixBuffer) {
3764 chain = getEffectChain_l(track->sessionId());
3765 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003766 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003767 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
3769 }
3770 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003771 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 }
3773 }
3774 }
3775
3776 // mix buffer must be cleared if all tracks are connected to an
3777 // effect chain as in this case the mixer will not write to
3778 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003779 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3780 // FIXME as a performance optimization, should remember previous zero status
3781 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 }
3783
Glenn Kasten58912562012-04-03 10:45:00 -07003784 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003785 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003786 if (fastTracks > 0) {
3787 mixerStatus = MIXER_TRACKS_READY;
3788 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 return mixerStatus;
3790}
3791
Glenn Kasten66fcab92012-02-24 14:59:21 -08003792/*
3793The derived values that are cached:
3794 - mixBufferSize from frame count * frame size
3795 - activeSleepTime from activeSleepTimeUs()
3796 - idleSleepTime from idleSleepTimeUs()
3797 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3798 - maxPeriod from frame count and sample rate (MIXER only)
3799
3800The parameters that affect these derived values are:
3801 - frame count
3802 - frame size
3803 - sample rate
3804 - device type: A2DP or not
3805 - device latency
3806 - format: PCM or not
3807 - active sleep time
3808 - idle sleep time
3809*/
3810
3811void AudioFlinger::PlaybackThread::cacheParameters_l()
3812{
Glenn Kasten58912562012-04-03 10:45:00 -07003813 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003814 activeSleepTime = activeSleepTimeUs();
3815 idleSleepTime = idleSleepTimeUs();
3816}
3817
Eric Laurent22167852012-06-20 12:26:32 -07003818void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003819{
Steve Block3856b092011-10-20 11:56:00 +01003820 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003821 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003823
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 size_t size = mTracks.size();
3825 for (size_t i = 0; i < size; i++) {
3826 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003827 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003828 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 }
3831 }
3832}
3833
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003835int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003837 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838}
3839
3840// deleteTrackName_l() must be called with ThreadBase::mLock held
3841void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3842{
Steve Block3856b092011-10-20 11:56:00 +01003843 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 mAudioMixer->deleteTrackName(name);
3845}
3846
3847// checkForNewParameters_l() must be called with ThreadBase::mLock held
3848bool AudioFlinger::MixerThread::checkForNewParameters_l()
3849{
Glenn Kasten58912562012-04-03 10:45:00 -07003850 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3851 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 bool reconfig = false;
3853
3854 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003855
3856 if (mFastMixer != NULL) {
3857 FastMixerStateQueue *sq = mFastMixer->sq();
3858 FastMixerState *state = sq->begin();
3859 if (!(state->mCommand & FastMixerState::IDLE)) {
3860 previousCommand = state->mCommand;
3861 state->mCommand = FastMixerState::HOT_IDLE;
3862 sq->end();
3863 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3864 } else {
3865 sq->end(false /*didModify*/);
3866 }
3867 }
3868
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 status_t status = NO_ERROR;
3870 String8 keyValuePair = mNewParameters[0];
3871 AudioParameter param = AudioParameter(keyValuePair);
3872 int value;
3873
3874 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3875 reconfig = true;
3876 }
3877 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003878 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 status = BAD_VALUE;
3880 } else {
3881 reconfig = true;
3882 }
3883 }
3884 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003885 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 status = BAD_VALUE;
3887 } else {
3888 reconfig = true;
3889 }
3890 }
3891 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3892 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003893 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 // if frame count is changed after track creation
3895 if (!mTracks.isEmpty()) {
3896 status = INVALID_OPERATION;
3897 } else {
3898 reconfig = true;
3899 }
3900 }
3901 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003902#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003903 // when changing the audio output device, call addBatteryData to notify
3904 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003905 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003906 uint32_t params = 0;
3907 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003908 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003909 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3910 }
3911
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003912 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003913 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003914 // check if any other device (except speaker) is on
3915 if (value & deviceWithoutSpeaker ) {
3916 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3917 }
3918
3919 if (params != 0) {
3920 addBatteryData(params);
3921 }
3922 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003923#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003924
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 // forward device change to effects that have requested to be
3926 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003927 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003929 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 }
3931 }
3932
3933 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003934 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003935 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003937 mOutput->stream->common.standby(&mOutput->stream->common);
3938 mStandby = true;
3939 mBytesWritten = 0;
3940 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003941 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 }
3943 if (status == NO_ERROR && reconfig) {
3944 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003945 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3946 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003948 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003950 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 if (name < 0) break;
3952 mTracks[i]->mName = name;
3953 // limit track sample rate to 2 x new output sample rate
3954 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3955 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3956 }
3957 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003958 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 }
3960 }
3961
3962 mNewParameters.removeAt(0);
3963
3964 mParamStatus = status;
3965 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003966 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3967 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003968 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 }
Glenn Kasten58912562012-04-03 10:45:00 -07003970
3971 if (!(previousCommand & FastMixerState::IDLE)) {
3972 ALOG_ASSERT(mFastMixer != NULL);
3973 FastMixerStateQueue *sq = mFastMixer->sq();
3974 FastMixerState *state = sq->begin();
3975 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3976 state->mCommand = previousCommand;
3977 sq->end();
3978 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3979 }
3980
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 return reconfig;
3982}
3983
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003984void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985{
3986 const size_t SIZE = 256;
3987 char buffer[SIZE];
3988 String8 result;
3989
3990 PlaybackThread::dumpInternals(fd, args);
3991
3992 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3993 result.append(buffer);
3994 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003995
3996 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3997 FastMixerDumpState copy = mFastMixerDumpState;
3998 copy.dump(fd);
3999
Glenn Kasten39993082012-05-31 13:40:27 -07004000#ifdef STATE_QUEUE_DUMP
4001 // Similar for state queue
4002 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4003 observerCopy.dump(fd);
4004 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4005 mutatorCopy.dump(fd);
4006#endif
4007
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004008 // Write the tee output to a .wav file
4009 NBAIO_Source *teeSource = mTeeSource.get();
4010 if (teeSource != NULL) {
4011 char teePath[64];
4012 struct timeval tv;
4013 gettimeofday(&tv, NULL);
4014 struct tm tm;
4015 localtime_r(&tv.tv_sec, &tm);
4016 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
4017 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
4018 if (teeFd >= 0) {
4019 char wavHeader[44];
4020 memcpy(wavHeader,
4021 "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",
4022 sizeof(wavHeader));
4023 NBAIO_Format format = teeSource->format();
4024 unsigned channelCount = Format_channelCount(format);
4025 ALOG_ASSERT(channelCount <= FCC_2);
4026 unsigned sampleRate = Format_sampleRate(format);
4027 wavHeader[22] = channelCount; // number of channels
4028 wavHeader[24] = sampleRate; // sample rate
4029 wavHeader[25] = sampleRate >> 8;
4030 wavHeader[32] = channelCount * 2; // block alignment
4031 write(teeFd, wavHeader, sizeof(wavHeader));
4032 size_t total = 0;
4033 bool firstRead = true;
4034 for (;;) {
4035#define TEE_SINK_READ 1024
4036 short buffer[TEE_SINK_READ * FCC_2];
4037 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07004038 ssize_t actual = teeSource->read(buffer, count,
4039 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004040 bool wasFirstRead = firstRead;
4041 firstRead = false;
4042 if (actual <= 0) {
4043 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
4044 continue;
4045 }
4046 break;
4047 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07004048 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004049 write(teeFd, buffer, actual * channelCount * sizeof(short));
4050 total += actual;
4051 }
4052 lseek(teeFd, (off_t) 4, SEEK_SET);
4053 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
4054 write(teeFd, &temp, sizeof(temp));
4055 lseek(teeFd, (off_t) 40, SEEK_SET);
4056 temp = total * channelCount * sizeof(short);
4057 write(teeFd, &temp, sizeof(temp));
4058 close(teeFd);
4059 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
4060 } else {
4061 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
4062 }
4063 }
4064
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004065#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07004066 if (mAudioWatchdog != 0) {
4067 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4068 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4069 wdCopy.dump(fd);
4070 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004071#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072}
4073
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004074uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075{
Glenn Kasten58912562012-04-03 10:45:00 -07004076 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077}
4078
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004079uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004080{
Glenn Kasten58912562012-04-03 10:45:00 -07004081 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004082}
4083
Glenn Kasten66fcab92012-02-24 14:59:21 -08004084void AudioFlinger::MixerThread::cacheParameters_l()
4085{
4086 PlaybackThread::cacheParameters_l();
4087
4088 // FIXME: Relaxed timing because of a certain device that can't meet latency
4089 // Should be reduced to 2x after the vendor fixes the driver issue
4090 // increase threshold again due to low power audio mode. The way this warning
4091 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004092 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004093}
4094
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004096AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004097 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004098 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004099 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101}
4102
4103AudioFlinger::DirectOutputThread::~DirectOutputThread()
4104{
4105}
4106
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004107AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4108 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004109)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004111 sp<Track> trackToRemove;
4112
Glenn Kastenfec279f2012-03-08 07:47:15 -08004113 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114
Glenn Kasten952eeb22012-03-06 11:30:57 -08004115 // find out which tracks need to be processed
4116 if (mActiveTracks.size() != 0) {
4117 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004118 // The track died recently
4119 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120
Glenn Kasten952eeb22012-03-06 11:30:57 -08004121 Track* const track = t.get();
4122 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123
Glenn Kasten952eeb22012-03-06 11:30:57 -08004124 // The first time a track is added we wait
4125 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004126 uint32_t minFrames;
4127 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4128 minFrames = mNormalFrameCount;
4129 } else {
4130 minFrames = 1;
4131 }
4132 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004133 !track->isPaused() && !track->isTerminated())
4134 {
4135 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136
Glenn Kasten952eeb22012-03-06 11:30:57 -08004137 if (track->mFillingUpStatus == Track::FS_FILLED) {
4138 track->mFillingUpStatus = Track::FS_ACTIVE;
4139 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004140 if (track->mState == TrackBase::RESUMING) {
4141 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004142 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004143 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004144
Glenn Kasten952eeb22012-03-06 11:30:57 -08004145 // compute volume for this track
4146 float left, right;
4147 if (track->isMuted() || mMasterMute || track->isPausing() ||
4148 mStreamTypes[track->streamType()].mute) {
4149 left = right = 0;
4150 if (track->isPausing()) {
4151 track->setPaused();
4152 }
4153 } else {
4154 float typeVolume = mStreamTypes[track->streamType()].volume;
4155 float v = mMasterVolume * typeVolume;
4156 uint32_t vlr = cblk->getVolumeLR();
4157 float v_clamped = v * (vlr & 0xFFFF);
4158 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4159 left = v_clamped/MAX_GAIN;
4160 v_clamped = v * (vlr >> 16);
4161 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4162 right = v_clamped/MAX_GAIN;
4163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164
Glenn Kasten952eeb22012-03-06 11:30:57 -08004165 if (left != mLeftVolFloat || right != mRightVolFloat) {
4166 mLeftVolFloat = left;
4167 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168
Glenn Kasten952eeb22012-03-06 11:30:57 -08004169 // Convert volumes from float to 8.24
4170 uint32_t vl = (uint32_t)(left * (1 << 24));
4171 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172
Glenn Kasten952eeb22012-03-06 11:30:57 -08004173 // Delegate volume control to effect in track effect chain if needed
4174 // only one effect chain can be present on DirectOutputThread, so if
4175 // there is one, the track is connected to it
4176 if (!mEffectChains.isEmpty()) {
4177 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004178 mEffectChains[0]->setVolume_l(&vl, &vr);
4179 left = (float)vl / (1 << 24);
4180 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004181 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004182 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004183 }
4184
4185 // reset retry count
4186 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004187 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004188 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004189 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004190 // clear effect chain input buffer if an active track underruns to avoid sending
4191 // previous audio buffer again to effects
4192 if (!mEffectChains.isEmpty()) {
4193 mEffectChains[0]->clearInputBuffer();
4194 }
4195
Glenn Kasten952eeb22012-03-06 11:30:57 -08004196 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004197 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004198 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004199 // We have consumed all the buffers of this track.
4200 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004201 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004202 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004203 size_t framesWritten =
4204 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004205 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004206 if (track->isStopped()) {
4207 track->reset();
4208 }
Eric Laurenta011e352012-03-29 15:51:43 -07004209 trackToRemove = track;
4210 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004211 } else {
4212 // No buffers for this track. Give it a few chances to
4213 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004214 if (--(track->mRetryCount) <= 0) {
4215 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004216 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004218 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 }
4220 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004221 }
4222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004224 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004225 // remove all the tracks that need to be...
4226 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004227 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004228 mActiveTracks.remove(trackToRemove);
4229 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004230 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004231 trackToRemove->sessionId());
4232 mEffectChains[0]->decActiveTrackCnt();
4233 }
4234 if (trackToRemove->isTerminated()) {
4235 removeTrack_l(trackToRemove);
4236 }
4237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238
Glenn Kastenfec279f2012-03-08 07:47:15 -08004239 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004240}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
Glenn Kasten000f0e32012-03-01 17:10:56 -08004242void AudioFlinger::DirectOutputThread::threadLoop_mix()
4243{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004244 AudioBufferProvider::Buffer buffer;
4245 size_t frameCount = mFrameCount;
4246 int8_t *curBuf = (int8_t *)mMixBuffer;
4247 // output audio to hardware
4248 while (frameCount) {
4249 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004250 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004251 if (CC_UNLIKELY(buffer.raw == NULL)) {
4252 memset(curBuf, 0, frameCount * mFrameSize);
4253 break;
4254 }
4255 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4256 frameCount -= buffer.frameCount;
4257 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004258 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004259 }
4260 sleepTime = 0;
4261 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004262 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004263
Glenn Kasten000f0e32012-03-01 17:10:56 -08004264}
4265
4266void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4267{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004268 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004269 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004270 sleepTime = activeSleepTime;
4271 } else {
4272 sleepTime = idleSleepTime;
4273 }
4274 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004275 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004276 sleepTime = 0;
4277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278}
4279
4280// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004281int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4282 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283{
4284 return 0;
4285}
4286
4287// deleteTrackName_l() must be called with ThreadBase::mLock held
4288void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4289{
4290}
4291
4292// checkForNewParameters_l() must be called with ThreadBase::mLock held
4293bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4294{
4295 bool reconfig = false;
4296
4297 while (!mNewParameters.isEmpty()) {
4298 status_t status = NO_ERROR;
4299 String8 keyValuePair = mNewParameters[0];
4300 AudioParameter param = AudioParameter(keyValuePair);
4301 int value;
4302
4303 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4304 // do not accept frame count changes if tracks are open as the track buffer
4305 // size depends on frame count and correct behavior would not be garantied
4306 // if frame count is changed after track creation
4307 if (!mTracks.isEmpty()) {
4308 status = INVALID_OPERATION;
4309 } else {
4310 reconfig = true;
4311 }
4312 }
4313 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004314 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004315 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004317 mOutput->stream->common.standby(&mOutput->stream->common);
4318 mStandby = true;
4319 mBytesWritten = 0;
4320 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004321 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 }
4323 if (status == NO_ERROR && reconfig) {
4324 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004325 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 }
4327 }
4328
4329 mNewParameters.removeAt(0);
4330
4331 mParamStatus = status;
4332 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004333 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4334 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004335 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 }
4337 return reconfig;
4338}
4339
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004340uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341{
4342 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004343 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004344 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 } else {
4346 time = 10000;
4347 }
4348 return time;
4349}
4350
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004351uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352{
4353 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004354 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004355 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 } else {
4357 time = 10000;
4358 }
4359 return time;
4360}
4361
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004362uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004363{
4364 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004365 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004366 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4367 } else {
4368 time = 10000;
4369 }
4370 return time;
4371}
4372
Glenn Kasten66fcab92012-02-24 14:59:21 -08004373void AudioFlinger::DirectOutputThread::cacheParameters_l()
4374{
4375 PlaybackThread::cacheParameters_l();
4376
4377 // use shorter standby delay as on normal output to release
4378 // hardware resources as soon as possible
4379 standbyDelay = microseconds(activeSleepTime*2);
4380}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004381
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382// ----------------------------------------------------------------------------
4383
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004384AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004385 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004386 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004387 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 addOutputTrack(mainThread);
4390}
4391
4392AudioFlinger::DuplicatingThread::~DuplicatingThread()
4393{
4394 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4395 mOutputTracks[i]->destroy();
4396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004397}
4398
Glenn Kasten000f0e32012-03-01 17:10:56 -08004399void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004401 // mix buffers...
4402 if (outputsReady(outputTracks)) {
4403 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4404 } else {
4405 memset(mMixBuffer, 0, mixBufferSize);
4406 }
4407 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004408 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004409 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004410}
4411
4412void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4413{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004414 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004415 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004416 sleepTime = activeSleepTime;
4417 } else {
4418 sleepTime = idleSleepTime;
4419 }
4420 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004421 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4422 writeFrames = mNormalFrameCount;
4423 memset(mMixBuffer, 0, mixBufferSize);
4424 } else {
4425 // flush remaining overflow buffers in output tracks
4426 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004427 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004428 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004429 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004430}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431
Glenn Kasten000f0e32012-03-01 17:10:56 -08004432void AudioFlinger::DuplicatingThread::threadLoop_write()
4433{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004434 for (size_t i = 0; i < outputTracks.size(); i++) {
4435 outputTracks[i]->write(mMixBuffer, writeFrames);
4436 }
4437 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004438}
Glenn Kasten688a6402012-02-29 07:57:06 -08004439
Glenn Kasten000f0e32012-03-01 17:10:56 -08004440void AudioFlinger::DuplicatingThread::threadLoop_standby()
4441{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004442 // DuplicatingThread implements standby by stopping all tracks
4443 for (size_t i = 0; i < outputTracks.size(); i++) {
4444 outputTracks[i]->stop();
4445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446}
4447
Glenn Kastenfa26a852012-03-06 11:28:04 -08004448void AudioFlinger::DuplicatingThread::saveOutputTracks()
4449{
4450 outputTracks = mOutputTracks;
4451}
4452
4453void AudioFlinger::DuplicatingThread::clearOutputTracks()
4454{
4455 outputTracks.clear();
4456}
4457
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4459{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004460 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004461 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004462 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004463 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 this,
4465 mSampleRate,
4466 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004467 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 frameCount);
4469 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004470 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004472 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004473 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 }
4475}
4476
4477void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4478{
4479 Mutex::Autolock _l(mLock);
4480 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004481 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 mOutputTracks[i]->destroy();
4483 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004484 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 return;
4486 }
4487 }
Steve Block3856b092011-10-20 11:56:00 +01004488 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489}
4490
Glenn Kasten438b0362012-03-06 11:24:48 -08004491// caller must hold mLock
4492void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493{
4494 mWaitTimeMs = UINT_MAX;
4495 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4496 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004497 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4499 if (waitTimeMs < mWaitTimeMs) {
4500 mWaitTimeMs = waitTimeMs;
4501 }
4502 }
4503 }
4504}
4505
4506
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004507bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508{
4509 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004510 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004512 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 return false;
4514 }
4515 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004516 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004518 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 return false;
4520 }
4521 }
4522 return true;
4523}
4524
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004525uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526{
4527 return (mWaitTimeMs * 1000) / 2;
4528}
4529
Glenn Kasten66fcab92012-02-24 14:59:21 -08004530void AudioFlinger::DuplicatingThread::cacheParameters_l()
4531{
4532 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4533 updateWaitTime_l();
4534
4535 MixerThread::cacheParameters_l();
4536}
4537
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538// ----------------------------------------------------------------------------
4539
4540// TrackBase constructor must be called with AudioFlinger::mLock held
4541AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004542 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 const sp<Client>& client,
4544 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004545 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004546 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 const sp<IMemory>& sharedBuffer,
4549 int sessionId)
4550 : RefBase(),
4551 mThread(thread),
4552 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004553 mCblk(NULL),
4554 // mBuffer
4555 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 mFrameCount(0),
4557 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004558 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004560 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004562 // mChannelCount
4563 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564{
Steve Block3856b092011-10-20 11:56:00 +01004565 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566
Steve Blockb8a80522011-12-20 16:23:08 +00004567 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004568 size_t size = sizeof(audio_track_cblk_t);
4569 uint8_t channelCount = popcount(channelMask);
4570 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4571 if (sharedBuffer == 0) {
4572 size += bufferSize;
4573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004575 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 mCblkMemory = client->heap()->allocate(size);
4577 if (mCblkMemory != 0) {
4578 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004579 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 new(mCblk) audio_track_cblk_t();
4581 // clear all buffers
4582 mCblk->frameCount = frameCount;
4583 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004584// uncomment the following lines to quickly test 32-bit wraparound
4585// mCblk->user = 0xffff0000;
4586// mCblk->server = 0xffff0000;
4587// mCblk->userBase = 0xffff0000;
4588// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004589 mChannelCount = channelCount;
4590 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 if (sharedBuffer == 0) {
4592 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4593 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4594 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004595 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 mCblk->flags = CBLK_UNDERRUN_ON;
4597 } else {
4598 mBuffer = sharedBuffer->pointer();
4599 }
4600 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4601 }
4602 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004603 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 client->heap()->dump("AudioTrack");
4605 return;
4606 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004607 } else {
4608 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004609 // construct the shared structure in-place.
4610 new(mCblk) audio_track_cblk_t();
4611 // clear all buffers
4612 mCblk->frameCount = frameCount;
4613 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004614// uncomment the following lines to quickly test 32-bit wraparound
4615// mCblk->user = 0xffff0000;
4616// mCblk->server = 0xffff0000;
4617// mCblk->userBase = 0xffff0000;
4618// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004619 mChannelCount = channelCount;
4620 mChannelMask = channelMask;
4621 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4622 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4623 // Force underrun condition to avoid false underrun callback until first data is
4624 // written to buffer (other flags are cleared)
4625 mCblk->flags = CBLK_UNDERRUN_ON;
4626 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628}
4629
4630AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4631{
Glenn Kastena0d68332012-01-27 16:47:15 -08004632 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004633 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004635 } else {
4636 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 }
4638 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004639 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004640 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004641 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004643 // If the client's reference count drops to zero, the associated destructor
4644 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4645 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 mClient.clear();
4647 }
4648}
4649
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004650// AudioBufferProvider interface
4651// getNextBuffer() = 0;
4652// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4654{
Glenn Kastene0feee32011-12-13 11:53:26 -08004655 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004657 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004658 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 buffer->frameCount = 0;
4660}
4661
4662bool AudioFlinger::ThreadBase::TrackBase::step() {
4663 bool result;
4664 audio_track_cblk_t* cblk = this->cblk();
4665
4666 result = cblk->stepServer(mFrameCount);
4667 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004668 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004669 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670 }
4671 return result;
4672}
4673
4674void AudioFlinger::ThreadBase::TrackBase::reset() {
4675 audio_track_cblk_t* cblk = this->cblk();
4676
4677 cblk->user = 0;
4678 cblk->server = 0;
4679 cblk->userBase = 0;
4680 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004681 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004682 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004683}
4684
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4686 return (int)mCblk->sampleRate;
4687}
4688
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4690 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004691 size_t frameSize = cblk->frameSize;
4692 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4693 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694
4695 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004696 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4697 "TrackBase::getBuffer buffer out of range:\n"
4698 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4699 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004701 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702
4703 return bufferStart;
4704}
4705
Eric Laurenta011e352012-03-29 15:51:43 -07004706status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4707{
4708 mSyncEvents.add(event);
4709 return NO_ERROR;
4710}
4711
Mathias Agopian65ab4712010-07-14 17:59:35 -07004712// ----------------------------------------------------------------------------
4713
4714// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4715AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004716 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004718 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004720 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004721 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004722 int frameCount,
4723 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004724 int sessionId,
4725 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004726 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004727 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004728 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004729 // mRetryCount initialized later when needed
4730 mSharedBuffer(sharedBuffer),
4731 mStreamType(streamType),
4732 mName(-1), // see note below
4733 mMainBuffer(thread->mixBuffer()),
4734 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004735 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004736 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004737 mFlags(flags),
4738 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004739 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004740 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741{
4742 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4744 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004745 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004746 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004747 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004748 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004749 if (mName < 0) {
4750 ALOGE("no more track names available");
4751 return;
4752 }
4753 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004754 if (flags & IAudioFlinger::TRACK_FAST) {
4755 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4756 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4757 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004758 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004759 // FIXME This is too eager. We allocate a fast track index before the
4760 // fast track becomes active. Since fast tracks are a scarce resource,
4761 // this means we are potentially denying other more important fast tracks from
4762 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004763 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004764 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004765 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004766 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004767 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004769 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004770 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771}
4772
4773AudioFlinger::PlaybackThread::Track::~Track()
4774{
Steve Block3856b092011-10-20 11:56:00 +01004775 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004776}
4777
4778void AudioFlinger::PlaybackThread::Track::destroy()
4779{
4780 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4781 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004782 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 // we must acquire a strong reference on this Track before locking mLock
4784 // here so that the destructor is called only when exiting this function.
4785 // On the other hand, as long as Track::destroy() is only called by
4786 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4787 // this Track with its member mTrack.
4788 sp<Track> keep(this);
4789 { // scope for mLock
4790 sp<ThreadBase> thread = mThread.promote();
4791 if (thread != 0) {
4792 if (!isOutputTrack()) {
4793 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004794 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004795
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004796#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004797 // to track the speaker usage
4798 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004799#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004800 }
4801 AudioSystem::releaseOutput(thread->id());
4802 }
4803 Mutex::Autolock _l(thread->mLock);
4804 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4805 playbackThread->destroyTrack_l(this);
4806 }
4807 }
4808}
4809
Glenn Kasten288ed212012-04-25 17:52:27 -07004810/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4811{
Glenn Kastene213c862012-04-25 13:46:15 -07004812 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 -07004813 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004814}
4815
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4817{
Glenn Kasten83d86532012-01-17 14:39:34 -08004818 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004819 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004820 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004821 } else {
4822 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4823 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004824 track_state state = mState;
4825 char stateChar;
4826 switch (state) {
4827 case IDLE:
4828 stateChar = 'I';
4829 break;
4830 case TERMINATED:
4831 stateChar = 'T';
4832 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004833 case STOPPING_1:
4834 stateChar = 's';
4835 break;
4836 case STOPPING_2:
4837 stateChar = '5';
4838 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004839 case STOPPED:
4840 stateChar = 'S';
4841 break;
4842 case RESUMING:
4843 stateChar = 'R';
4844 break;
4845 case ACTIVE:
4846 stateChar = 'A';
4847 break;
4848 case PAUSING:
4849 stateChar = 'p';
4850 break;
4851 case PAUSED:
4852 stateChar = 'P';
4853 break;
Eric Laurent29864602012-05-08 18:57:51 -07004854 case FLUSHED:
4855 stateChar = 'F';
4856 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004857 default:
4858 stateChar = '?';
4859 break;
4860 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004861 char nowInUnderrun;
4862 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4863 case UNDERRUN_FULL:
4864 nowInUnderrun = ' ';
4865 break;
4866 case UNDERRUN_PARTIAL:
4867 nowInUnderrun = '<';
4868 break;
4869 case UNDERRUN_EMPTY:
4870 nowInUnderrun = '*';
4871 break;
4872 default:
4873 nowInUnderrun = '?';
4874 break;
4875 }
Glenn Kastene213c862012-04-25 13:46:15 -07004876 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4877 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004878 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 mStreamType,
4880 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004881 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004882 mSessionId,
4883 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004884 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004885 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004886 mMute,
4887 mFillingUpStatus,
4888 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004889 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4890 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004891 mCblk->server,
4892 mCblk->user,
4893 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004894 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004895 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004896 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004897 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898}
4899
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004900// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004901status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004902 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004903{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004904 audio_track_cblk_t* cblk = this->cblk();
4905 uint32_t framesReady;
4906 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004908 // Check if last stepServer failed, try to step now
4909 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004910 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4911 // Since the fast mixer is higher priority than client callback thread,
4912 // it does not result in priority inversion for client.
4913 // But a non-blocking solution would be preferable to avoid
4914 // fast mixer being unable to tryLock(), and
4915 // to avoid the extra context switches if the client wakes up,
4916 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004917 if (!step()) goto getNextBuffer_exit;
4918 ALOGV("stepServer recovered");
4919 mStepServerFailed = false;
4920 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921
Glenn Kasten288ed212012-04-25 17:52:27 -07004922 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004923 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004925 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 uint32_t s = cblk->server;
4927 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4928
4929 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4930 if (framesReq > framesReady) {
4931 framesReq = framesReady;
4932 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004933 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 framesReq = bufferEnd - s;
4935 }
4936
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004937 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004938 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004939 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004940 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941
4942getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004943 buffer->raw = NULL;
4944 buffer->frameCount = 0;
4945 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4946 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947}
4948
Glenn Kasten288ed212012-04-25 17:52:27 -07004949// Note that framesReady() takes a mutex on the control block using tryLock().
4950// This could result in priority inversion if framesReady() is called by the normal mixer,
4951// as the normal mixer thread runs at lower
4952// priority than the client's callback thread: there is a short window within framesReady()
4953// during which the normal mixer could be preempted, and the client callback would block.
4954// Another problem can occur if framesReady() is called by the fast mixer:
4955// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4956// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4957size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004958 return mCblk->framesReady();
4959}
4960
Glenn Kasten288ed212012-04-25 17:52:27 -07004961// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004963 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004964
John Grossman4ff14ba2012-02-08 16:37:41 -08004965 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004966 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4967 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004968 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 return true;
4970 }
4971 return false;
4972}
4973
Glenn Kasten3acbd052012-02-28 10:39:56 -08004974status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004975 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976{
4977 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004978 ALOGV("start(%d), calling pid %d session %d",
4979 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004980
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 sp<ThreadBase> thread = mThread.promote();
4982 if (thread != 0) {
4983 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004984 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 // here the track could be either new, or restarted
4986 // in both cases "unstop" the track
4987 if (mState == PAUSED) {
4988 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004989 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004990 } else {
4991 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004992 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 }
4994
4995 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4996 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004997 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004999
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005000#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005001 // to track the speaker usage
5002 if (status == NO_ERROR) {
5003 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
5004 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005005#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 }
5007 if (status == NO_ERROR) {
5008 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5009 playbackThread->addTrack_l(this);
5010 } else {
5011 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07005012 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 }
5014 } else {
5015 status = BAD_VALUE;
5016 }
5017 return status;
5018}
5019
5020void AudioFlinger::PlaybackThread::Track::stop()
5021{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005022 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 sp<ThreadBase> thread = mThread.promote();
5024 if (thread != 0) {
5025 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08005026 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07005027 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028 // If the track is not active (PAUSED and buffers full), flush buffers
5029 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5030 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5031 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07005032 mState = STOPPED;
5033 } else if (!isFastTrack()) {
5034 mState = STOPPED;
5035 } else {
5036 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
5037 // and then to STOPPED and reset() when presentation is complete
5038 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07005040 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 }
5042 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
5043 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005044 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005046
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005047#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005048 // to track the speaker usage
5049 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005050#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 }
5052 }
5053}
5054
5055void AudioFlinger::PlaybackThread::Track::pause()
5056{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005057 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 sp<ThreadBase> thread = mThread.promote();
5059 if (thread != 0) {
5060 Mutex::Autolock _l(thread->mLock);
5061 if (mState == ACTIVE || mState == RESUMING) {
5062 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01005063 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 if (!isOutputTrack()) {
5065 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005066 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005068
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005069#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005070 // to track the speaker usage
5071 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005072#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 }
5074 }
5075 }
5076}
5077
5078void AudioFlinger::PlaybackThread::Track::flush()
5079{
Steve Block3856b092011-10-20 11:56:00 +01005080 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005081 sp<ThreadBase> thread = mThread.promote();
5082 if (thread != 0) {
5083 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005084 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005085 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 return;
5087 }
5088 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005089 // FLUSHED state
5090 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005091 // do not reset the track if it is still in the process of being stopped or paused.
5092 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005093 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005094 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005095 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5096 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5097 reset();
5098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005099 }
5100}
5101
5102void AudioFlinger::PlaybackThread::Track::reset()
5103{
5104 // Do not reset twice to avoid discarding data written just after a flush and before
5105 // the audioflinger thread detects the track is stopped.
5106 if (!mResetDone) {
5107 TrackBase::reset();
5108 // Force underrun condition to avoid false underrun callback until first data is
5109 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005110 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5111 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112 mFillingUpStatus = FS_FILLING;
5113 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005114 if (mState == FLUSHED) {
5115 mState = IDLE;
5116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 }
5118}
5119
5120void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5121{
5122 mMute = muted;
5123}
5124
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5126{
5127 status_t status = DEAD_OBJECT;
5128 sp<ThreadBase> thread = mThread.promote();
5129 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005130 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005131 sp<AudioFlinger> af = mClient->audioFlinger();
5132
5133 Mutex::Autolock _l(af->mLock);
5134
5135 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005136
Eric Laurent109347d2012-07-02 12:31:03 -07005137 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005138 Mutex::Autolock _dl(playbackThread->mLock);
5139 Mutex::Autolock _sl(srcThread->mLock);
5140 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5141 if (chain == 0) {
5142 return INVALID_OPERATION;
5143 }
5144
5145 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5146 if (effect == 0) {
5147 return INVALID_OPERATION;
5148 }
5149 srcThread->removeEffect_l(effect);
5150 playbackThread->addEffect_l(effect);
5151 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5152 if (effect->state() == EffectModule::ACTIVE ||
5153 effect->state() == EffectModule::STOPPING) {
5154 effect->start();
5155 }
5156
5157 sp<EffectChain> dstChain = effect->chain().promote();
5158 if (dstChain == 0) {
5159 srcThread->addEffect_l(effect);
5160 return INVALID_OPERATION;
5161 }
5162 AudioSystem::unregisterEffect(effect->id());
5163 AudioSystem::registerEffect(&effect->desc(),
5164 srcThread->id(),
5165 dstChain->strategy(),
5166 AUDIO_SESSION_OUTPUT_MIX,
5167 effect->id());
5168 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005169 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 }
5171 return status;
5172}
5173
5174void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5175{
5176 mAuxEffectId = EffectId;
5177 mAuxBuffer = buffer;
5178}
5179
Eric Laurenta011e352012-03-29 15:51:43 -07005180bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5181 size_t audioHalFrames)
5182{
5183 // a track is considered presented when the total number of frames written to audio HAL
5184 // corresponds to the number of frames written when presentationComplete() is called for the
5185 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5186 if (mPresentationCompleteFrames == 0) {
5187 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5188 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5189 mPresentationCompleteFrames, audioHalFrames);
5190 }
5191 if (framesWritten >= mPresentationCompleteFrames) {
5192 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5193 mSessionId, framesWritten);
5194 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005195 return true;
5196 }
5197 return false;
5198}
5199
5200void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5201{
5202 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5203 if (mSyncEvents[i]->type() == type) {
5204 mSyncEvents[i]->trigger();
5205 mSyncEvents.removeAt(i);
5206 i--;
5207 }
5208 }
5209}
5210
Glenn Kasten58912562012-04-03 10:45:00 -07005211// implement VolumeBufferProvider interface
5212
5213uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5214{
5215 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5216 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5217 uint32_t vlr = mCblk->getVolumeLR();
5218 uint32_t vl = vlr & 0xFFFF;
5219 uint32_t vr = vlr >> 16;
5220 // track volumes come from shared memory, so can't be trusted and must be clamped
5221 if (vl > MAX_GAIN_INT) {
5222 vl = MAX_GAIN_INT;
5223 }
5224 if (vr > MAX_GAIN_INT) {
5225 vr = MAX_GAIN_INT;
5226 }
5227 // now apply the cached master volume and stream type volume;
5228 // this is trusted but lacks any synchronization or barrier so may be stale
5229 float v = mCachedVolume;
5230 vl *= v;
5231 vr *= v;
5232 // re-combine into U4.16
5233 vlr = (vr << 16) | (vl & 0xFFFF);
5234 // FIXME look at mute, pause, and stop flags
5235 return vlr;
5236}
Eric Laurenta011e352012-03-29 15:51:43 -07005237
Eric Laurent29864602012-05-08 18:57:51 -07005238status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5239{
5240 if (mState == TERMINATED || mState == PAUSED ||
5241 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5242 (mState == STOPPED)))) {
5243 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5244 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5245 event->cancel();
5246 return INVALID_OPERATION;
5247 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005248 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005249 return NO_ERROR;
5250}
5251
John Grossman4ff14ba2012-02-08 16:37:41 -08005252// timed audio tracks
5253
5254sp<AudioFlinger::PlaybackThread::TimedTrack>
5255AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005256 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005257 const sp<Client>& client,
5258 audio_stream_type_t streamType,
5259 uint32_t sampleRate,
5260 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005261 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005262 int frameCount,
5263 const sp<IMemory>& sharedBuffer,
5264 int sessionId) {
5265 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005266 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005267
Glenn Kastena0356762012-03-19 10:38:51 -07005268 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005269 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5270 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005271}
5272
5273AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005274 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005275 const sp<Client>& client,
5276 audio_stream_type_t streamType,
5277 uint32_t sampleRate,
5278 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005279 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005280 int frameCount,
5281 const sp<IMemory>& sharedBuffer,
5282 int sessionId)
5283 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005284 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005285 mQueueHeadInFlight(false),
5286 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005287 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005288 mTimedSilenceBuffer(NULL),
5289 mTimedSilenceBufferSize(0),
5290 mTimedAudioOutputOnTime(false),
5291 mMediaTimeTransformValid(false)
5292{
5293 LocalClock lc;
5294 mLocalTimeFreq = lc.getLocalFreq();
5295
5296 mLocalTimeToSampleTransform.a_zero = 0;
5297 mLocalTimeToSampleTransform.b_zero = 0;
5298 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5299 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5300 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5301 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005302
5303 mMediaTimeToSampleTransform.a_zero = 0;
5304 mMediaTimeToSampleTransform.b_zero = 0;
5305 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5306 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5307 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5308 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005309}
5310
5311AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5312 mClient->releaseTimedTrack();
5313 delete [] mTimedSilenceBuffer;
5314}
5315
5316status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5317 size_t size, sp<IMemory>* buffer) {
5318
5319 Mutex::Autolock _l(mTimedBufferQueueLock);
5320
5321 trimTimedBufferQueue_l();
5322
5323 // lazily initialize the shared memory heap for timed buffers
5324 if (mTimedMemoryDealer == NULL) {
5325 const int kTimedBufferHeapSize = 512 << 10;
5326
5327 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5328 "AudioFlingerTimed");
5329 if (mTimedMemoryDealer == NULL)
5330 return NO_MEMORY;
5331 }
5332
5333 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5334 if (newBuffer == NULL) {
5335 newBuffer = mTimedMemoryDealer->allocate(size);
5336 if (newBuffer == NULL)
5337 return NO_MEMORY;
5338 }
5339
5340 *buffer = newBuffer;
5341 return NO_ERROR;
5342}
5343
5344// caller must hold mTimedBufferQueueLock
5345void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5346 int64_t mediaTimeNow;
5347 {
5348 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5349 if (!mMediaTimeTransformValid)
5350 return;
5351
5352 int64_t targetTimeNow;
5353 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5354 ? mCCHelper.getCommonTime(&targetTimeNow)
5355 : mCCHelper.getLocalTime(&targetTimeNow);
5356
5357 if (OK != res)
5358 return;
5359
5360 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5361 &mediaTimeNow)) {
5362 return;
5363 }
5364 }
5365
John Grossman1c345192012-03-27 14:00:17 -07005366 size_t trimEnd;
5367 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005368 int64_t bufEnd;
5369
John Grossmanc95cfbb2012-04-12 11:53:11 -07005370 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5371 // We have a next buffer. Just use its PTS as the PTS of the frame
5372 // following the last frame in this buffer. If the stream is sparse
5373 // (ie, there are deliberate gaps left in the stream which should be
5374 // filled with silence by the TimedAudioTrack), then this can result
5375 // in one extra buffer being left un-trimmed when it could have
5376 // been. In general, this is not typical, and we would rather
5377 // optimized away the TS calculation below for the more common case
5378 // where PTSes are contiguous.
5379 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5380 } else {
5381 // We have no next buffer. Compute the PTS of the frame following
5382 // the last frame in this buffer by computing the duration of of
5383 // this frame in media time units and adding it to the PTS of the
5384 // buffer.
5385 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5386 / mCblk->frameSize;
5387
5388 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5389 &bufEnd)) {
5390 ALOGE("Failed to convert frame count of %lld to media time"
5391 " duration" " (scale factor %d/%u) in %s",
5392 frameCount,
5393 mMediaTimeToSampleTransform.a_to_b_numer,
5394 mMediaTimeToSampleTransform.a_to_b_denom,
5395 __PRETTY_FUNCTION__);
5396 break;
5397 }
5398 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005399 }
John Grossman9fbdee12012-03-26 17:51:46 -07005400
5401 if (bufEnd > mediaTimeNow)
5402 break;
5403
5404 // Is the buffer we want to use in the middle of a mix operation right
5405 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5406 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005407 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005408 mTrimQueueHeadOnRelease = true;
5409 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005410 }
5411
John Grossman9fbdee12012-03-26 17:51:46 -07005412 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005413 if (trimStart < trimEnd) {
5414 // Update the bookkeeping for framesReady()
5415 for (size_t i = trimStart; i < trimEnd; ++i) {
5416 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5417 }
5418
5419 // Now actually remove the buffers from the queue.
5420 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005421 }
5422}
5423
John Grossman1c345192012-03-27 14:00:17 -07005424void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5425 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005426 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5427 "%s called (reason \"%s\"), but timed buffer queue has no"
5428 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005429
5430 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5431 mTimedBufferQueue.removeAt(0);
5432}
5433
5434void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5435 const TimedBuffer& buf,
5436 const char* logTag) {
5437 uint32_t bufBytes = buf.buffer()->size();
5438 uint32_t consumedAlready = buf.position();
5439
Eric Laurentb388e532012-04-14 13:32:48 -07005440 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005441 "Bad bookkeeping while updating frames pending. Timed buffer is"
5442 " only %u bytes long, but claims to have consumed %u"
5443 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005444 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005445
5446 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005447 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5448 "Bad bookkeeping while updating frames pending. Should have at"
5449 " least %u queued frames, but we think we have only %u. (update"
5450 " reason: \"%s\")",
5451 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005452
5453 mFramesPendingInQueue -= bufFrames;
5454}
5455
John Grossman4ff14ba2012-02-08 16:37:41 -08005456status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5457 const sp<IMemory>& buffer, int64_t pts) {
5458
5459 {
5460 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5461 if (!mMediaTimeTransformValid)
5462 return INVALID_OPERATION;
5463 }
5464
5465 Mutex::Autolock _l(mTimedBufferQueueLock);
5466
John Grossman1c345192012-03-27 14:00:17 -07005467 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5468 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005469 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5470
5471 return NO_ERROR;
5472}
5473
5474status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5475 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5476
John Grossman1c345192012-03-27 14:00:17 -07005477 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5478 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5479 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005480
5481 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5482 target == TimedAudioTrack::COMMON_TIME)) {
5483 return BAD_VALUE;
5484 }
5485
5486 Mutex::Autolock lock(mMediaTimeTransformLock);
5487 mMediaTimeTransform = xform;
5488 mMediaTimeTransformTarget = target;
5489 mMediaTimeTransformValid = true;
5490
5491 return NO_ERROR;
5492}
5493
5494#define min(a, b) ((a) < (b) ? (a) : (b))
5495
5496// implementation of getNextBuffer for tracks whose buffers have timestamps
5497status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5498 AudioBufferProvider::Buffer* buffer, int64_t pts)
5499{
5500 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005501 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005502 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005503 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005504 return INVALID_OPERATION;
5505 }
5506
John Grossman4ff14ba2012-02-08 16:37:41 -08005507 Mutex::Autolock _l(mTimedBufferQueueLock);
5508
John Grossman9fbdee12012-03-26 17:51:46 -07005509 ALOG_ASSERT(!mQueueHeadInFlight,
5510 "getNextBuffer called without releaseBuffer!");
5511
John Grossman4ff14ba2012-02-08 16:37:41 -08005512 while (true) {
5513
5514 // if we have no timed buffers, then fail
5515 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005516 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005517 buffer->frameCount = 0;
5518 return NOT_ENOUGH_DATA;
5519 }
5520
5521 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5522
5523 // calculate the PTS of the head of the timed buffer queue expressed in
5524 // local time
5525 int64_t headLocalPTS;
5526 {
5527 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5528
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005529 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005530
5531 if (mMediaTimeTransform.a_to_b_denom == 0) {
5532 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005533 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005534 return NO_ERROR;
5535 }
5536
5537 int64_t transformedPTS;
5538 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5539 &transformedPTS)) {
5540 // the transform failed. this shouldn't happen, but if it does
5541 // then just drop this buffer
5542 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005543 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005544 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005545 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005546 return NO_ERROR;
5547 }
5548
5549 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5550 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5551 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005552 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005553 buffer->frameCount = 0;
5554 return INVALID_OPERATION;
5555 }
5556 } else {
5557 headLocalPTS = transformedPTS;
5558 }
5559 }
5560
5561 // adjust the head buffer's PTS to reflect the portion of the head buffer
5562 // that has already been consumed
5563 int64_t effectivePTS = headLocalPTS +
5564 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5565
5566 // Calculate the delta in samples between the head of the input buffer
5567 // queue and the start of the next output buffer that will be written.
5568 // If the transformation fails because of over or underflow, it means
5569 // that the sample's position in the output stream is so far out of
5570 // whack that it should just be dropped.
5571 int64_t sampleDelta;
5572 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5573 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005574 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5575 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005576 continue;
5577 }
5578 if (!mLocalTimeToSampleTransform.doForwardTransform(
5579 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005580 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005581 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005582 continue;
5583 }
5584
John Grossman1c345192012-03-27 14:00:17 -07005585 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5586 " sampleDelta=[%d.%08x]",
5587 head.pts(), head.position(), pts,
5588 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5589 + (sampleDelta >> 32)),
5590 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005591
5592 // if the delta between the ideal placement for the next input sample and
5593 // the current output position is within this threshold, then we will
5594 // concatenate the next input samples to the previous output
5595 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005596 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005597
5598 // if this is the first buffer of audio that we're emitting from this track
5599 // then it should be almost exactly on time.
5600 const int64_t kSampleStartupThreshold = 1LL << 32;
5601
5602 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005603 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005604 // the next input is close enough to being on time, so concatenate it
5605 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005606 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005607
John Grossman1c345192012-03-27 14:00:17 -07005608 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5609 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005610 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005611 }
5612
5613 // Looks like our output is not on time. Reset our on timed status.
5614 // Next time we mix samples from our input queue, then should be within
5615 // the StartupThreshold.
5616 mTimedAudioOutputOnTime = false;
5617 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005618 // the gap between the current output position and the proper start of
5619 // the next input sample is too big, so fill it with silence
5620 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5621
John Grossman9fbdee12012-03-26 17:51:46 -07005622 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005623 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5624 return NO_ERROR;
5625 } else {
5626 // the next input sample is late
5627 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5628 size_t onTimeSamplePosition =
5629 head.position() + lateFrames * mCblk->frameSize;
5630
5631 if (onTimeSamplePosition > head.buffer()->size()) {
5632 // all the remaining samples in the head are too late, so
5633 // drop it and move on
5634 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005635 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005636 continue;
5637 } else {
5638 // skip over the late samples
5639 head.setPosition(onTimeSamplePosition);
5640
5641 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005642 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005643
5644 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5645 return NO_ERROR;
5646 }
5647 }
5648 }
5649}
5650
5651// Yield samples from the timed buffer queue head up to the given output
5652// buffer's capacity.
5653//
5654// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005655void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005656 AudioBufferProvider::Buffer* buffer) {
5657
5658 const TimedBuffer& head = mTimedBufferQueue[0];
5659
5660 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5661 head.position());
5662
5663 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5664 mCblk->frameSize);
5665 size_t framesRequested = buffer->frameCount;
5666 buffer->frameCount = min(framesLeftInHead, framesRequested);
5667
John Grossman9fbdee12012-03-26 17:51:46 -07005668 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005669 mTimedAudioOutputOnTime = true;
5670}
5671
5672// Yield samples of silence up to the given output buffer's capacity
5673//
5674// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005675void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005676 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5677
5678 // lazily allocate a buffer filled with silence
5679 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5680 delete [] mTimedSilenceBuffer;
5681 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5682 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5683 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5684 }
5685
5686 buffer->raw = mTimedSilenceBuffer;
5687 size_t framesRequested = buffer->frameCount;
5688 buffer->frameCount = min(numFrames, framesRequested);
5689
5690 mTimedAudioOutputOnTime = false;
5691}
5692
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005693// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005694void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5695 AudioBufferProvider::Buffer* buffer) {
5696
5697 Mutex::Autolock _l(mTimedBufferQueueLock);
5698
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005699 // If the buffer which was just released is part of the buffer at the head
5700 // of the queue, be sure to update the amt of the buffer which has been
5701 // consumed. If the buffer being returned is not part of the head of the
5702 // queue, its either because the buffer is part of the silence buffer, or
5703 // because the head of the timed queue was trimmed after the mixer called
5704 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005705 if (buffer->raw == mTimedSilenceBuffer) {
5706 ALOG_ASSERT(!mQueueHeadInFlight,
5707 "Queue head in flight during release of silence buffer!");
5708 goto done;
5709 }
5710
5711 ALOG_ASSERT(mQueueHeadInFlight,
5712 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5713 " head in flight.");
5714
5715 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005716 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005717
5718 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005719 void* end = reinterpret_cast<void*>(
5720 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5721 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005722
John Grossman9fbdee12012-03-26 17:51:46 -07005723 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5724 "released buffer not within the head of the timed buffer"
5725 " queue; qHead = [%p, %p], released buffer = %p",
5726 start, end, buffer->raw);
5727
5728 head.setPosition(head.position() +
5729 (buffer->frameCount * mCblk->frameSize));
5730 mQueueHeadInFlight = false;
5731
John Grossman1c345192012-03-27 14:00:17 -07005732 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5733 "Bad bookkeeping during releaseBuffer! Should have at"
5734 " least %u queued frames, but we think we have only %u",
5735 buffer->frameCount, mFramesPendingInQueue);
5736
5737 mFramesPendingInQueue -= buffer->frameCount;
5738
John Grossman9fbdee12012-03-26 17:51:46 -07005739 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5740 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005741 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005742 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005743 }
John Grossman9fbdee12012-03-26 17:51:46 -07005744 } else {
5745 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5746 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005747 }
5748
John Grossman9fbdee12012-03-26 17:51:46 -07005749done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005750 buffer->raw = 0;
5751 buffer->frameCount = 0;
5752}
5753
Glenn Kasten288ed212012-04-25 17:52:27 -07005754size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005755 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005756 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005757}
5758
5759AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5760 : mPTS(0), mPosition(0) {}
5761
5762AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5763 const sp<IMemory>& buffer, int64_t pts)
5764 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5765
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766// ----------------------------------------------------------------------------
5767
5768// RecordTrack constructor must be called with AudioFlinger::mLock held
5769AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005770 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 const sp<Client>& client,
5772 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005773 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005774 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 int sessionId)
5777 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005778 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 mOverflow(false)
5780{
5781 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005782 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5783 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5784 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5785 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5786 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5787 } else {
5788 mCblk->frameSize = sizeof(int8_t);
5789 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 }
5791}
5792
5793AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5794{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005795 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796}
5797
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005798// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005799status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800{
5801 audio_track_cblk_t* cblk = this->cblk();
5802 uint32_t framesAvail;
5803 uint32_t framesReq = buffer->frameCount;
5804
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005805 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005806 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005808 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005809 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 }
5811
5812 framesAvail = cblk->framesAvailable_l();
5813
Glenn Kastenf6b16782011-12-15 09:51:17 -08005814 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 uint32_t s = cblk->server;
5816 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5817
5818 if (framesReq > framesAvail) {
5819 framesReq = framesAvail;
5820 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005821 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 framesReq = bufferEnd - s;
5823 }
5824
5825 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 buffer->frameCount = framesReq;
5827 return NO_ERROR;
5828 }
5829
5830getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005831 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 buffer->frameCount = 0;
5833 return NOT_ENOUGH_DATA;
5834}
5835
Glenn Kasten3acbd052012-02-28 10:39:56 -08005836status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005837 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838{
5839 sp<ThreadBase> thread = mThread.promote();
5840 if (thread != 0) {
5841 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005842 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 } else {
5844 return BAD_VALUE;
5845 }
5846}
5847
5848void AudioFlinger::RecordThread::RecordTrack::stop()
5849{
5850 sp<ThreadBase> thread = mThread.promote();
5851 if (thread != 0) {
5852 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005853 recordThread->mLock.lock();
5854 bool doStop = recordThread->stop_l(this);
5855 if (doStop) {
5856 TrackBase::reset();
5857 // Force overrun condition to avoid false overrun callback until first data is
5858 // read from buffer
5859 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5860 }
5861 recordThread->mLock.unlock();
5862 if (doStop) {
5863 AudioSystem::stopInput(recordThread->id());
5864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865 }
5866}
5867
Glenn Kasten510a3d62012-07-16 14:24:34 -07005868/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5869{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005870 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005871}
5872
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5874{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005875 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005876 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005878 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 mSessionId,
5880 mFrameCount,
5881 mState,
5882 mCblk->sampleRate,
5883 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005884 mCblk->user,
5885 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886}
5887
5888
5889// ----------------------------------------------------------------------------
5890
5891AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005892 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893 DuplicatingThread *sourceThread,
5894 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005895 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005896 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005898 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5899 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 mActive(false), mSourceThread(sourceThread)
5901{
5902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 if (mCblk != NULL) {
5904 mCblk->flags |= CBLK_DIRECTION_OUT;
5905 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 mOutBuffer.frameCount = 0;
5907 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005908 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005909 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5910 mCblk, mBuffer, mCblk->buffers,
5911 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005913 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 }
5915}
5916
5917AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5918{
5919 clearBufferQueue();
5920}
5921
Glenn Kasten3acbd052012-02-28 10:39:56 -08005922status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005923 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005925 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 if (status != NO_ERROR) {
5927 return status;
5928 }
5929
5930 mActive = true;
5931 mRetryCount = 127;
5932 return status;
5933}
5934
5935void AudioFlinger::PlaybackThread::OutputTrack::stop()
5936{
5937 Track::stop();
5938 clearBufferQueue();
5939 mOutBuffer.frameCount = 0;
5940 mActive = false;
5941}
5942
5943bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5944{
5945 Buffer *pInBuffer;
5946 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005947 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 bool outputBufferFull = false;
5949 inBuffer.frameCount = frames;
5950 inBuffer.i16 = data;
5951
5952 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5953
5954 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005955 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 sp<ThreadBase> thread = mThread.promote();
5957 if (thread != 0) {
5958 MixerThread *mixerThread = (MixerThread *)thread.get();
5959 if (mCblk->frameCount > frames){
5960 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5961 uint32_t startFrames = (mCblk->frameCount - frames);
5962 pInBuffer = new Buffer;
5963 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5964 pInBuffer->frameCount = startFrames;
5965 pInBuffer->i16 = pInBuffer->mBuffer;
5966 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5967 mBufferQueue.add(pInBuffer);
5968 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005969 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 }
5971 }
5972 }
5973 }
5974
5975 while (waitTimeLeftMs) {
5976 // First write pending buffers, then new data
5977 if (mBufferQueue.size()) {
5978 pInBuffer = mBufferQueue.itemAt(0);
5979 } else {
5980 pInBuffer = &inBuffer;
5981 }
5982
5983 if (pInBuffer->frameCount == 0) {
5984 break;
5985 }
5986
5987 if (mOutBuffer.frameCount == 0) {
5988 mOutBuffer.frameCount = pInBuffer->frameCount;
5989 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005990 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005991 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 outputBufferFull = true;
5993 break;
5994 }
5995 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5996 if (waitTimeLeftMs >= waitTimeMs) {
5997 waitTimeLeftMs -= waitTimeMs;
5998 } else {
5999 waitTimeLeftMs = 0;
6000 }
6001 }
6002
6003 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
6004 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
6005 mCblk->stepUser(outFrames);
6006 pInBuffer->frameCount -= outFrames;
6007 pInBuffer->i16 += outFrames * channelCount;
6008 mOutBuffer.frameCount -= outFrames;
6009 mOutBuffer.i16 += outFrames * channelCount;
6010
6011 if (pInBuffer->frameCount == 0) {
6012 if (mBufferQueue.size()) {
6013 mBufferQueue.removeAt(0);
6014 delete [] pInBuffer->mBuffer;
6015 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01006016 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 } else {
6018 break;
6019 }
6020 }
6021 }
6022
6023 // If we could not write all frames, allocate a buffer and queue it for next time.
6024 if (inBuffer.frameCount) {
6025 sp<ThreadBase> thread = mThread.promote();
6026 if (thread != 0 && !thread->standby()) {
6027 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
6028 pInBuffer = new Buffer;
6029 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
6030 pInBuffer->frameCount = inBuffer.frameCount;
6031 pInBuffer->i16 = pInBuffer->mBuffer;
6032 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
6033 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006036 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 }
6038 }
6039 }
6040
6041 // Calling write() with a 0 length buffer, means that no more data will be written:
6042 // If no more buffers are pending, fill output track buffer to make sure it is started
6043 // by output mixer.
6044 if (frames == 0 && mBufferQueue.size() == 0) {
6045 if (mCblk->user < mCblk->frameCount) {
6046 frames = mCblk->frameCount - mCblk->user;
6047 pInBuffer = new Buffer;
6048 pInBuffer->mBuffer = new int16_t[frames * channelCount];
6049 pInBuffer->frameCount = frames;
6050 pInBuffer->i16 = pInBuffer->mBuffer;
6051 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
6052 mBufferQueue.add(pInBuffer);
6053 } else if (mActive) {
6054 stop();
6055 }
6056 }
6057
6058 return outputBufferFull;
6059}
6060
6061status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
6062{
6063 int active;
6064 status_t result;
6065 audio_track_cblk_t* cblk = mCblk;
6066 uint32_t framesReq = buffer->frameCount;
6067
Steve Block3856b092011-10-20 11:56:00 +01006068// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 buffer->frameCount = 0;
6070
6071 uint32_t framesAvail = cblk->framesAvailable();
6072
6073
6074 if (framesAvail == 0) {
6075 Mutex::Autolock _l(cblk->lock);
6076 goto start_loop_here;
6077 while (framesAvail == 0) {
6078 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006079 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006080 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006081 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 }
6083 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6084 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006085 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 }
6087 // read the server count again
6088 start_loop_here:
6089 framesAvail = cblk->framesAvailable_l();
6090 }
6091 }
6092
6093// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006094// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095// }
6096
6097 if (framesReq > framesAvail) {
6098 framesReq = framesAvail;
6099 }
6100
6101 uint32_t u = cblk->user;
6102 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6103
Marco Nelissena1472d92012-03-30 14:36:54 -07006104 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 framesReq = bufferEnd - u;
6106 }
6107
6108 buffer->frameCount = framesReq;
6109 buffer->raw = (void *)cblk->buffer(u);
6110 return NO_ERROR;
6111}
6112
6113
6114void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6115{
6116 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117
6118 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006119 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 delete [] pBuffer->mBuffer;
6121 delete pBuffer;
6122 }
6123 mBufferQueue.clear();
6124}
6125
6126// ----------------------------------------------------------------------------
6127
6128AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6129 : RefBase(),
6130 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006131 // 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 -07006132 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006133 mPid(pid),
6134 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135{
6136 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6137}
6138
6139// Client destructor must be called with AudioFlinger::mLock held
6140AudioFlinger::Client::~Client()
6141{
6142 mAudioFlinger->removeClient_l(mPid);
6143}
6144
Glenn Kasten435dbe62012-01-30 10:15:48 -08006145sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146{
6147 return mMemoryDealer;
6148}
6149
John Grossman4ff14ba2012-02-08 16:37:41 -08006150// Reserve one of the limited slots for a timed audio track associated
6151// with this client
6152bool AudioFlinger::Client::reserveTimedTrack()
6153{
6154 const int kMaxTimedTracksPerClient = 4;
6155
6156 Mutex::Autolock _l(mTimedTrackLock);
6157
6158 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6159 ALOGW("can not create timed track - pid %d has exceeded the limit",
6160 mPid);
6161 return false;
6162 }
6163
6164 mTimedTrackCount++;
6165 return true;
6166}
6167
6168// Release a slot for a timed audio track
6169void AudioFlinger::Client::releaseTimedTrack()
6170{
6171 Mutex::Autolock _l(mTimedTrackLock);
6172 mTimedTrackCount--;
6173}
6174
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175// ----------------------------------------------------------------------------
6176
6177AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6178 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006179 sp<IBinder> binder)
6180 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181{
6182}
6183
6184AudioFlinger::NotificationClient::~NotificationClient()
6185{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186}
6187
6188void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6189{
6190 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006191 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192}
6193
6194// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006195#ifdef QCOM_HARDWARE
6196AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6197 int output, AudioSessionDescriptor *outputDesc,
6198 IDirectTrackClient* client, audio_output_flags_t outflag)
6199 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6200 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6201{
6202 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6203 createEffectThread();
6204
6205 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6206 mAudioFlinger->registerClient(mAudioFlingerClient);
6207
6208 allocateBufPool();
6209 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08006210 outputDesc->mVolumeScale = 1.0;
vivek mehta2192bc92012-12-04 11:46:08 -08006211 mDeathRecipient = new PMDeathRecipient(this);
6212 acquireWakeLock();
6213}
6214
6215AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6216 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6217 requestAndWaitForEffectsThreadExit();
6218 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6219 mAudioFlinger->deleteEffectSession();
6220 deallocateBufPool();
6221 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006222 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006223 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006224
Mingming Yin9b3dd172013-01-10 18:42:38 -08006225 {
6226 Mutex::Autolock _l(pmLock);
6227 if (mPowerManager != 0) {
6228 sp<IBinder> binder = mPowerManager->asBinder();
6229 binder->unlinkToDeath(mDeathRecipient);
6230 }
vivek mehta2192bc92012-12-04 11:46:08 -08006231 }
vivek mehta2192bc92012-12-04 11:46:08 -08006232}
6233
6234status_t AudioFlinger::DirectAudioTrack::start() {
6235 if(mIsPaused) {
6236 mIsPaused = false;
6237 mOutputDesc->stream->start(mOutputDesc->stream);
6238 }
6239 mOutputDesc->mActive = true;
6240 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6241 return NO_ERROR;
6242}
6243
6244void AudioFlinger::DirectAudioTrack::stop() {
6245 mOutputDesc->mActive = false;
6246 mOutputDesc->stream->stop(mOutputDesc->stream);
6247 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6248}
6249
6250void AudioFlinger::DirectAudioTrack::pause() {
6251 if(!mIsPaused) {
6252 mIsPaused = true;
6253 mOutputDesc->stream->pause(mOutputDesc->stream);
6254 mOutputDesc->mActive = false;
6255 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6256 }
6257}
6258
6259ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6260 ALOGV("Writing to AudioSessionOut");
6261 int isAvail = 0;
6262 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6263 if (!isAvail) {
6264 return 0;
6265 }
6266
6267 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6268 mEffectLock.lock();
6269 List<BufferInfo>::iterator it = mEffectsPool.begin();
6270 BufferInfo buf = *it;
6271 mEffectsPool.erase(it);
6272 memcpy((char *) buf.localBuf, (char *)buffer, size);
6273 buf.bytesToWrite = size;
6274 mEffectsPool.push_back(buf);
6275 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6276 mEffectLock.unlock();
6277 }
6278 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6279}
6280
6281void AudioFlinger::DirectAudioTrack::flush() {
6282 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6283 mEffectsPool.clear();
6284 mEffectsPool = mBufPool;
6285 }
6286 mOutputDesc->stream->flush(mOutputDesc->stream);
6287}
6288
6289void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6290}
6291
6292void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
Mingming Yin9b3dd172013-01-10 18:42:38 -08006293 mOutputDesc->mVolumeLeft = left;
6294 mOutputDesc->mVolumeRight = right;
Dorian Snyderf32d5702013-03-01 14:25:46 -08006295 mOutputDesc->stream->set_volume(mOutputDesc->stream,
6296 left * mOutputDesc->mVolumeScale,
6297 right* mOutputDesc->mVolumeScale);
vivek mehta2192bc92012-12-04 11:46:08 -08006298}
6299
6300int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6301 int64_t time;
6302 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6303 ALOGV("Timestamp %lld",time);
6304 return time;
6305}
6306
6307void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006308#ifdef QCOM_HARDWARE
6309 if (delayUs == 0 ) {
6310 ALOGV("Notify Audio Track of EOS event");
6311 mClient->notify(DIRECT_TRACK_EOS);
6312 } else {
6313 ALOGV("Notify Audio Track of hardware failure event");
6314 mClient->notify(DIRECT_TRACK_HW_FAIL);
6315 }
6316#else
vivek mehta2192bc92012-12-04 11:46:08 -08006317 ALOGV("Notify Audio Track of EOS event");
6318 mClient->notify(DIRECT_TRACK_EOS);
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006319#endif
vivek mehta2192bc92012-12-04 11:46:08 -08006320}
6321
6322void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6323 void *dsp_buf = NULL;
6324 void *local_buf = NULL;
6325
6326 //1. get the ion buffer information
6327 struct buf_info* buf = NULL;
6328 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6329 ALOGV("get buffer info %p",buf);
6330 if (!buf) {
6331 ALOGV("buffer is NULL");
6332 return;
6333 }
6334 int nSize = buf->bufsize;
6335 int bufferCount = buf->nBufs;
6336
6337 //2. allocate the buffer pool, allocate local buffers
6338 for (int i = 0; i < bufferCount; i++) {
6339 dsp_buf = (void *)buf->buffers[i];
6340 local_buf = malloc(nSize);
6341 memset(local_buf, 0, nSize);
6342 // Store this information for internal mapping / maintanence
6343 BufferInfo buf(local_buf, dsp_buf, nSize);
6344 buf.bytesToWrite = 0;
6345 mBufPool.push_back(buf);
6346 mEffectsPool.push_back(buf);
6347
6348 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6349 }
6350 free(buf);
6351}
6352
6353void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6354
6355 //1. Deallocate the local memory
6356 //2. Remove all the buffers from bufpool
6357 while (!mBufPool.empty()) {
6358 List<BufferInfo>::iterator it = mBufPool.begin();
6359 BufferInfo &memBuffer = *it;
6360 // free the local buffer corresponding to mem buffer
6361 if (memBuffer.localBuf) {
6362 free(memBuffer.localBuf);
6363 memBuffer.localBuf = NULL;
6364 }
6365 ALOGV("Removing from bufpool");
6366 mBufPool.erase(it);
6367 }
6368}
6369
6370status_t AudioFlinger::DirectAudioTrack::onTransact(
6371 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6372{
6373 return BnDirectTrack::onTransact(code, data, reply, flags);
6374}
6375
6376void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6377 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6378 return NULL;
6379}
6380
6381void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6382 while(1) {
6383 mEffectLock.lock();
6384 if (!mEffectConfigChanged && !mKillEffectsThread) {
6385 mEffectCv.wait(mEffectLock);
6386 }
6387
6388 if(mKillEffectsThread) {
6389 mEffectLock.unlock();
6390 break;
6391 }
6392
6393 if (mEffectConfigChanged) {
6394 mEffectConfigChanged = false;
6395 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6396 it != mEffectsPool.end(); it++) {
6397 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6398 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6399 (int16_t *)it->localBuf,
6400 (int16_t *)it->dspBuf,
6401 it->bytesToWrite);
6402 if (mEffectConfigChanged) {
6403 break;
6404 }
6405 }
6406
6407 }
6408 mEffectLock.unlock();
6409 }
6410 ALOGV("Effects thread is dead");
6411 mEffectsThreadAlive = false;
6412}
6413
6414void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6415 if (!mEffectsThreadAlive)
6416 return;
6417 mKillEffectsThread = true;
6418 mEffectCv.signal();
6419 pthread_join(mEffectsThread,NULL);
6420 ALOGV("effects thread killed");
6421}
6422
6423void AudioFlinger::DirectAudioTrack::createEffectThread() {
6424 //Create the effects thread
6425 pthread_attr_t attr;
6426 pthread_attr_init(&attr);
6427 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6428 mEffectsThreadAlive = true;
6429 ALOGV("Creating Effects Thread");
6430 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6431}
6432AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6433{
6434 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6435 pBaseClass = (DirectAudioTrack*)obj;
6436}
6437
6438void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6439 pBaseClass->mAudioFlinger.clear();
6440 ALOGW("AudioFlinger server died!");
6441}
6442
6443void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6444 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6445 ALOGV("ioConfigChanged() event %d", event);
6446 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6447 ALOGV("Received notification for change in effect module");
6448 // Seek to current media time - flush the decoded buffers with the driver
6449 pBaseClass->mEffectConfigChanged = true;
6450 // Signal effects thread to re-apply effects
6451 ALOGV("Signalling Effects Thread");
6452 pBaseClass->mEffectCv.signal();
6453
6454 }
6455 ALOGV("ioConfigChanged Out");
6456}
6457
6458void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6459{
6460 Mutex::Autolock _l(pmLock);
6461
6462 if (mPowerManager == 0) {
6463 // use checkService() to avoid blocking if power service is not up yet
6464 sp<IBinder> binder =
6465 defaultServiceManager()->checkService(String16("power"));
6466 if (binder == 0) {
6467 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6468 } else {
6469 mPowerManager = interface_cast<IPowerManager>(binder);
6470 binder->linkToDeath(mDeathRecipient);
6471 }
6472 }
6473 if (mPowerManager != 0 && mWakeLockToken == 0) {
6474 sp<IBinder> binder = new BBinder();
6475 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6476 binder,
6477 String16(lockName));
6478 if (status == NO_ERROR) {
6479 mWakeLockToken = binder;
6480 }
6481 ALOGV("acquireWakeLock() status %d", status);
6482 }
6483}
6484
6485void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6486{
6487 Mutex::Autolock _l(pmLock);
6488
6489 if (mWakeLockToken != 0) {
6490 ALOGV("releaseWakeLock()");
6491 if (mPowerManager != 0) {
6492 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6493 }
6494 mWakeLockToken.clear();
6495 }
6496}
6497
6498void AudioFlinger::DirectAudioTrack::clearPowerManager()
6499{
vivek mehta2192bc92012-12-04 11:46:08 -08006500 releaseWakeLock();
Mingming Yin9b3dd172013-01-10 18:42:38 -08006501 Mutex::Autolock _l(pmLock);
vivek mehta2192bc92012-12-04 11:46:08 -08006502 mPowerManager.clear();
6503}
6504
6505void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6506{
6507 parentClass->clearPowerManager();
6508 ALOGW("power manager service died !!!");
6509}
6510#endif
6511
6512// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513
6514AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6515 : BnAudioTrack(),
6516 mTrack(track)
6517{
6518}
6519
6520AudioFlinger::TrackHandle::~TrackHandle() {
6521 // just stop the track on deletion, associated resources
6522 // will be freed from the main thread once all pending buffers have
6523 // been played. Unless it's not in the active track list, in which
6524 // case we free everything now...
6525 mTrack->destroy();
6526}
6527
Glenn Kasten90716c52012-01-26 13:40:12 -08006528sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6529 return mTrack->getCblk();
6530}
6531
Glenn Kasten3acbd052012-02-28 10:39:56 -08006532status_t AudioFlinger::TrackHandle::start() {
6533 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534}
6535
6536void AudioFlinger::TrackHandle::stop() {
6537 mTrack->stop();
6538}
6539
6540void AudioFlinger::TrackHandle::flush() {
6541 mTrack->flush();
6542}
6543
6544void AudioFlinger::TrackHandle::mute(bool e) {
6545 mTrack->mute(e);
6546}
6547
6548void AudioFlinger::TrackHandle::pause() {
6549 mTrack->pause();
6550}
6551
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6553{
6554 return mTrack->attachAuxEffect(EffectId);
6555}
6556
John Grossman4ff14ba2012-02-08 16:37:41 -08006557status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6558 sp<IMemory>* buffer) {
6559 if (!mTrack->isTimedTrack())
6560 return INVALID_OPERATION;
6561
6562 PlaybackThread::TimedTrack* tt =
6563 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6564 return tt->allocateTimedBuffer(size, buffer);
6565}
6566
6567status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6568 int64_t pts) {
6569 if (!mTrack->isTimedTrack())
6570 return INVALID_OPERATION;
6571
6572 PlaybackThread::TimedTrack* tt =
6573 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6574 return tt->queueTimedBuffer(buffer, pts);
6575}
6576
6577status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6578 const LinearTransform& xform, int target) {
6579
6580 if (!mTrack->isTimedTrack())
6581 return INVALID_OPERATION;
6582
6583 PlaybackThread::TimedTrack* tt =
6584 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6585 return tt->setMediaTimeTransform(
6586 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6587}
6588
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589status_t AudioFlinger::TrackHandle::onTransact(
6590 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6591{
6592 return BnAudioTrack::onTransact(code, data, reply, flags);
6593}
6594
6595// ----------------------------------------------------------------------------
6596
6597sp<IAudioRecord> AudioFlinger::openRecord(
6598 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006599 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006601 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006602 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006604 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006605 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 int *sessionId,
6607 status_t *status)
6608{
6609 sp<RecordThread::RecordTrack> recordTrack;
6610 sp<RecordHandle> recordHandle;
6611 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 status_t lStatus;
6613 RecordThread *thread;
6614 size_t inFrameCount;
6615 int lSessionId;
6616
6617 // check calling permissions
6618 if (!recordingAllowed()) {
6619 lStatus = PERMISSION_DENIED;
6620 goto Exit;
6621 }
6622
6623 // add client to list
6624 { // scope for mLock
6625 Mutex::Autolock _l(mLock);
6626 thread = checkRecordThread_l(input);
6627 if (thread == NULL) {
6628 lStatus = BAD_VALUE;
6629 goto Exit;
6630 }
6631
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006632 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633
6634 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006635 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006636 lSessionId = *sessionId;
6637 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006638 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 if (sessionId != NULL) {
6640 *sessionId = lSessionId;
6641 }
6642 }
6643 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006644 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6645 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006647 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6649 // destructor is called by the TrackBase destructor with mLock held
6650 client.clear();
6651 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652 goto Exit;
6653 }
6654
6655 // return to handle to client
6656 recordHandle = new RecordHandle(recordTrack);
6657 lStatus = NO_ERROR;
6658
6659Exit:
6660 if (status) {
6661 *status = lStatus;
6662 }
6663 return recordHandle;
6664}
6665
6666// ----------------------------------------------------------------------------
6667
6668AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6669 : BnAudioRecord(),
6670 mRecordTrack(recordTrack)
6671{
6672}
6673
6674AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006675 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006676 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677}
6678
Glenn Kasten90716c52012-01-26 13:40:12 -08006679sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6680 return mRecordTrack->getCblk();
6681}
6682
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006683status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006684 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006685 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686}
6687
6688void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006689 stop_nonvirtual();
6690}
6691
6692void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006693 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006694 mRecordTrack->stop();
6695}
6696
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697status_t AudioFlinger::RecordHandle::onTransact(
6698 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6699{
6700 return BnAudioRecord::onTransact(code, data, reply, flags);
6701}
6702
6703// ----------------------------------------------------------------------------
6704
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006705AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6706 AudioStreamIn *input,
6707 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006708 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006709 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006710 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006711 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006712 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006713 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006714 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006715 mReqSampleRate(sampleRate)
6716 // mBytesRead is only meaningful while active, and so is cleared in start()
6717 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006718{
Glenn Kasten480b4682012-02-28 12:30:08 -08006719 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006720
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 readInputParameters();
6722}
6723
6724
6725AudioFlinger::RecordThread::~RecordThread()
6726{
6727 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006728 delete mResampler;
6729 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730}
6731
6732void AudioFlinger::RecordThread::onFirstRef()
6733{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006734 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735}
6736
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006737status_t AudioFlinger::RecordThread::readyToRun()
6738{
6739 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006740 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006741 return status;
6742}
6743
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744bool AudioFlinger::RecordThread::threadLoop()
6745{
6746 AudioBufferProvider::Buffer buffer;
6747 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006748 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749
Eric Laurent44d98482010-09-30 16:12:31 -07006750 nsecs_t lastWarning = 0;
6751
Glenn Kastene4e2a372012-07-23 12:55:09 -07006752 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006753 acquireWakeLock();
6754
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006755 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006756 bool readOnce = false;
6757
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 // start recording
6759 while (!exitPending()) {
6760
6761 processConfigEvents();
6762
6763 { // scope for mLock
6764 Mutex::Autolock _l(mLock);
6765 checkForNewParameters_l();
6766 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006767 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768
6769 if (exitPending()) break;
6770
Eric Laurentfeb0db62011-07-22 09:04:31 -07006771 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006772 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 // go to sleep
6774 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006775 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006776 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 continue;
6778 }
6779 if (mActiveTrack != 0) {
6780 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006781 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782 mActiveTrack.clear();
6783 mStartStopCond.broadcast();
6784 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6785 if (mReqChannelCount != mActiveTrack->channelCount()) {
6786 mActiveTrack.clear();
6787 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006788 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789 // record start succeeds only if first read from audio input
6790 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006791 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 mActiveTrack->mState = TrackBase::ACTIVE;
6793 } else {
6794 mActiveTrack.clear();
6795 }
6796 mStartStopCond.broadcast();
6797 }
6798 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006799 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6800 removeTrack_l(mActiveTrack);
6801 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802 }
6803 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006804 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805 }
6806
6807 if (mActiveTrack != 0) {
6808 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6809 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006810 unlockEffectChains(effectChains);
6811 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 continue;
6813 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006814 for (size_t i = 0; i < effectChains.size(); i ++) {
6815 effectChains[i]->process_l();
6816 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006817
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006819 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006820 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006822 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823 // no resampling
6824 while (framesOut) {
6825 size_t framesIn = mFrameCount - mRsmpInIndex;
6826 if (framesIn) {
6827 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6828 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6829 if (framesIn > framesOut)
6830 framesIn = framesOut;
6831 mRsmpInIndex += framesIn;
6832 framesOut -= framesIn;
6833 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006834 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 memcpy(dst, src, framesIn * mFrameSize);
6836 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006838 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6839 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006841 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6842 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843 }
6844 }
6845 }
6846 if (framesOut && mFrameCount == mRsmpInIndex) {
6847 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006848 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006849 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 framesOut = 0;
6851 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006852 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 mRsmpInIndex = 0;
6854 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006855 if (mBytesRead <= 0) {
6856 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6857 {
6858 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 // Force input into standby so that it tries to
6860 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006861 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006862 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 }
6864 mRsmpInIndex = mFrameCount;
6865 framesOut = 0;
6866 buffer.frameCount = 0;
6867 }
6868 }
6869 }
6870 } else {
6871 // resampling
6872
6873 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6874 // alter output frame count as if we were expecting stereo samples
6875 if (mChannelCount == 1 && mReqChannelCount == 1) {
6876 framesOut >>= 1;
6877 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006878 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6880 // are 32 bit aligned which should be always true.
6881 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006882 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006884 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6885 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006887 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 }
6889
6890 }
Eric Laurenta011e352012-03-29 15:51:43 -07006891 if (mFramestoDrop == 0) {
6892 mActiveTrack->releaseBuffer(&buffer);
6893 } else {
6894 if (mFramestoDrop > 0) {
6895 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006896 if (mFramestoDrop <= 0) {
6897 clearSyncStartEvent();
6898 }
6899 } else {
6900 mFramestoDrop += buffer.frameCount;
6901 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6902 mSyncStartEvent->isCancelled()) {
6903 ALOGW("Synced record %s, session %d, trigger session %d",
6904 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6905 mActiveTrack->sessionId(),
6906 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6907 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006908 }
6909 }
6910 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006911 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912 }
6913 // client isn't retrieving buffers fast enough
6914 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006915 if (!mActiveTrack->setOverflow()) {
6916 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006917 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006918 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006919 lastWarning = now;
6920 }
6921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 // Release the processor for a while before asking for a new buffer.
6923 // This will give the application more chance to read from the buffer and
6924 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006925 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 }
6927 }
Eric Laurentec437d82011-07-26 20:54:46 -07006928 // enable changes in effect chain
6929 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931 }
6932
Glenn Kastene4e2a372012-07-23 12:55:09 -07006933 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934
Glenn Kasten33e6e352012-07-16 15:56:57 -07006935 {
6936 Mutex::Autolock _l(mLock);
6937 mActiveTrack.clear();
6938 mStartStopCond.broadcast();
6939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940
Eric Laurentfeb0db62011-07-22 09:04:31 -07006941 releaseWakeLock();
6942
Steve Block3856b092011-10-20 11:56:00 +01006943 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944 return false;
6945}
6946
Glenn Kastene4e2a372012-07-23 12:55:09 -07006947void AudioFlinger::RecordThread::standby()
6948{
6949 if (!mStandby) {
6950 inputStandBy();
6951 mStandby = true;
6952 }
6953}
6954
6955void AudioFlinger::RecordThread::inputStandBy()
6956{
6957 mInput->stream->common.standby(&mInput->stream->common);
6958}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006959
6960sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6961 const sp<AudioFlinger::Client>& client,
6962 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006963 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006964 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006965 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006966 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006967 IAudioFlinger::track_flags_t flags,
6968 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006969 status_t *status)
6970{
6971 sp<RecordTrack> track;
6972 status_t lStatus;
6973
6974 lStatus = initCheck();
6975 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006976 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006977 goto Exit;
6978 }
6979
Glenn Kasten1879fff2012-07-11 15:36:59 -07006980 // FIXME use flags and tid similar to createTrack_l()
6981
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006982 { // scope for mLock
6983 Mutex::Autolock _l(mLock);
6984
6985 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006986 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006987
Glenn Kasten7378ca52012-01-20 13:44:40 -08006988 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006989 lStatus = NO_MEMORY;
6990 goto Exit;
6991 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006992 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006993
Eric Laurent59bd0da2011-08-01 09:52:20 -07006994 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006995 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006996 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006997 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6998 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006999 }
7000 lStatus = NO_ERROR;
7001
7002Exit:
7003 if (status) {
7004 *status = lStatus;
7005 }
7006 return track;
7007}
7008
Eric Laurenta011e352012-03-29 15:51:43 -07007009status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08007010 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07007011 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012{
Glenn Kasten58912562012-04-03 10:45:00 -07007013 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007014 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07007016
7017 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07007018 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07007019 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
7020 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
7021 triggerSession,
7022 recordTrack->sessionId(),
7023 syncStartEventCallback,
7024 this);
Eric Laurent29864602012-05-08 18:57:51 -07007025 // Sync event can be cancelled by the trigger session if the track is not in a
7026 // compatible state in which case we start record immediately
7027 if (mSyncStartEvent->isCancelled()) {
7028 clearSyncStartEvent();
7029 } else {
7030 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
7031 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
7032 }
Eric Laurenta011e352012-03-29 15:51:43 -07007033 }
7034
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08007036 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 if (mActiveTrack != 0) {
7038 if (recordTrack != mActiveTrack.get()) {
7039 status = -EBUSY;
7040 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
7041 mActiveTrack->mState = TrackBase::ACTIVE;
7042 }
7043 return status;
7044 }
7045
7046 recordTrack->mState = TrackBase::IDLE;
7047 mActiveTrack = recordTrack;
7048 mLock.unlock();
7049 status_t status = AudioSystem::startInput(mId);
7050 mLock.lock();
7051 if (status != NO_ERROR) {
7052 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07007053 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 return status;
7055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 mRsmpInIndex = mFrameCount;
7057 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08007058 if (mResampler != NULL) {
7059 mResampler->reset();
7060 }
7061 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01007063 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07007064 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08007066 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 mActiveTrack.clear();
7068 status = INVALID_OPERATION;
7069 goto startError;
7070 }
7071 mStartStopCond.wait(mLock);
7072 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007073 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 status = BAD_VALUE;
7075 goto startError;
7076 }
Steve Block3856b092011-10-20 11:56:00 +01007077 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 return status;
7079 }
7080startError:
7081 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07007082 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007083 return status;
7084}
7085
Eric Laurenta011e352012-03-29 15:51:43 -07007086void AudioFlinger::RecordThread::clearSyncStartEvent()
7087{
7088 if (mSyncStartEvent != 0) {
7089 mSyncStartEvent->cancel();
7090 }
7091 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007092 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007093}
7094
7095void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7096{
7097 sp<SyncEvent> strongEvent = event.promote();
7098
7099 if (strongEvent != 0) {
7100 RecordThread *me = (RecordThread *)strongEvent->cookie();
7101 me->handleSyncStartEvent(strongEvent);
7102 }
7103}
7104
7105void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7106{
Eric Laurent29864602012-05-08 18:57:51 -07007107 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007108 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7109 // from audio HAL
7110 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007111 }
7112}
7113
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007114bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007115 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007116 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7117 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007119 recordTrack->mState = TrackBase::PAUSING;
7120 // do not wait for mStartStopCond if exiting
7121 if (exitPending()) {
7122 return true;
7123 }
7124 mStartStopCond.wait(mLock);
7125 // if we have been restarted, recordTrack == mActiveTrack.get() here
7126 if (exitPending() || recordTrack != mActiveTrack.get()) {
7127 ALOGV("Record stopped OK");
7128 return true;
7129 }
7130 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131}
7132
Glenn Kasten106e8a42012-08-02 13:37:12 -07007133bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007134{
7135 return false;
7136}
7137
7138status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7139{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007140#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 -07007141 if (!isValidSyncEvent(event)) {
7142 return BAD_VALUE;
7143 }
7144
Glenn Kasten510a3d62012-07-16 14:24:34 -07007145 int eventSession = event->triggerSession();
7146 status_t ret = NAME_NOT_FOUND;
7147
Eric Laurenta011e352012-03-29 15:51:43 -07007148 Mutex::Autolock _l(mLock);
7149
Glenn Kasten510a3d62012-07-16 14:24:34 -07007150 for (size_t i = 0; i < mTracks.size(); i++) {
7151 sp<RecordTrack> track = mTracks[i];
7152 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007153 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007154 ret = NO_ERROR;
7155 }
Eric Laurenta011e352012-03-29 15:51:43 -07007156 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007157 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007158#else
7159 return BAD_VALUE;
7160#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007161}
7162
7163void AudioFlinger::RecordThread::RecordTrack::destroy()
7164{
7165 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7166 sp<RecordTrack> keep(this);
7167 {
7168 sp<ThreadBase> thread = mThread.promote();
7169 if (thread != 0) {
7170 if (mState == ACTIVE || mState == RESUMING) {
7171 AudioSystem::stopInput(thread->id());
7172 }
7173 AudioSystem::releaseInput(thread->id());
7174 Mutex::Autolock _l(thread->mLock);
7175 RecordThread *recordThread = (RecordThread *) thread.get();
7176 recordThread->destroyTrack_l(this);
7177 }
7178 }
7179}
7180
7181// destroyTrack_l() must be called with ThreadBase::mLock held
7182void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7183{
7184 track->mState = TrackBase::TERMINATED;
7185 // active tracks are removed by threadLoop()
7186 if (mActiveTrack != track) {
7187 removeTrack_l(track);
7188 }
7189}
7190
7191void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7192{
7193 mTracks.remove(track);
7194 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007195}
7196
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007197void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007199 dumpInternals(fd, args);
7200 dumpTracks(fd, args);
7201 dumpEffectChains(fd, args);
7202}
7203
7204void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7205{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206 const size_t SIZE = 256;
7207 char buffer[SIZE];
7208 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209
7210 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7211 result.append(buffer);
7212
7213 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7215 result.append(buffer);
7216 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7217 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007218 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219 result.append(buffer);
7220 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7221 result.append(buffer);
7222 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7223 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007225 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007227
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 write(fd, result.string(), result.size());
7229
7230 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007231}
7232
7233void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7234{
7235 const size_t SIZE = 256;
7236 char buffer[SIZE];
7237 String8 result;
7238
7239 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7240 result.append(buffer);
7241 RecordTrack::appendDumpHeader(result);
7242 for (size_t i = 0; i < mTracks.size(); ++i) {
7243 sp<RecordTrack> track = mTracks[i];
7244 if (track != 0) {
7245 track->dump(buffer, SIZE);
7246 result.append(buffer);
7247 }
7248 }
7249
7250 if (mActiveTrack != 0) {
7251 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7252 result.append(buffer);
7253 RecordTrack::appendDumpHeader(result);
7254 mActiveTrack->dump(buffer, SIZE);
7255 result.append(buffer);
7256
7257 }
7258 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259}
7260
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007261// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007262status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007263{
7264 size_t framesReq = buffer->frameCount;
7265 size_t framesReady = mFrameCount - mRsmpInIndex;
7266 int channelCount;
7267
7268 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007269 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007270 if (mBytesRead <= 0) {
7271 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7272 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 // Force input into standby so that it tries to
7274 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007275 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007276 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007278 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279 buffer->frameCount = 0;
7280 return NOT_ENOUGH_DATA;
7281 }
7282 mRsmpInIndex = 0;
7283 framesReady = mFrameCount;
7284 }
7285
7286 if (framesReq > framesReady) {
7287 framesReq = framesReady;
7288 }
7289
7290 if (mChannelCount == 1 && mReqChannelCount == 2) {
7291 channelCount = 1;
7292 } else {
7293 channelCount = 2;
7294 }
7295 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7296 buffer->frameCount = framesReq;
7297 return NO_ERROR;
7298}
7299
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007300// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7302{
7303 mRsmpInIndex += buffer->frameCount;
7304 buffer->frameCount = 0;
7305}
7306
7307bool AudioFlinger::RecordThread::checkForNewParameters_l()
7308{
7309 bool reconfig = false;
7310
7311 while (!mNewParameters.isEmpty()) {
7312 status_t status = NO_ERROR;
7313 String8 keyValuePair = mNewParameters[0];
7314 AudioParameter param = AudioParameter(keyValuePair);
7315 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007316 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317 int reqSamplingRate = mReqSampleRate;
7318 int reqChannelCount = mReqChannelCount;
7319
7320 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7321 reqSamplingRate = value;
7322 reconfig = true;
7323 }
7324 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007325 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 reconfig = true;
7327 }
7328 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007329 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 reconfig = true;
7331 }
7332 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7333 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007334 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 // if frame count is changed after track creation
7336 if (mActiveTrack != 0) {
7337 status = INVALID_OPERATION;
7338 } else {
7339 reconfig = true;
7340 }
7341 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007342 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7343 // forward device change to effects that have requested to be
7344 // aware of attached audio device.
7345 for (size_t i = 0; i < mEffectChains.size(); i++) {
7346 mEffectChains[i]->setDevice_l(value);
7347 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007348
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007349 // store input device and output device but do not forward output device to audio HAL.
7350 // Note that status is ignored by the caller for output device
7351 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007352 if (audio_is_output_devices(value)) {
7353 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007354 status = BAD_VALUE;
7355 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007356 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007357 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007358 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007359 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7360 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007361 for (size_t i = 0; i < mTracks.size(); i++) {
7362 sp<RecordTrack> track = mTracks[i];
7363 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7364 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7365 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007366 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007367 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007368 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007369 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7370 mAudioSource != (audio_source_t)value) {
7371 // forward device change to effects that have requested to be
7372 // aware of attached audio device.
7373 for (size_t i = 0; i < mEffectChains.size(); i++) {
7374 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7375 }
7376 mAudioSource = (audio_source_t)value;
7377 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007379 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007381 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007382 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7383 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 }
7385 if (reconfig) {
7386 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007387 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007388 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007389 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007390 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007391 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 status = NO_ERROR;
7393 }
7394 if (status == NO_ERROR) {
7395 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007396 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 }
7398 }
7399 }
7400
7401 mNewParameters.removeAt(0);
7402
7403 mParamStatus = status;
7404 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007405 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7406 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007407 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 }
7409 return reconfig;
7410}
7411
7412String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7413{
Dima Zavinfce7a472011-04-19 22:30:36 -07007414 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007415 String8 out_s8 = String8();
7416
7417 Mutex::Autolock _l(mLock);
7418 if (initCheck() != NO_ERROR) {
7419 return out_s8;
7420 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007421
Dima Zavin799a70e2011-04-18 16:57:27 -07007422 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007423 out_s8 = String8(s);
7424 free(s);
7425 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426}
7427
7428void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7429 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007430 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431
7432 switch (event) {
7433 case AudioSystem::INPUT_OPENED:
7434 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007435 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 desc.samplingRate = mSampleRate;
7437 desc.format = mFormat;
7438 desc.frameCount = mFrameCount;
7439 desc.latency = 0;
7440 param2 = &desc;
7441 break;
7442
7443 case AudioSystem::INPUT_CLOSED:
7444 default:
7445 break;
7446 }
7447 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7448}
7449
7450void AudioFlinger::RecordThread::readInputParameters()
7451{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007452 delete mRsmpInBuffer;
7453 // mRsmpInBuffer is always assigned a new[] below
7454 delete mRsmpOutBuffer;
7455 mRsmpOutBuffer = NULL;
7456 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007457 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458
Dima Zavin799a70e2011-04-18 16:57:27 -07007459 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007460 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007461 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007462 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007463 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007464 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007466 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7468
Glenn Kasten53d76db2012-03-08 12:32:47 -08007469 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007470 {
7471 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007472 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7473 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 if (mChannelCount == 1 && mReqChannelCount == 2) {
7475 channelCount = 1;
7476 } else {
7477 channelCount = 2;
7478 }
7479 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7480 mResampler->setSampleRate(mSampleRate);
7481 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7482 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7483
7484 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7485 if (mChannelCount == 1 && mReqChannelCount == 1) {
7486 mFrameCount >>= 1;
7487 }
7488
7489 }
7490 mRsmpInIndex = mFrameCount;
7491}
7492
7493unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7494{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007495 Mutex::Autolock _l(mLock);
7496 if (initCheck() != NO_ERROR) {
7497 return 0;
7498 }
7499
Dima Zavin799a70e2011-04-18 16:57:27 -07007500 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501}
7502
Glenn Kasten106e8a42012-08-02 13:37:12 -07007503uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007504{
7505 Mutex::Autolock _l(mLock);
7506 uint32_t result = 0;
7507 if (getEffectChain_l(sessionId) != 0) {
7508 result = EFFECT_SESSION;
7509 }
7510
Glenn Kasten510a3d62012-07-16 14:24:34 -07007511 for (size_t i = 0; i < mTracks.size(); ++i) {
7512 if (sessionId == mTracks[i]->sessionId()) {
7513 result |= TRACK_SESSION;
7514 break;
7515 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007516 }
7517
7518 return result;
7519}
7520
Glenn Kasten106e8a42012-08-02 13:37:12 -07007521KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007522{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007523 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007524 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007525 for (size_t j = 0; j < mTracks.size(); ++j) {
7526 sp<RecordThread::RecordTrack> track = mTracks[j];
7527 int sessionId = track->sessionId();
7528 if (ids.indexOfKey(sessionId) < 0) {
7529 ids.add(sessionId, true);
7530 }
7531 }
7532 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007533}
7534
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007535AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7536{
7537 Mutex::Autolock _l(mLock);
7538 AudioStreamIn *input = mInput;
7539 mInput = NULL;
7540 return input;
7541}
7542
7543// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007544audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007545{
7546 if (mInput == NULL) {
7547 return NULL;
7548 }
7549 return &mInput->stream->common;
7550}
7551
7552
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553// ----------------------------------------------------------------------------
7554
Eric Laurenta4c5a552012-03-29 10:12:40 -07007555audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7556{
7557 if (!settingsAllowed()) {
7558 return 0;
7559 }
7560 Mutex::Autolock _l(mLock);
7561 return loadHwModule_l(name);
7562}
7563
7564// loadHwModule_l() must be called with AudioFlinger::mLock held
7565audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7566{
7567 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7568 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7569 ALOGW("loadHwModule() module %s already loaded", name);
7570 return mAudioHwDevs.keyAt(i);
7571 }
7572 }
7573
Eric Laurenta4c5a552012-03-29 10:12:40 -07007574 audio_hw_device_t *dev;
7575
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007576 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007577 if (rc) {
7578 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7579 return 0;
7580 }
7581
7582 mHardwareStatus = AUDIO_HW_INIT;
7583 rc = dev->init_check(dev);
7584 mHardwareStatus = AUDIO_HW_IDLE;
7585 if (rc) {
7586 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7587 return 0;
7588 }
7589
John Grossmanee578c02012-07-23 17:05:46 -07007590 // Check and cache this HAL's level of support for master mute and master
7591 // volume. If this is the first HAL opened, and it supports the get
7592 // methods, use the initial values provided by the HAL as the current
7593 // master mute and volume settings.
7594
7595 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7596 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007597 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007598
madmack2f8d3672013-01-14 21:19:20 -05007599#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007600 if (0 == mAudioHwDevs.size()) {
7601 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7602 if (NULL != dev->get_master_volume) {
7603 float mv;
7604 if (OK == dev->get_master_volume(dev, &mv)) {
7605 mMasterVolume = mv;
7606 }
7607 }
7608
7609 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7610 if (NULL != dev->get_master_mute) {
7611 bool mm;
7612 if (OK == dev->get_master_mute(dev, &mm)) {
7613 mMasterMute = mm;
7614 }
7615 }
7616 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007617#endif
John Grossmanee578c02012-07-23 17:05:46 -07007618
Eric Laurenta4c5a552012-03-29 10:12:40 -07007619 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007620 if ((NULL != dev->set_master_volume) &&
7621 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7622 flags = static_cast<AudioHwDevice::Flags>(flags |
7623 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7624 }
7625
madmack2f8d3672013-01-14 21:19:20 -05007626#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007627 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7628 if ((NULL != dev->set_master_mute) &&
7629 (OK == dev->set_master_mute(dev, mMasterMute))) {
7630 flags = static_cast<AudioHwDevice::Flags>(flags |
7631 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7632 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007633#endif
John Grossmanee578c02012-07-23 17:05:46 -07007634
Eric Laurenta4c5a552012-03-29 10:12:40 -07007635 mHardwareStatus = AUDIO_HW_IDLE;
7636 }
7637
7638 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007639 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007640
7641 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007642 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007643
7644 return handle;
7645
7646}
7647
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007648// ----------------------------------------------------------------------------
7649
7650int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7651{
7652 Mutex::Autolock _l(mLock);
7653 PlaybackThread *thread = primaryPlaybackThread_l();
7654 return thread != NULL ? thread->sampleRate() : 0;
7655}
7656
7657int32_t AudioFlinger::getPrimaryOutputFrameCount()
7658{
7659 Mutex::Autolock _l(mLock);
7660 PlaybackThread *thread = primaryPlaybackThread_l();
7661 return thread != NULL ? thread->frameCountHAL() : 0;
7662}
7663
7664// ----------------------------------------------------------------------------
7665
Eric Laurenta4c5a552012-03-29 10:12:40 -07007666audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7667 audio_devices_t *pDevices,
7668 uint32_t *pSamplingRate,
7669 audio_format_t *pFormat,
7670 audio_channel_mask_t *pChannelMask,
7671 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007672 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673{
7674 status_t status;
7675 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007676 struct audio_config config = {
7677 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7678 channel_mask: pChannelMask ? *pChannelMask : 0,
7679 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7680 };
7681 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007682 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683
Eric Laurenta4c5a552012-03-29 10:12:40 -07007684 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7685 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007686 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007687 config.sample_rate,
7688 config.format,
7689 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007690 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691
7692 if (pDevices == NULL || *pDevices == 0) {
7693 return 0;
7694 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007695
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 Mutex::Autolock _l(mLock);
7697
Eric Laurenta4c5a552012-03-29 10:12:40 -07007698 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007699 if (outHwDev == NULL)
7700 return 0;
7701
John Grossmanee578c02012-07-23 17:05:46 -07007702 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007703 audio_io_handle_t id = nextUniqueId();
7704
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007705 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007706
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007707#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007708 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007709 id,
7710 *pDevices,
7711 (audio_output_flags_t)flags,
7712 &config,
7713 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007714#else
7715 status = hwDevHal->open_output_stream(hwDevHal,
7716 *pDevices,
7717 (int *)&config.format,
7718 &config.channel_mask,
7719 &config.sample_rate,
7720 &outStream);
7721 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7722 flags = (audio_output_flags_t)newflags;
7723#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007724
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007725 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007727 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007728 config.sample_rate,
7729 config.format,
7730 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007731 status);
7732
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007733 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007734 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007735#ifdef QCOM_HARDWARE
7736 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7737 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7738 desc->mActive = true;
7739 //TODO: no stream type
7740 //desc->mStreamType = streamType;
7741 desc->mVolumeLeft = 1.0;
7742 desc->mVolumeRight = 1.0;
7743 desc->device = *pDevices;
7744 mDirectAudioTracks.add(id, desc);
7745 } else
7746#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007747 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007748 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7749 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007751 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 } else {
7753 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007754 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007755 }
vivek mehta2192bc92012-12-04 11:46:08 -08007756#ifdef QCOM_HARDWARE
7757 if (thread != NULL)
7758#endif
7759 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760
Dorian Snyderf32d5702013-03-01 14:25:46 -08007761#ifdef QCOM_HARDWARE
7762 // if the device is a A2DP, then this is an A2DP Output
7763 if ( true == audio_is_a2dp_device((audio_devices_t) *pDevices) )
7764 {
7765 mA2DPHandle = id;
7766 ALOGV("A2DP device activated. The handle is set to %d", mA2DPHandle);
7767 }
7768#endif
7769
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007770 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7771 if (pFormat != NULL) *pFormat = config.format;
7772 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007773#ifdef QCOM_HARDWARE
7774 if (thread != NULL) {
7775#endif
7776 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7777 // notify client processes of the new output creation
7778 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7779#ifdef QCOM_HARDWARE
7780 }
7781 else {
7782 *pLatencyMs = 0;
7783 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7784 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7785 *pLatencyMs = desc->stream->get_latency(desc->stream);
7786 }
7787 }
7788#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007789 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007790 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007791 ALOGI("Using module %d has the primary audio interface", module);
7792 mPrimaryHardwareDev = outHwDev;
7793
7794 AutoMutex lock(mHardwareLock);
7795 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007796 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007797 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007798 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 return id;
7800 }
7801
7802 return 0;
7803}
7804
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007805audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7806 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807{
7808 Mutex::Autolock _l(mLock);
7809 MixerThread *thread1 = checkMixerThread_l(output1);
7810 MixerThread *thread2 = checkMixerThread_l(output2);
7811
7812 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007813 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814 return 0;
7815 }
7816
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007817 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7819 thread->addOutputTrack(thread2);
7820 mPlaybackThreads.add(id, thread);
7821 // notify client processes of the new output creation
7822 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7823 return id;
7824}
7825
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007826status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007827{
Glenn Kastend96c5722012-04-25 13:44:49 -07007828 return closeOutput_nonvirtual(output);
7829}
7830
7831status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7832{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 // keep strong reference on the playback thread so that
7834 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007835#ifdef QCOM_HARDWARE
7836 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7837 if (desc) {
7838 ALOGV("Closing DirectTrack output %d", output);
7839 desc->mActive = false;
7840 desc->stream->common.standby(&desc->stream->common);
7841 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7842 desc->trackRefPtr = NULL;
7843 mDirectAudioTracks.removeItem(output);
7844 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7845 delete desc;
7846 return NO_ERROR;
7847 }
7848#endif
7849
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007850 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007851 {
7852 Mutex::Autolock _l(mLock);
7853 thread = checkPlaybackThread_l(output);
7854 if (thread == NULL) {
7855 return BAD_VALUE;
7856 }
7857
Steve Block3856b092011-10-20 11:56:00 +01007858 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007860 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007862 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7864 dupThread->removeOutputTrack((MixerThread *)thread.get());
7865 }
7866 }
7867 }
Glenn Kastena1117922012-01-26 10:53:32 -08007868 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869 mPlaybackThreads.removeItem(output);
Dorian Snyderf32d5702013-03-01 14:25:46 -08007870#ifdef QCOM_HARDWARE
7871 if (mA2DPHandle == output)
7872 {
7873 mA2DPHandle = -1;
7874 ALOGV("A2DP OutputClosed Notifying Client");
7875 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
7876 }
7877#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 }
7879 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007880 // The thread entity (active unit of execution) is no longer running here,
7881 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007883 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007884 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007885 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007886 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007887 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007888 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 }
7890 return NO_ERROR;
7891}
7892
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007893status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894{
7895 Mutex::Autolock _l(mLock);
7896 PlaybackThread *thread = checkPlaybackThread_l(output);
7897
7898 if (thread == NULL) {
7899 return BAD_VALUE;
7900 }
7901
Steve Block3856b092011-10-20 11:56:00 +01007902 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 thread->suspend();
7904
7905 return NO_ERROR;
7906}
7907
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007908status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909{
7910 Mutex::Autolock _l(mLock);
7911 PlaybackThread *thread = checkPlaybackThread_l(output);
7912
7913 if (thread == NULL) {
7914 return BAD_VALUE;
7915 }
7916
Steve Block3856b092011-10-20 11:56:00 +01007917 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918
7919 thread->restore();
7920
7921 return NO_ERROR;
7922}
7923
Eric Laurenta4c5a552012-03-29 10:12:40 -07007924audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7925 audio_devices_t *pDevices,
7926 uint32_t *pSamplingRate,
7927 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007928 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007929{
7930 status_t status;
7931 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007932 struct audio_config config = {
7933 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7934 channel_mask: pChannelMask ? *pChannelMask : 0,
7935 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7936 };
7937 uint32_t reqSamplingRate = config.sample_rate;
7938 audio_format_t reqFormat = config.format;
7939 audio_channel_mask_t reqChannels = config.channel_mask;
7940 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007941 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942
7943 if (pDevices == NULL || *pDevices == 0) {
7944 return 0;
7945 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007946
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 Mutex::Autolock _l(mLock);
7948
Eric Laurenta4c5a552012-03-29 10:12:40 -07007949 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007950 if (inHwDev == NULL)
7951 return 0;
7952
John Grossmanee578c02012-07-23 17:05:46 -07007953 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007954 audio_io_handle_t id = nextUniqueId();
7955
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007956#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007957 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007958 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007959#else
7960 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7961 (int *)&config.format,
7962 &config.channel_mask,
7963 &config.sample_rate, (audio_in_acoustics_t)0,
7964 &inStream);
7965#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007966 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007967 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007968 config.sample_rate,
7969 config.format,
7970 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007971 status);
7972
7973 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7974 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7975 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007976 if (status == BAD_VALUE &&
7977 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7978 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007979 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007980 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007981 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007982#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007983 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007984#else
7985 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7986 (int *)&config.format,
7987 &config.channel_mask,
7988 &config.sample_rate, (audio_in_acoustics_t)0,
7989 &inStream);
7990#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 }
7992
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007993 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007994 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7995
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007996 // Start record thread
7997 // RecorThread require both input and output device indication to forward to audio
7998 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007999 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008000 thread = new RecordThread(this,
8001 input,
8002 reqSamplingRate,
8003 reqChannels,
8004 id,
8005 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008006 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01008007 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08008008 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07008009 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07008010 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012 // notify client processes of the new input creation
8013 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
8014 return id;
8015 }
8016
8017 return 0;
8018}
8019
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008020status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021{
Glenn Kastend96c5722012-04-25 13:44:49 -07008022 return closeInput_nonvirtual(input);
8023}
8024
8025status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
8026{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 // keep strong reference on the record thread so that
8028 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008029 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030 {
8031 Mutex::Autolock _l(mLock);
8032 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07008033 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008034 return BAD_VALUE;
8035 }
8036
Steve Block3856b092011-10-20 11:56:00 +01008037 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08008038 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039 mRecordThreads.removeItem(input);
8040 }
8041 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08008042 // The thread entity (active unit of execution) is no longer running here,
8043 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008045 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08008046 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008047 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07008048 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07008049 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008050
8051 return NO_ERROR;
8052}
8053
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008054status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055{
8056 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008057 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008058
8059 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8060 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07008061 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07008062 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08008063#ifdef QCOM_HARDWARE
8064 if ( mA2DPHandle == output ) {
8065 ALOGV("A2DP Activated and hence notifying the client");
8066 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &output);
8067 }
8068#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008069
8070 return NO_ERROR;
8071}
8072
8073
8074int AudioFlinger::newAudioSessionId()
8075{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008076 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077}
8078
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008079void AudioFlinger::acquireAudioSessionId(int audioSession)
8080{
8081 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008082 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008083 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008084 size_t num = mAudioSessionRefs.size();
8085 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008086 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008087 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8088 ref->mCnt++;
8089 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008090 return;
8091 }
8092 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08008093 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
8094 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008095}
8096
8097void AudioFlinger::releaseAudioSessionId(int audioSession)
8098{
8099 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008100 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008101 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008102 size_t num = mAudioSessionRefs.size();
8103 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008104 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008105 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8106 ref->mCnt--;
8107 ALOGV(" decremented refcount to %d", ref->mCnt);
8108 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008109 mAudioSessionRefs.removeAt(i);
8110 delete ref;
8111 purgeStaleEffects_l();
8112 }
8113 return;
8114 }
8115 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008116 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008117}
8118
8119void AudioFlinger::purgeStaleEffects_l() {
8120
Steve Block3856b092011-10-20 11:56:00 +01008121 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008122
8123 Vector< sp<EffectChain> > chains;
8124
8125 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8126 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8127 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8128 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008129 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8130 chains.push(ec);
8131 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008132 }
8133 }
8134 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8135 sp<RecordThread> t = mRecordThreads.valueAt(i);
8136 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8137 sp<EffectChain> ec = t->mEffectChains[j];
8138 chains.push(ec);
8139 }
8140 }
8141
8142 for (size_t i = 0; i < chains.size(); i++) {
8143 sp<EffectChain> ec = chains[i];
8144 int sessionid = ec->sessionId();
8145 sp<ThreadBase> t = ec->mThread.promote();
8146 if (t == 0) {
8147 continue;
8148 }
8149 size_t numsessionrefs = mAudioSessionRefs.size();
8150 bool found = false;
8151 for (size_t k = 0; k < numsessionrefs; k++) {
8152 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008153 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008154 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008155 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008156 found = true;
8157 break;
8158 }
8159 }
8160 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008161 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008162 // remove all effects from the chain
8163 while (ec->mEffects.size()) {
8164 sp<EffectModule> effect = ec->mEffects[0];
8165 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008166 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008167 if (effect->purgeHandles()) {
8168 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008169 }
8170 AudioSystem::unregisterEffect(effect->id());
8171 }
8172 }
8173 }
8174 return;
8175}
8176
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008178AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008179{
Glenn Kastena1117922012-01-26 10:53:32 -08008180 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181}
8182
8183// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008184AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185{
8186 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008187 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188}
8189
8190// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008191AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008192{
Glenn Kastena1117922012-01-26 10:53:32 -08008193 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194}
8195
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008196uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008197{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008198 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199}
8200
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008201AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008202{
8203 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8204 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008205 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008206 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008207 return thread;
8208 }
8209 }
8210 return NULL;
8211}
8212
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008213audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008214{
8215 PlaybackThread *thread = primaryPlaybackThread_l();
8216
8217 if (thread == NULL) {
8218 return 0;
8219 }
8220
Eric Laurentf1c04f92012-08-28 14:26:53 -07008221 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008222}
8223
Eric Laurenta011e352012-03-29 15:51:43 -07008224sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8225 int triggerSession,
8226 int listenerSession,
8227 sync_event_callback_t callBack,
8228 void *cookie)
8229{
8230 Mutex::Autolock _l(mLock);
8231
8232 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8233 status_t playStatus = NAME_NOT_FOUND;
8234 status_t recStatus = NAME_NOT_FOUND;
8235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8236 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8237 if (playStatus == NO_ERROR) {
8238 return event;
8239 }
8240 }
8241 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8242 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8243 if (recStatus == NO_ERROR) {
8244 return event;
8245 }
8246 }
8247 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8248 mPendingSyncEvents.add(event);
8249 } else {
8250 ALOGV("createSyncEvent() invalid event %d", event->type());
8251 event.clear();
8252 }
8253 return event;
8254}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008255
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256// ----------------------------------------------------------------------------
8257// Effect management
8258// ----------------------------------------------------------------------------
8259
8260
Glenn Kastenf587ba52012-01-26 16:25:10 -08008261status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262{
8263 Mutex::Autolock _l(mLock);
8264 return EffectQueryNumberEffects(numEffects);
8265}
8266
Glenn Kastenf587ba52012-01-26 16:25:10 -08008267status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268{
8269 Mutex::Autolock _l(mLock);
8270 return EffectQueryEffect(index, descriptor);
8271}
8272
Glenn Kasten5e92a782012-01-30 07:40:52 -08008273status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008274 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008275{
8276 Mutex::Autolock _l(mLock);
8277 return EffectGetDescriptor(pUuid, descriptor);
8278}
8279
8280
Mathias Agopian65ab4712010-07-14 17:59:35 -07008281sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8282 effect_descriptor_t *pDesc,
8283 const sp<IEffectClient>& effectClient,
8284 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008285 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286 int sessionId,
8287 status_t *status,
8288 int *id,
8289 int *enabled)
8290{
8291 status_t lStatus = NO_ERROR;
8292 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008295 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008296 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008297
8298 if (pDesc == NULL) {
8299 lStatus = BAD_VALUE;
8300 goto Exit;
8301 }
8302
Eric Laurent84e9a102010-09-23 16:10:16 -07008303 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008304 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008305 lStatus = PERMISSION_DENIED;
8306 goto Exit;
8307 }
8308
Dima Zavinfce7a472011-04-19 22:30:36 -07008309 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008310 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008311 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008312 lStatus = PERMISSION_DENIED;
8313 goto Exit;
8314 }
8315
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008316 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008317 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008318 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008319 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008320 lStatus = BAD_VALUE;
8321 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008322 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008323 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008324 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008325 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008326 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008327 }
8328 }
8329
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 {
8331 Mutex::Autolock _l(mLock);
8332
Mathias Agopian65ab4712010-07-14 17:59:35 -07008333
8334 if (!EffectIsNullUuid(&pDesc->uuid)) {
8335 // if uuid is specified, request effect descriptor
8336 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8337 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008338 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 goto Exit;
8340 }
8341 } else {
8342 // if uuid is not specified, look for an available implementation
8343 // of the required type in effect factory
8344 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008345 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346 lStatus = BAD_VALUE;
8347 goto Exit;
8348 }
8349 uint32_t numEffects = 0;
8350 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008351 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008352 bool found = false;
8353
8354 lStatus = EffectQueryNumberEffects(&numEffects);
8355 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008356 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 goto Exit;
8358 }
8359 for (uint32_t i = 0; i < numEffects; i++) {
8360 lStatus = EffectQueryEffect(i, &desc);
8361 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008362 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008363 continue;
8364 }
8365 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8366 // If matching type found save effect descriptor. If the session is
8367 // 0 and the effect is not auxiliary, continue enumeration in case
8368 // an auxiliary version of this effect type is available
8369 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008370 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008371 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8373 break;
8374 }
8375 }
8376 }
8377 if (!found) {
8378 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008379 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380 goto Exit;
8381 }
8382 // For same effect type, chose auxiliary version over insert version if
8383 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008384 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008385 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008386 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 }
8388 }
8389
8390 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008391 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8393 lStatus = INVALID_OPERATION;
8394 goto Exit;
8395 }
8396
Eric Laurent59255e42011-07-27 19:49:51 -07008397 // check recording permission for visualizer
8398 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8399 !recordingAllowed()) {
8400 lStatus = PERMISSION_DENIED;
8401 goto Exit;
8402 }
8403
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008405 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008406
8407 // If output is not specified try to find a matching audio session ID in one of the
8408 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008409 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8410 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008411 // Note: io is never 0 when creating an effect on an input
8412 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008413 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008414 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8415 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008416 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008417 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008420 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008421 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8422 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8423 io = mRecordThreads.keyAt(i);
8424 break;
8425 }
8426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008427 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008428 // If no output thread contains the requested session ID, default to
8429 // first output. The effect chain will be moved to the correct output
8430 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008431 if (io == 0 && mPlaybackThreads.size()) {
8432 io = mPlaybackThreads.keyAt(0);
8433 }
Steve Block3856b092011-10-20 11:56:00 +01008434 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008435 }
8436 ThreadBase *thread = checkRecordThread_l(io);
8437 if (thread == NULL) {
8438 thread = checkPlaybackThread_l(io);
8439 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008440 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008441 lStatus = BAD_VALUE;
8442 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008445
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008446 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008447
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008448 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008449 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8450 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008451 if (handle != 0 && id != NULL) {
8452 *id = handle->id();
8453 }
8454 }
8455
8456Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008457 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008458 *status = lStatus;
8459 }
8460 return handle;
8461}
8462
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008463status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8464 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008465{
Steve Block3856b092011-10-20 11:56:00 +01008466 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008467 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008468 Mutex::Autolock _l(mLock);
8469 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008470 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008471 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008472 }
Eric Laurentde070132010-07-13 04:45:46 -07008473 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8474 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008475 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008476 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477 }
Eric Laurentde070132010-07-13 04:45:46 -07008478 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8479 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008480 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008481 return BAD_VALUE;
8482 }
8483
8484 Mutex::Autolock _dl(dstThread->mLock);
8485 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008486 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008487
Mathias Agopian65ab4712010-07-14 17:59:35 -07008488 return NO_ERROR;
8489}
8490
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008491// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008492status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008493 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008494 AudioFlinger::PlaybackThread *dstThread,
8495 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008496{
Steve Block3856b092011-10-20 11:56:00 +01008497 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008498 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008499
Eric Laurent59255e42011-07-27 19:49:51 -07008500 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008501 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008502 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008503 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008504 return INVALID_OPERATION;
8505 }
8506
Eric Laurent39e94f82010-07-28 01:32:47 -07008507 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008508 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008509 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008510 // removed.
8511 srcThread->removeEffectChain_l(chain);
8512
8513 // transfer all effects one by one so that new effect chain is created on new thread with
8514 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008515 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008516 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008517 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008518 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8519 while (effect != 0) {
8520 srcThread->removeEffect_l(effect);
8521 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008522 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8523 if (effect->state() == EffectModule::ACTIVE ||
8524 effect->state() == EffectModule::STOPPING) {
8525 effect->start();
8526 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008527 // if the move request is not received from audio policy manager, the effect must be
8528 // re-registered with the new strategy and output
8529 if (dstChain == 0) {
8530 dstChain = effect->chain().promote();
8531 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008532 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008533 srcThread->addEffect_l(effect);
8534 return NO_INIT;
8535 }
8536 strategy = dstChain->strategy();
8537 }
8538 if (reRegister) {
8539 AudioSystem::unregisterEffect(effect->id());
8540 AudioSystem::registerEffect(&effect->desc(),
8541 dstOutput,
8542 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008543 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008544 effect->id());
8545 }
Eric Laurentde070132010-07-13 04:45:46 -07008546 effect = chain->getEffectFromId_l(0);
8547 }
8548
8549 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550}
8551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008552
Mathias Agopian65ab4712010-07-14 17:59:35 -07008553// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008554sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008555 const sp<AudioFlinger::Client>& client,
8556 const sp<IEffectClient>& effectClient,
8557 int32_t priority,
8558 int sessionId,
8559 effect_descriptor_t *desc,
8560 int *enabled,
8561 status_t *status
8562 )
8563{
8564 sp<EffectModule> effect;
8565 sp<EffectHandle> handle;
8566 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008567 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008568 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 bool effectCreated = false;
8570 bool effectRegistered = false;
8571
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008572 lStatus = initCheck();
8573 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008574 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 goto Exit;
8576 }
8577
8578 // Do not allow effects with session ID 0 on direct output or duplicating threads
8579 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008580 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008581 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008582 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008583 lStatus = BAD_VALUE;
8584 goto Exit;
8585 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008586 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008587 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008588 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008589 desc->name, desc->flags, mType);
8590 lStatus = BAD_VALUE;
8591 goto Exit;
8592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593
Steve Block3856b092011-10-20 11:56:00 +01008594 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595
8596 { // scope for mLock
8597 Mutex::Autolock _l(mLock);
8598
8599 // check for existing effect chain with the requested audio session
8600 chain = getEffectChain_l(sessionId);
8601 if (chain == 0) {
8602 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008603 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008604 chain = new EffectChain(this, sessionId);
8605 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008606 chain->setStrategy(getStrategyForSession_l(sessionId));
8607 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008608#ifdef QCOM_HARDWARE
8609 if(sessionId == mAudioFlinger->mLPASessionId) {
8610 // Clear reference to previous effect chain if any
8611 if(mAudioFlinger->mLPAEffectChain.get()) {
8612 mAudioFlinger->mLPAEffectChain.clear();
8613 }
8614 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8615 mAudioFlinger->mLPAEffectChain = chain;
8616 chain->setLPAFlag(true);
8617 // For LPA, the volume will be applied in DSP. No need for volume
8618 // control in the Effect chain, so setting it to unity.
8619 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8620 chain->setVolume_l(&volume,&volume);
8621 }
8622#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008623 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008624 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 }
8626
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008627 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008628
8629 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008630 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008632 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008633 if (lStatus != NO_ERROR) {
8634 goto Exit;
8635 }
8636 effectRegistered = true;
8637 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008638 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008639 lStatus = effect->status();
8640 if (lStatus != NO_ERROR) {
8641 goto Exit;
8642 }
Eric Laurentcab11242010-07-15 12:50:15 -07008643 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644 if (lStatus != NO_ERROR) {
8645 goto Exit;
8646 }
8647 effectCreated = true;
8648
Eric Laurentf1c04f92012-08-28 14:26:53 -07008649 effect->setDevice(mOutDevice);
8650 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008652 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008653#ifdef QCOM_HARDWARE
8654 if(chain == mAudioFlinger->mLPAEffectChain) {
8655 effect->setLPAFlag(true);
8656 }
8657#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008658 }
8659 // create effect handle and connect it to effect module
8660 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008661 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008662 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008663 *enabled = (int)effect->isEnabled();
8664 }
8665 }
8666
8667Exit:
8668 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008669 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008671 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672 }
8673 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008674 AudioSystem::unregisterEffect(effect->id());
8675 }
8676 if (chainCreated) {
8677 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008678 }
8679 handle.clear();
8680 }
8681
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008682 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008683 *status = lStatus;
8684 }
8685 return handle;
8686}
8687
Eric Laurent717e1282012-06-29 16:36:52 -07008688sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8689{
8690 Mutex::Autolock _l(mLock);
8691 return getEffect_l(sessionId, effectId);
8692}
8693
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008694sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8695{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008696 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008697 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008698}
8699
Eric Laurentde070132010-07-13 04:45:46 -07008700// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8701// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008702status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008703{
8704 // check for existing effect chain with the requested audio session
8705 int sessionId = effect->sessionId();
8706 sp<EffectChain> chain = getEffectChain_l(sessionId);
8707 bool chainCreated = false;
8708
8709 if (chain == 0) {
8710 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008711 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008712 chain = new EffectChain(this, sessionId);
8713 addEffectChain_l(chain);
8714 chain->setStrategy(getStrategyForSession_l(sessionId));
8715 chainCreated = true;
8716 }
Steve Block3856b092011-10-20 11:56:00 +01008717 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008718
8719 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008720 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008721 this, effect->desc().name, chain.get());
8722 return BAD_VALUE;
8723 }
8724
8725 status_t status = chain->addEffect_l(effect);
8726 if (status != NO_ERROR) {
8727 if (chainCreated) {
8728 removeEffectChain_l(chain);
8729 }
8730 return status;
8731 }
8732
Eric Laurentf1c04f92012-08-28 14:26:53 -07008733 effect->setDevice(mOutDevice);
8734 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008735 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008736 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008737 return NO_ERROR;
8738}
8739
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008740void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008741
Steve Block3856b092011-10-20 11:56:00 +01008742 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008744 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8745 detachAuxEffect_l(effect->id());
8746 }
8747
8748 sp<EffectChain> chain = effect->chain().promote();
8749 if (chain != 0) {
8750 // remove effect chain if removing last effect
8751 if (chain->removeEffect_l(effect) == 0) {
8752 removeEffectChain_l(chain);
8753 }
8754 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008755 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008756 }
8757}
8758
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008759void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008760 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008761{
8762 effectChains = mEffectChains;
8763 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008764#ifdef QCOM_HARDWARE
8765 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8766#endif
8767 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008768 }
8769}
8770
8771void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008772 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008773{
8774 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008775#ifdef QCOM_HARDWARE
8776 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8777#endif
8778 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008779 }
8780}
8781
8782sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8783{
8784 Mutex::Autolock _l(mLock);
8785 return getEffectChain_l(sessionId);
8786}
8787
Glenn Kasten106e8a42012-08-02 13:37:12 -07008788sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008789{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008790 size_t size = mEffectChains.size();
8791 for (size_t i = 0; i < size; i++) {
8792 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008793 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008794 }
8795 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008796 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008797}
8798
Glenn Kastenf78aee72012-01-04 11:00:47 -08008799void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008800{
8801 Mutex::Autolock _l(mLock);
8802 size_t size = mEffectChains.size();
8803 for (size_t i = 0; i < size; i++) {
8804 mEffectChains[i]->setMode_l(mode);
8805 }
8806}
8807
8808void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008809 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008810 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008811
Mathias Agopian65ab4712010-07-14 17:59:35 -07008812 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008813 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814 // delete the effect module if removing last handle on it
8815 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008816 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008817 removeEffect_l(effect);
8818 AudioSystem::unregisterEffect(effect->id());
8819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008820 }
8821}
8822
8823status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8824{
8825 int session = chain->sessionId();
8826 int16_t *buffer = mMixBuffer;
8827 bool ownsBuffer = false;
8828
Steve Block3856b092011-10-20 11:56:00 +01008829 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008830 if (session > 0) {
8831 // Only one effect chain can be present in direct output thread and it uses
8832 // the mix buffer as input
8833 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008834 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 buffer = new int16_t[numSamples];
8836 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008837 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838 ownsBuffer = true;
8839 }
8840
8841 // Attach all tracks with same session ID to this chain.
8842 for (size_t i = 0; i < mTracks.size(); ++i) {
8843 sp<Track> track = mTracks[i];
8844 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008845 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008847 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008848 }
8849 }
8850
8851 // indicate all active tracks in the chain
8852 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8853 sp<Track> track = mActiveTracks[i].promote();
8854 if (track == 0) continue;
8855 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008856 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008857 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008858 }
8859 }
8860 }
8861
8862 chain->setInBuffer(buffer, ownsBuffer);
8863 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008864 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008865 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008866 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8867 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008869 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8870 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008871 // Effect chain for other sessions are inserted at beginning of effect
8872 // chains list to be processed before output mix effects. Relative order between other
8873 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008874 size_t size = mEffectChains.size();
8875 size_t i = 0;
8876 for (i = 0; i < size; i++) {
8877 if (mEffectChains[i]->sessionId() < session) break;
8878 }
8879 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008880 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008881
8882 return NO_ERROR;
8883}
8884
8885size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8886{
8887 int session = chain->sessionId();
8888
Steve Block3856b092011-10-20 11:56:00 +01008889 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890
8891 for (size_t i = 0; i < mEffectChains.size(); i++) {
8892 if (chain == mEffectChains[i]) {
8893 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008894 // detach all active tracks from the chain
8895 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8896 sp<Track> track = mActiveTracks[i].promote();
8897 if (track == 0) continue;
8898 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008899 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008900 chain.get(), session);
8901 chain->decActiveTrackCnt();
8902 }
8903 }
8904
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 // detach all tracks with same session ID from this chain
8906 for (size_t i = 0; i < mTracks.size(); ++i) {
8907 sp<Track> track = mTracks[i];
8908 if (session == track->sessionId()) {
8909 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008910 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911 }
8912 }
Eric Laurentde070132010-07-13 04:45:46 -07008913 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 }
8915 }
8916 return mEffectChains.size();
8917}
8918
Eric Laurentde070132010-07-13 04:45:46 -07008919status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8920 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921{
8922 Mutex::Autolock _l(mLock);
8923 return attachAuxEffect_l(track, EffectId);
8924}
8925
Eric Laurentde070132010-07-13 04:45:46 -07008926status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8927 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928{
8929 status_t status = NO_ERROR;
8930
8931 if (EffectId == 0) {
8932 track->setAuxBuffer(0, NULL);
8933 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008934 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8935 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936 if (effect != 0) {
8937 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8938 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8939 } else {
8940 status = INVALID_OPERATION;
8941 }
8942 } else {
8943 status = BAD_VALUE;
8944 }
8945 }
8946 return status;
8947}
8948
8949void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8950{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008951 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952 sp<Track> track = mTracks[i];
8953 if (track->auxEffectId() == effectId) {
8954 attachAuxEffect_l(track, 0);
8955 }
8956 }
8957}
8958
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008959status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8960{
8961 // only one chain per input thread
8962 if (mEffectChains.size() != 0) {
8963 return INVALID_OPERATION;
8964 }
Steve Block3856b092011-10-20 11:56:00 +01008965 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008966
8967 chain->setInBuffer(NULL);
8968 chain->setOutBuffer(NULL);
8969
Eric Laurent59255e42011-07-27 19:49:51 -07008970 checkSuspendOnAddEffectChain_l(chain);
8971
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008972 mEffectChains.add(chain);
8973
8974 return NO_ERROR;
8975}
8976
8977size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8978{
Steve Block3856b092011-10-20 11:56:00 +01008979 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008980 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008981 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8982 chain.get(), mEffectChains.size(), this);
8983 if (mEffectChains.size() == 1) {
8984 mEffectChains.removeAt(0);
8985 }
8986 return 0;
8987}
8988
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989// ----------------------------------------------------------------------------
8990// EffectModule implementation
8991// ----------------------------------------------------------------------------
8992
8993#undef LOG_TAG
8994#define LOG_TAG "AudioFlinger::EffectModule"
8995
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008996AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997 const wp<AudioFlinger::EffectChain>& chain,
8998 effect_descriptor_t *desc,
8999 int id,
9000 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07009001 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
9002 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07009003 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07009004 // mConfig is set by configure() and not used before then
9005 mEffectInterface(NULL),
9006 mStatus(NO_INIT), mState(IDLE),
9007 // mMaxDisableWaitCnt is set by configure() and not used before then
9008 // mDisableWaitCnt is set by process() and updateState() and not used before then
9009 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08009010#ifdef QCOM_HARDWARE
9011 ,mIsForLPA(false)
9012#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013{
Steve Block3856b092011-10-20 11:56:00 +01009014 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009015 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016
9017 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009018 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019
9020 if (mStatus != NO_ERROR) {
9021 return;
9022 }
9023 lStatus = init();
9024 if (lStatus < 0) {
9025 mStatus = lStatus;
9026 goto Error;
9027 }
9028
Steve Block3856b092011-10-20 11:56:00 +01009029 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 return;
9031Error:
9032 EffectRelease(mEffectInterface);
9033 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01009034 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035}
9036
9037AudioFlinger::EffectModule::~EffectModule()
9038{
Steve Block3856b092011-10-20 11:56:00 +01009039 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009040 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009041 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9042 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
9043 sp<ThreadBase> thread = mThread.promote();
9044 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009045 audio_stream_t *stream = thread->stream();
9046 if (stream != NULL) {
9047 stream->remove_audio_effect(stream, mEffectInterface);
9048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009049 }
9050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051 // release effect engine
9052 EffectRelease(mEffectInterface);
9053 }
9054}
9055
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009056status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009057{
9058 status_t status;
9059
9060 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009061 int priority = handle->priority();
9062 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009063 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009064 size_t i;
9065 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009066 EffectHandle *h = mHandles[i];
9067 if (h == NULL || h->destroyed_l()) continue;
9068 // first non destroyed handle is considered in control
9069 if (controlHandle == NULL)
9070 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009071 if (h->priority() <= priority) break;
9072 }
9073 // if inserted in first place, move effect control from previous owner to this handle
9074 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07009075 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009076 if (controlHandle != NULL) {
9077 enabled = controlHandle->enabled();
9078 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009079 }
Eric Laurent59255e42011-07-27 19:49:51 -07009080 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081 status = NO_ERROR;
9082 } else {
9083 status = ALREADY_EXISTS;
9084 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009085 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009086 mHandles.insertAt(handle, i);
9087 return status;
9088}
9089
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009090size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091{
9092 Mutex::Autolock _l(mLock);
9093 size_t size = mHandles.size();
9094 size_t i;
9095 for (i = 0; i < size; i++) {
9096 if (mHandles[i] == handle) break;
9097 }
9098 if (i == size) {
9099 return size;
9100 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009101 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07009102
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009105 if (i == 0) {
9106 EffectHandle *h = controlHandle_l();
9107 if (h != NULL) {
9108 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009109 }
9110 }
9111
Eric Laurentec437d82011-07-26 20:54:46 -07009112 // Prevent calls to process() and other functions on effect interface from now on.
9113 // The effect engine will be released by the destructor when the last strong reference on
9114 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009115 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009116 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009117 }
9118
Eric Laurente65c8912012-07-20 15:57:23 -07009119 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120}
9121
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009122// must be called with EffectModule::mLock held
9123AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009124{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009125 // the first valid handle in the list has control over the module
9126 for (size_t i = 0; i < mHandles.size(); i++) {
9127 EffectHandle *h = mHandles[i];
9128 if (h != NULL && !h->destroyed_l()) {
9129 return h;
9130 }
9131 }
9132
9133 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009134}
9135
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009136size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009137{
vivek mehta2192bc92012-12-04 11:46:08 -08009138#ifdef QCOM_HARDWARE
9139 setEnabled(false);
9140#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009141 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142 // keep a strong reference on this EffectModule to avoid calling the
9143 // destructor before we exit
9144 sp<EffectModule> keep(this);
9145 {
9146 sp<ThreadBase> thread = mThread.promote();
9147 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009148 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009149 }
9150 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009151 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152}
9153
9154void AudioFlinger::EffectModule::updateState() {
9155 Mutex::Autolock _l(mLock);
9156
9157 switch (mState) {
9158 case RESTART:
9159 reset_l();
9160 // FALL THROUGH
9161
9162 case STARTING:
9163 // clear auxiliary effect input buffer for next accumulation
9164 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9165 memset(mConfig.inputCfg.buffer.raw,
9166 0,
9167 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9168 }
9169 start_l();
9170 mState = ACTIVE;
9171 break;
9172 case STOPPING:
9173 stop_l();
9174 mDisableWaitCnt = mMaxDisableWaitCnt;
9175 mState = STOPPED;
9176 break;
9177 case STOPPED:
9178 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9179 // turn off sequence.
9180 if (--mDisableWaitCnt == 0) {
9181 reset_l();
9182 mState = IDLE;
9183 }
9184 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009185 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009186 break;
9187 }
9188}
9189
9190void AudioFlinger::EffectModule::process()
9191{
9192 Mutex::Autolock _l(mLock);
9193
Eric Laurentec437d82011-07-26 20:54:46 -07009194 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009195 mConfig.inputCfg.buffer.raw == NULL ||
9196 mConfig.outputCfg.buffer.raw == NULL) {
9197 return;
9198 }
9199
Eric Laurent8f45bd72010-08-31 13:50:07 -07009200 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9202 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009203 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009204 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009205 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009206 }
9207
9208 // do the actual processing in the effect engine
9209 int ret = (*mEffectInterface)->process(mEffectInterface,
9210 &mConfig.inputCfg.buffer,
9211 &mConfig.outputCfg.buffer);
9212
9213 // force transition to IDLE state when engine is ready
9214 if (mState == STOPPED && ret == -ENODATA) {
9215 mDisableWaitCnt = 1;
9216 }
9217
9218 // clear auxiliary effect input buffer for next accumulation
9219 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009220 memset(mConfig.inputCfg.buffer.raw, 0,
9221 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222 }
9223 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009224 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9225 // If an insert effect is idle and input buffer is different from output buffer,
9226 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009227 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009228 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009229 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9230 int16_t *in = mConfig.inputCfg.buffer.s16;
9231 int16_t *out = mConfig.outputCfg.buffer.s16;
9232 for (size_t i = 0; i < frameCnt; i++) {
9233 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235 }
9236 }
9237}
9238
9239void AudioFlinger::EffectModule::reset_l()
9240{
9241 if (mEffectInterface == NULL) {
9242 return;
9243 }
9244 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9245}
9246
vivek mehta2192bc92012-12-04 11:46:08 -08009247#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248status_t AudioFlinger::EffectModule::configure()
9249{
vivek mehta2192bc92012-12-04 11:46:08 -08009250#else
9251status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9252{
9253 uint32_t channels;
9254
9255 // Acquire lock here to make sure that any other thread does not delete
9256 // the effect handle and release the effect module.
9257 Mutex::Autolock _l(mLock);
9258#endif
9259
Mathias Agopian65ab4712010-07-14 17:59:35 -07009260 if (mEffectInterface == NULL) {
9261 return NO_INIT;
9262 }
9263
9264 sp<ThreadBase> thread = mThread.promote();
9265 if (thread == 0) {
9266 return DEAD_OBJECT;
9267 }
9268
9269 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009270 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009271#ifdef QCOM_HARDWARE
9272 mIsForLPA = isForLPA;
9273 if(isForLPA) {
9274 if (channelCount == 1) {
9275 channels = AUDIO_CHANNEL_OUT_MONO;
9276 } else {
9277 channels = AUDIO_CHANNEL_OUT_STEREO;
9278 }
9279 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9280 } else {
9281 if (thread->channelCount() == 1) {
9282 channels = AUDIO_CHANNEL_OUT_MONO;
9283 } else {
9284 channels = AUDIO_CHANNEL_OUT_STEREO;
9285 }
9286 }
9287#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288
9289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009290 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009291 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009292 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009293 }
Glenn Kasten254af182012-07-03 14:59:05 -07009294 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009295 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9296 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009297#ifdef QCOM_HARDWARE
9298 if(isForLPA){
9299 mConfig.inputCfg.samplingRate = sampleRate;
9300 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9301 } else
9302#endif
9303 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009304 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9305 mConfig.inputCfg.bufferProvider.cookie = NULL;
9306 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9307 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9308 mConfig.outputCfg.bufferProvider.cookie = NULL;
9309 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9310 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9311 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9312 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009313 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009314 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009315 // - in other sessions:
9316 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9317 // other effect: overwrites output buffer: input buffer == output buffer
9318 // Auxiliary effect:
9319 // accumulates in output buffer: input buffer != output buffer
9320 // Therefore: accumulate <=> input buffer != output buffer
9321 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9322 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9323 } else {
9324 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9325 }
9326 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9327 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009328#ifdef QCOM_HARDWARE
9329 if(isForLPA) {
9330 mConfig.inputCfg.buffer.frameCount = frameCount;
9331 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9332 } else
9333#endif
9334 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009335 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9336
Steve Block3856b092011-10-20 11:56:00 +01009337 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009338 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9339
Mathias Agopian65ab4712010-07-14 17:59:35 -07009340 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009341 uint32_t size = sizeof(int);
9342 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009343 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009344 sizeof(effect_config_t),
9345 &mConfig,
9346 &size,
9347 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009348 if (status == 0) {
9349 status = cmdStatus;
9350 }
9351
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009352 if (status == 0 &&
9353 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9354 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9355 effect_param_t *p = (effect_param_t *)buf32;
9356
9357 p->psize = sizeof(uint32_t);
9358 p->vsize = sizeof(uint32_t);
9359 size = sizeof(int);
9360 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9361
9362 uint32_t latency = 0;
9363 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9364 if (pbt != NULL) {
9365 latency = pbt->latency_l();
9366 }
9367
9368 *((int32_t *)p->data + 1)= latency;
9369 (*mEffectInterface)->command(mEffectInterface,
9370 EFFECT_CMD_SET_PARAM,
9371 sizeof(effect_param_t) + 8,
9372 &buf32,
9373 &size,
9374 &cmdStatus);
9375 }
9376
Mathias Agopian65ab4712010-07-14 17:59:35 -07009377 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9378 (1000 * mConfig.outputCfg.buffer.frameCount);
9379
9380 return status;
9381}
9382
9383status_t AudioFlinger::EffectModule::init()
9384{
9385 Mutex::Autolock _l(mLock);
9386 if (mEffectInterface == NULL) {
9387 return NO_INIT;
9388 }
9389 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009390 uint32_t size = sizeof(status_t);
9391 status_t status = (*mEffectInterface)->command(mEffectInterface,
9392 EFFECT_CMD_INIT,
9393 0,
9394 NULL,
9395 &size,
9396 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009397 if (status == 0) {
9398 status = cmdStatus;
9399 }
9400 return status;
9401}
9402
Eric Laurentec35a142011-10-05 17:42:25 -07009403status_t AudioFlinger::EffectModule::start()
9404{
9405 Mutex::Autolock _l(mLock);
9406 return start_l();
9407}
9408
Mathias Agopian65ab4712010-07-14 17:59:35 -07009409status_t AudioFlinger::EffectModule::start_l()
9410{
9411 if (mEffectInterface == NULL) {
9412 return NO_INIT;
9413 }
9414 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009415 uint32_t size = sizeof(status_t);
9416 status_t status = (*mEffectInterface)->command(mEffectInterface,
9417 EFFECT_CMD_ENABLE,
9418 0,
9419 NULL,
9420 &size,
9421 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009422 if (status == 0) {
9423 status = cmdStatus;
9424 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009425 if (status == 0 &&
9426 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9427 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9428 sp<ThreadBase> thread = mThread.promote();
9429 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009430 audio_stream_t *stream = thread->stream();
9431 if (stream != NULL) {
9432 stream->add_audio_effect(stream, mEffectInterface);
9433 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009434 }
9435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009436 return status;
9437}
9438
Eric Laurentec437d82011-07-26 20:54:46 -07009439status_t AudioFlinger::EffectModule::stop()
9440{
9441 Mutex::Autolock _l(mLock);
9442 return stop_l();
9443}
9444
Mathias Agopian65ab4712010-07-14 17:59:35 -07009445status_t AudioFlinger::EffectModule::stop_l()
9446{
9447 if (mEffectInterface == NULL) {
9448 return NO_INIT;
9449 }
9450 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009451 uint32_t size = sizeof(status_t);
9452 status_t status = (*mEffectInterface)->command(mEffectInterface,
9453 EFFECT_CMD_DISABLE,
9454 0,
9455 NULL,
9456 &size,
9457 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009458 if (status == 0) {
9459 status = cmdStatus;
9460 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009461 if (status == 0 &&
9462 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9463 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9464 sp<ThreadBase> thread = mThread.promote();
9465 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009466 audio_stream_t *stream = thread->stream();
9467 if (stream != NULL) {
9468 stream->remove_audio_effect(stream, mEffectInterface);
9469 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009470 }
9471 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009472 return status;
9473}
9474
Eric Laurent25f43952010-07-28 05:40:18 -07009475status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9476 uint32_t cmdSize,
9477 void *pCmdData,
9478 uint32_t *replySize,
9479 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009480{
9481 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009482// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009483
Eric Laurentec437d82011-07-26 20:54:46 -07009484 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009485 return NO_INIT;
9486 }
Eric Laurent25f43952010-07-28 05:40:18 -07009487 status_t status = (*mEffectInterface)->command(mEffectInterface,
9488 cmdCode,
9489 cmdSize,
9490 pCmdData,
9491 replySize,
9492 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009493 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009494 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009495 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009496 EffectHandle *h = mHandles[i];
9497 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009498 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9499 }
9500 }
9501 }
9502 return status;
9503}
9504
9505status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9506{
9507 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009508 return setEnabled_l(enabled);
9509}
9510
9511// must be called with EffectModule::mLock held
9512status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9513{
vivek mehta2192bc92012-12-04 11:46:08 -08009514#ifdef QCOM_HARDWARE
9515 bool effectStateChanged = false;
9516#endif
Steve Block3856b092011-10-20 11:56:00 +01009517 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009518
9519 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009520#ifdef QCOM_HARDWARE
9521 effectStateChanged = true;
9522#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009523 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9524 if (enabled && status != NO_ERROR) {
9525 return status;
9526 }
9527
Mathias Agopian65ab4712010-07-14 17:59:35 -07009528 switch (mState) {
9529 // going from disabled to enabled
9530 case IDLE:
9531 mState = STARTING;
9532 break;
9533 case STOPPED:
9534 mState = RESTART;
9535 break;
9536 case STOPPING:
9537 mState = ACTIVE;
9538 break;
9539
9540 // going from enabled to disabled
9541 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009542 mState = STOPPED;
9543 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009544 case STARTING:
9545 mState = IDLE;
9546 break;
9547 case ACTIVE:
9548 mState = STOPPING;
9549 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009550 case DESTROYED:
9551 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009552 }
9553 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009554 EffectHandle *h = mHandles[i];
9555 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009556 h->setEnabled(enabled);
9557 }
9558 }
9559 }
vivek mehta2192bc92012-12-04 11:46:08 -08009560#ifdef QCOM_HARDWARE
9561 /*
9562 Send notification event to LPA Player when an effect for
9563 LPA output is enabled or disabled.
9564 */
9565 if (effectStateChanged && mIsForLPA) {
9566 sp<ThreadBase> thread = mThread.promote();
9567 thread->effectConfigChanged();
9568 }
9569#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009570 return NO_ERROR;
9571}
9572
Glenn Kastenc59c0042012-02-02 14:06:11 -08009573bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009574{
9575 switch (mState) {
9576 case RESTART:
9577 case STARTING:
9578 case ACTIVE:
9579 return true;
9580 case IDLE:
9581 case STOPPING:
9582 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009583 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009584 default:
9585 return false;
9586 }
9587}
9588
Glenn Kastenc59c0042012-02-02 14:06:11 -08009589bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009590{
9591 switch (mState) {
9592 case RESTART:
9593 case ACTIVE:
9594 case STOPPING:
9595 case STOPPED:
9596 return true;
9597 case IDLE:
9598 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009599 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009600 default:
9601 return false;
9602 }
9603}
9604
Mathias Agopian65ab4712010-07-14 17:59:35 -07009605status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9606{
9607 Mutex::Autolock _l(mLock);
9608 status_t status = NO_ERROR;
9609
9610 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9611 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009612 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009613 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9614 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009615 status_t cmdStatus;
9616 uint32_t volume[2];
9617 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009618 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009619 volume[0] = *left;
9620 volume[1] = *right;
9621 if (controller) {
9622 pVolume = volume;
9623 }
Eric Laurent25f43952010-07-28 05:40:18 -07009624 status = (*mEffectInterface)->command(mEffectInterface,
9625 EFFECT_CMD_SET_VOLUME,
9626 size,
9627 volume,
9628 &size,
9629 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009630 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9631 *left = volume[0];
9632 *right = volume[1];
9633 }
9634 }
9635 return status;
9636}
9637
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009638status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009639{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009640 if (device == AUDIO_DEVICE_NONE) {
9641 return NO_ERROR;
9642 }
9643
Mathias Agopian65ab4712010-07-14 17:59:35 -07009644 Mutex::Autolock _l(mLock);
9645 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009646 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009647 status_t cmdStatus;
9648 uint32_t size = sizeof(status_t);
9649 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9650 EFFECT_CMD_SET_INPUT_DEVICE;
9651 status = (*mEffectInterface)->command(mEffectInterface,
9652 cmd,
9653 sizeof(uint32_t),
9654 &device,
9655 &size,
9656 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009657 }
9658 return status;
9659}
9660
Glenn Kastenf78aee72012-01-04 11:00:47 -08009661status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009662{
9663 Mutex::Autolock _l(mLock);
9664 status_t status = NO_ERROR;
9665 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009666 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009667 uint32_t size = sizeof(status_t);
9668 status = (*mEffectInterface)->command(mEffectInterface,
9669 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009670 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009671 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009672 &size,
9673 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009674 if (status == NO_ERROR) {
9675 status = cmdStatus;
9676 }
9677 }
9678 return status;
9679}
9680
Eric Laurent57b2dd12012-08-31 17:44:06 -07009681status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9682{
9683 Mutex::Autolock _l(mLock);
9684 status_t status = NO_ERROR;
9685 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9686 uint32_t size = 0;
9687 status = (*mEffectInterface)->command(mEffectInterface,
9688 EFFECT_CMD_SET_AUDIO_SOURCE,
9689 sizeof(audio_source_t),
9690 &source,
9691 &size,
9692 NULL);
9693 }
9694 return status;
9695}
9696
Eric Laurent59255e42011-07-27 19:49:51 -07009697void AudioFlinger::EffectModule::setSuspended(bool suspended)
9698{
9699 Mutex::Autolock _l(mLock);
9700 mSuspended = suspended;
9701}
Glenn Kastena3a85482012-01-04 11:01:11 -08009702
9703bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009704{
9705 Mutex::Autolock _l(mLock);
9706 return mSuspended;
9707}
9708
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009709bool AudioFlinger::EffectModule::purgeHandles()
9710{
9711 bool enabled = false;
9712 Mutex::Autolock _l(mLock);
9713 for (size_t i = 0; i < mHandles.size(); i++) {
9714 EffectHandle *handle = mHandles[i];
9715 if (handle != NULL && !handle->destroyed_l()) {
9716 handle->effect().clear();
9717 if (handle->hasControl()) {
9718 enabled = handle->enabled();
9719 }
9720 }
9721 }
9722 return enabled;
9723}
9724
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009725void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009726{
9727 const size_t SIZE = 256;
9728 char buffer[SIZE];
9729 String8 result;
9730
9731 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9732 result.append(buffer);
9733
9734 bool locked = tryLock(mLock);
9735 // failed to lock - AudioFlinger is probably deadlocked
9736 if (!locked) {
9737 result.append("\t\tCould not lock Fx mutex:\n");
9738 }
9739
9740 result.append("\t\tSession Status State Engine:\n");
9741 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9742 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9743 result.append(buffer);
9744
9745 result.append("\t\tDescriptor:\n");
9746 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9747 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9748 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9749 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9750 result.append(buffer);
9751 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9752 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9753 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9754 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9755 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009756 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009757 mDescriptor.apiVersion,
9758 mDescriptor.flags);
9759 result.append(buffer);
9760 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9761 mDescriptor.name);
9762 result.append(buffer);
9763 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9764 mDescriptor.implementor);
9765 result.append(buffer);
9766
9767 result.append("\t\t- Input configuration:\n");
9768 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9769 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9770 (uint32_t)mConfig.inputCfg.buffer.raw,
9771 mConfig.inputCfg.buffer.frameCount,
9772 mConfig.inputCfg.samplingRate,
9773 mConfig.inputCfg.channels,
9774 mConfig.inputCfg.format);
9775 result.append(buffer);
9776
9777 result.append("\t\t- Output configuration:\n");
9778 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9779 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9780 (uint32_t)mConfig.outputCfg.buffer.raw,
9781 mConfig.outputCfg.buffer.frameCount,
9782 mConfig.outputCfg.samplingRate,
9783 mConfig.outputCfg.channels,
9784 mConfig.outputCfg.format);
9785 result.append(buffer);
9786
9787 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9788 result.append(buffer);
9789 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9790 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009791 EffectHandle *handle = mHandles[i];
9792 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009793 handle->dump(buffer, SIZE);
9794 result.append(buffer);
9795 }
9796 }
9797
9798 result.append("\n");
9799
9800 write(fd, result.string(), result.length());
9801
9802 if (locked) {
9803 mLock.unlock();
9804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009805}
9806
9807// ----------------------------------------------------------------------------
9808// EffectHandle implementation
9809// ----------------------------------------------------------------------------
9810
9811#undef LOG_TAG
9812#define LOG_TAG "AudioFlinger::EffectHandle"
9813
9814AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9815 const sp<AudioFlinger::Client>& client,
9816 const sp<IEffectClient>& effectClient,
9817 int32_t priority)
9818 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009819 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009820 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009821{
Steve Block3856b092011-10-20 11:56:00 +01009822 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009823
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009824 if (client == 0) {
9825 return;
9826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009827 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9828 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9829 if (mCblkMemory != 0) {
9830 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9831
Glenn Kastena0d68332012-01-27 16:47:15 -08009832 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009833 new(mCblk) effect_param_cblk_t();
9834 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009836 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009837 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009838 return;
9839 }
9840}
9841
9842AudioFlinger::EffectHandle::~EffectHandle()
9843{
Steve Block3856b092011-10-20 11:56:00 +01009844 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009845
9846 if (mEffect == 0) {
9847 mDestroyed = true;
9848 return;
9849 }
9850 mEffect->lock();
9851 mDestroyed = true;
9852 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009853 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009854}
9855
9856status_t AudioFlinger::EffectHandle::enable()
9857{
Steve Block3856b092011-10-20 11:56:00 +01009858 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009859 if (!mHasControl) return INVALID_OPERATION;
9860 if (mEffect == 0) return DEAD_OBJECT;
9861
Eric Laurentdb7c0792011-08-10 10:37:50 -07009862 if (mEnabled) {
9863 return NO_ERROR;
9864 }
9865
Eric Laurent59255e42011-07-27 19:49:51 -07009866 mEnabled = true;
9867
9868 sp<ThreadBase> thread = mEffect->thread().promote();
9869 if (thread != 0) {
9870 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9871 }
9872
9873 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9874 if (mEffect->suspended()) {
9875 return NO_ERROR;
9876 }
9877
Eric Laurentdb7c0792011-08-10 10:37:50 -07009878 status_t status = mEffect->setEnabled(true);
9879 if (status != NO_ERROR) {
9880 if (thread != 0) {
9881 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9882 }
9883 mEnabled = false;
9884 }
9885 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009886}
9887
9888status_t AudioFlinger::EffectHandle::disable()
9889{
Steve Block3856b092011-10-20 11:56:00 +01009890 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009891 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009892 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009893
Eric Laurentdb7c0792011-08-10 10:37:50 -07009894 if (!mEnabled) {
9895 return NO_ERROR;
9896 }
Eric Laurent59255e42011-07-27 19:49:51 -07009897 mEnabled = false;
9898
9899 if (mEffect->suspended()) {
9900 return NO_ERROR;
9901 }
9902
9903 status_t status = mEffect->setEnabled(false);
9904
9905 sp<ThreadBase> thread = mEffect->thread().promote();
9906 if (thread != 0) {
9907 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9908 }
9909
9910 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009911}
9912
9913void AudioFlinger::EffectHandle::disconnect()
9914{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009915 disconnect(true);
9916}
9917
Glenn Kasten58123c32012-02-03 10:32:24 -08009918void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009919{
Glenn Kasten58123c32012-02-03 10:32:24 -08009920 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009921 if (mEffect == 0) {
9922 return;
9923 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009924 // restore suspended effects if the disconnected handle was enabled and the last one.
9925 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009926 sp<ThreadBase> thread = mEffect->thread().promote();
9927 if (thread != 0) {
9928 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9929 }
Eric Laurent59255e42011-07-27 19:49:51 -07009930 }
9931
Mathias Agopian65ab4712010-07-14 17:59:35 -07009932 // release sp on module => module destructor can be called now
9933 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009934 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009935 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009936 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009937 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9938 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009939 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009940 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009941 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9942 mClient.clear();
9943 }
9944}
9945
Eric Laurent25f43952010-07-28 05:40:18 -07009946status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9947 uint32_t cmdSize,
9948 void *pCmdData,
9949 uint32_t *replySize,
9950 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009951{
Steve Block3856b092011-10-20 11:56:00 +01009952// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009953// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009954
9955 // only get parameter command is permitted for applications not controlling the effect
9956 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9957 return INVALID_OPERATION;
9958 }
9959 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009960 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009961
9962 // handle commands that are not forwarded transparently to effect engine
9963 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9964 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9965 // no risk to block the whole media server process or mixer threads is we are stuck here
9966 Mutex::Autolock _l(mCblk->lock);
9967 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9968 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9969 mCblk->serverIndex = 0;
9970 mCblk->clientIndex = 0;
9971 return BAD_VALUE;
9972 }
9973 status_t status = NO_ERROR;
9974 while (mCblk->serverIndex < mCblk->clientIndex) {
9975 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009976 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009977 int *p = (int *)(mBuffer + mCblk->serverIndex);
9978 int size = *p++;
9979 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009980 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009981 break;
9982 }
9983 effect_param_t *param = (effect_param_t *)p;
9984 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009985 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009986 mCblk->serverIndex += size;
9987 continue;
9988 }
Eric Laurent25f43952010-07-28 05:40:18 -07009989 uint32_t psize = sizeof(effect_param_t) +
9990 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9991 param->vsize;
9992 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9993 psize,
9994 p,
9995 &rsize,
9996 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009997 // stop at first error encountered
9998 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009999 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -070010000 *(int *)pReplyData = reply;
10001 break;
10002 } else if (reply != NO_ERROR) {
10003 *(int *)pReplyData = reply;
10004 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010005 }
10006 mCblk->serverIndex += size;
10007 }
10008 mCblk->serverIndex = 0;
10009 mCblk->clientIndex = 0;
10010 return status;
10011 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -070010012 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010013 return enable();
10014 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -070010015 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010016 return disable();
10017 }
10018
vivek mehta2192bc92012-12-04 11:46:08 -080010019#ifdef QCOM_HARDWARE
10020 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
10021 if(mEffect->isOnLPA() &&
10022 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
10023 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
10024 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
10025 // Notify Direct track for the change in Effect module
10026 // TODO: check if it is required to send mLPAHandle
10027 ALOGV("Notifying Direct Track for the change in effect config");
10028 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
10029 }
10030#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010031 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10032}
10033
Eric Laurent59255e42011-07-27 19:49:51 -070010034void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010035{
Steve Block3856b092011-10-20 11:56:00 +010010036 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010037
10038 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -070010039 mEnabled = enabled;
10040
Mathias Agopian65ab4712010-07-14 17:59:35 -070010041 if (signal && mEffectClient != 0) {
10042 mEffectClient->controlStatusChanged(hasControl);
10043 }
10044}
10045
Eric Laurent25f43952010-07-28 05:40:18 -070010046void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
10047 uint32_t cmdSize,
10048 void *pCmdData,
10049 uint32_t replySize,
10050 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010051{
10052 if (mEffectClient != 0) {
10053 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10054 }
10055}
10056
10057
10058
10059void AudioFlinger::EffectHandle::setEnabled(bool enabled)
10060{
10061 if (mEffectClient != 0) {
10062 mEffectClient->enableStatusChanged(enabled);
10063 }
10064}
10065
10066status_t AudioFlinger::EffectHandle::onTransact(
10067 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10068{
10069 return BnEffect::onTransact(code, data, reply, flags);
10070}
10071
10072
10073void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
10074{
Glenn Kastena0d68332012-01-27 16:47:15 -080010075 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010076
10077 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -080010078 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -070010079 mPriority,
10080 mHasControl,
10081 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -070010082 mCblk ? mCblk->clientIndex : 0,
10083 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070010084 );
10085
10086 if (locked) {
10087 mCblk->lock.unlock();
10088 }
10089}
10090
10091#undef LOG_TAG
10092#define LOG_TAG "AudioFlinger::EffectChain"
10093
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010094AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010095 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010096 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -070010097 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
10098 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -080010099#ifdef QCOM_HARDWARE
10100 ,mIsForLPATrack(false)
10101#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010102{
Dima Zavinfce7a472011-04-19 22:30:36 -070010103 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010104 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010105 return;
10106 }
10107 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
10108 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010109}
10110
10111AudioFlinger::EffectChain::~EffectChain()
10112{
10113 if (mOwnInBuffer) {
10114 delete mInBuffer;
10115 }
10116
10117}
10118
Eric Laurent59255e42011-07-27 19:49:51 -070010119// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010120sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010121{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010122 size_t size = mEffects.size();
10123
10124 for (size_t i = 0; i < size; i++) {
10125 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010126 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010127 }
10128 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010129 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010130}
10131
Eric Laurent59255e42011-07-27 19:49:51 -070010132// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010133sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010134{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010135 size_t size = mEffects.size();
10136
10137 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010138 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10139 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010140 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010141 }
10142 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010143 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010144}
10145
vivek mehta2192bc92012-12-04 11:46:08 -080010146#ifdef QCOM_HARDWARE
10147sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10148{
10149 sp<EffectModule> effect = NULL;
10150 if(idx < 0 || idx >= mEffects.size()) {
10151 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10152 }
10153 if(mEffects.size() > 0){
10154 effect = mEffects[idx];
10155 }
10156 return effect;
10157}
10158#endif
10159
Eric Laurent59255e42011-07-27 19:49:51 -070010160// getEffectFromType_l() must be called with ThreadBase::mLock held
10161sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10162 const effect_uuid_t *type)
10163{
Eric Laurent59255e42011-07-27 19:49:51 -070010164 size_t size = mEffects.size();
10165
10166 for (size_t i = 0; i < size; i++) {
10167 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010168 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010169 }
10170 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010171 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010172}
10173
Eric Laurent91b14c42012-05-30 12:30:29 -070010174void AudioFlinger::EffectChain::clearInputBuffer()
10175{
10176 Mutex::Autolock _l(mLock);
10177 sp<ThreadBase> thread = mThread.promote();
10178 if (thread == 0) {
10179 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10180 return;
10181 }
10182 clearInputBuffer_l(thread);
10183}
10184
10185// Must be called with EffectChain::mLock locked
10186void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10187{
10188 size_t numSamples = thread->frameCount() * thread->channelCount();
10189 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10190
10191}
10192
Mathias Agopian65ab4712010-07-14 17:59:35 -070010193// Must be called with EffectChain::mLock locked
10194void AudioFlinger::EffectChain::process_l()
10195{
Eric Laurentdac69112010-09-28 14:09:57 -070010196 sp<ThreadBase> thread = mThread.promote();
10197 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010198 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010199 return;
10200 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010201 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10202 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010203 // always process effects unless no more tracks are on the session and the effect tail
10204 // has been rendered
10205 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010206 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010207 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010208
Eric Laurent544fe9b2011-11-11 15:42:52 -080010209 if (!tracksOnSession && mTailBufferCount == 0) {
10210 doProcess = false;
10211 }
10212
10213 if (activeTrackCnt() == 0) {
10214 // if no track is active and the effect tail has not been rendered,
10215 // the input buffer must be cleared here as the mixer process will not do it
10216 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010217 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010218 if (mTailBufferCount > 0) {
10219 mTailBufferCount--;
10220 }
10221 }
10222 }
Eric Laurentdac69112010-09-28 14:09:57 -070010223 }
10224
Mathias Agopian65ab4712010-07-14 17:59:35 -070010225 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010226#ifdef QCOM_HARDWARE
10227 if (doProcess || isForLPATrack()) {
10228#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010229 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010230#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010231 for (size_t i = 0; i < size; i++) {
10232 mEffects[i]->process();
10233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010234 }
10235 for (size_t i = 0; i < size; i++) {
10236 mEffects[i]->updateState();
10237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010238}
10239
Eric Laurentcab11242010-07-15 12:50:15 -070010240// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010241status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010242{
10243 effect_descriptor_t desc = effect->desc();
10244 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10245
10246 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010247 effect->setChain(this);
10248 sp<ThreadBase> thread = mThread.promote();
10249 if (thread == 0) {
10250 return NO_INIT;
10251 }
10252 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010253
10254 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10255 // Auxiliary effects are inserted at the beginning of mEffects vector as
10256 // they are processed first and accumulated in chain input buffer
10257 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010258
Mathias Agopian65ab4712010-07-14 17:59:35 -070010259 // the input buffer for auxiliary effect contains mono samples in
10260 // 32 bit format. This is to avoid saturation in AudoMixer
10261 // accumulation stage. Saturation is done in EffectModule::process() before
10262 // calling the process in effect engine
10263 size_t numSamples = thread->frameCount();
10264 int32_t *buffer = new int32_t[numSamples];
10265 memset(buffer, 0, numSamples * sizeof(int32_t));
10266 effect->setInBuffer((int16_t *)buffer);
10267 // auxiliary effects output samples to chain input buffer for further processing
10268 // by insert effects
10269 effect->setOutBuffer(mInBuffer);
10270 } else {
10271 // Insert effects are inserted at the end of mEffects vector as they are processed
10272 // after track and auxiliary effects.
10273 // Insert effect order as a function of indicated preference:
10274 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10275 // another effect is present
10276 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10277 // last effect claiming first position
10278 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10279 // first effect claiming last position
10280 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10281 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10282 // already present
10283
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010284 size_t size = mEffects.size();
10285 size_t idx_insert = size;
10286 ssize_t idx_insert_first = -1;
10287 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010288
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010289 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010290 effect_descriptor_t d = mEffects[i]->desc();
10291 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10292 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10293 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10294 // check invalid effect chaining combinations
10295 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10296 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010297 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010298 return INVALID_OPERATION;
10299 }
10300 // remember position of first insert effect and by default
10301 // select this as insert position for new effect
10302 if (idx_insert == size) {
10303 idx_insert = i;
10304 }
10305 // remember position of last insert effect claiming
10306 // first position
10307 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10308 idx_insert_first = i;
10309 }
10310 // remember position of first insert effect claiming
10311 // last position
10312 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10313 idx_insert_last == -1) {
10314 idx_insert_last = i;
10315 }
10316 }
10317 }
10318
10319 // modify idx_insert from first position if needed
10320 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10321 if (idx_insert_last != -1) {
10322 idx_insert = idx_insert_last;
10323 } else {
10324 idx_insert = size;
10325 }
10326 } else {
10327 if (idx_insert_first != -1) {
10328 idx_insert = idx_insert_first + 1;
10329 }
10330 }
10331
10332 // always read samples from chain input buffer
10333 effect->setInBuffer(mInBuffer);
10334
10335 // if last effect in the chain, output samples to chain
10336 // output buffer, otherwise to chain input buffer
10337 if (idx_insert == size) {
10338 if (idx_insert != 0) {
10339 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10340 mEffects[idx_insert-1]->configure();
10341 }
10342 effect->setOutBuffer(mOutBuffer);
10343 } else {
10344 effect->setOutBuffer(mInBuffer);
10345 }
10346 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010347
Steve Block3856b092011-10-20 11:56:00 +010010348 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010349 }
10350 effect->configure();
10351 return NO_ERROR;
10352}
10353
Eric Laurentcab11242010-07-15 12:50:15 -070010354// removeEffect_l() must be called with PlaybackThread::mLock held
10355size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010356{
10357 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010358 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010359 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10360
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010361 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010362 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010363 // calling stop here will remove pre-processing effect from the audio HAL.
10364 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10365 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010366 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10367 mEffects[i]->state() == EffectModule::STOPPING) {
10368 mEffects[i]->stop();
10369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010370 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10371 delete[] effect->inBuffer();
10372 } else {
10373 if (i == size - 1 && i != 0) {
10374 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10375 mEffects[i - 1]->configure();
10376 }
10377 }
10378 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010379 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010380 break;
10381 }
10382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010383
10384 return mEffects.size();
10385}
10386
Eric Laurentcab11242010-07-15 12:50:15 -070010387// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010388void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010389{
10390 size_t size = mEffects.size();
10391 for (size_t i = 0; i < size; i++) {
10392 mEffects[i]->setDevice(device);
10393 }
10394}
10395
Eric Laurentcab11242010-07-15 12:50:15 -070010396// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010397void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010398{
10399 size_t size = mEffects.size();
10400 for (size_t i = 0; i < size; i++) {
10401 mEffects[i]->setMode(mode);
10402 }
10403}
10404
Eric Laurent57b2dd12012-08-31 17:44:06 -070010405// setAudioSource_l() must be called with PlaybackThread::mLock held
10406void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10407{
10408 size_t size = mEffects.size();
10409 for (size_t i = 0; i < size; i++) {
10410 mEffects[i]->setAudioSource(source);
10411 }
10412}
10413
Eric Laurentcab11242010-07-15 12:50:15 -070010414// setVolume_l() must be called with PlaybackThread::mLock held
10415bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010416{
10417 uint32_t newLeft = *left;
10418 uint32_t newRight = *right;
10419 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010420 int ctrlIdx = -1;
10421 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010422
Eric Laurentcab11242010-07-15 12:50:15 -070010423 // first update volume controller
10424 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010425 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010426 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10427 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010428 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010429 break;
10430 }
10431 }
10432
10433 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010434 if (hasControl) {
10435 *left = mNewLeftVolume;
10436 *right = mNewRightVolume;
10437 }
10438 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010439 }
10440
10441 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010442 mLeftVolume = newLeft;
10443 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010444
10445 // second get volume update from volume controller
10446 if (ctrlIdx >= 0) {
10447 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010448 mNewLeftVolume = newLeft;
10449 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010450 }
10451 // then indicate volume to all other effects in chain.
10452 // Pass altered volume to effects before volume controller
10453 // and requested volume to effects after controller
10454 uint32_t lVol = newLeft;
10455 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010456
Mathias Agopian65ab4712010-07-14 17:59:35 -070010457 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010458 if ((int)i == ctrlIdx) continue;
10459 // this also works for ctrlIdx == -1 when there is no volume controller
10460 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010461 lVol = *left;
10462 rVol = *right;
10463 }
10464 mEffects[i]->setVolume(&lVol, &rVol, false);
10465 }
10466 *left = newLeft;
10467 *right = newRight;
10468
10469 return hasControl;
10470}
10471
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010472void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010473{
10474 const size_t SIZE = 256;
10475 char buffer[SIZE];
10476 String8 result;
10477
10478 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10479 result.append(buffer);
10480
10481 bool locked = tryLock(mLock);
10482 // failed to lock - AudioFlinger is probably deadlocked
10483 if (!locked) {
10484 result.append("\tCould not lock mutex:\n");
10485 }
10486
Eric Laurentcab11242010-07-15 12:50:15 -070010487 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10488 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010489 mEffects.size(),
10490 (uint32_t)mInBuffer,
10491 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010492 mActiveTrackCnt);
10493 result.append(buffer);
10494 write(fd, result.string(), result.size());
10495
10496 for (size_t i = 0; i < mEffects.size(); ++i) {
10497 sp<EffectModule> effect = mEffects[i];
10498 if (effect != 0) {
10499 effect->dump(fd, args);
10500 }
10501 }
10502
10503 if (locked) {
10504 mLock.unlock();
10505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010506}
10507
Eric Laurent59255e42011-07-27 19:49:51 -070010508// must be called with ThreadBase::mLock held
10509void AudioFlinger::EffectChain::setEffectSuspended_l(
10510 const effect_uuid_t *type, bool suspend)
10511{
10512 sp<SuspendedEffectDesc> desc;
10513 // use effect type UUID timelow as key as there is no real risk of identical
10514 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010515 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010516 if (suspend) {
10517 if (index >= 0) {
10518 desc = mSuspendedEffects.valueAt(index);
10519 } else {
10520 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010521 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010522 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010523 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010524 }
10525 if (desc->mRefCount++ == 0) {
10526 sp<EffectModule> effect = getEffectIfEnabled(type);
10527 if (effect != 0) {
10528 desc->mEffect = effect;
10529 effect->setSuspended(true);
10530 effect->setEnabled(false);
10531 }
10532 }
10533 } else {
10534 if (index < 0) {
10535 return;
10536 }
10537 desc = mSuspendedEffects.valueAt(index);
10538 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010539 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010540 desc->mRefCount = 1;
10541 }
10542 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010543 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010544 if (desc->mEffect != 0) {
10545 sp<EffectModule> effect = desc->mEffect.promote();
10546 if (effect != 0) {
10547 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010548 effect->lock();
10549 EffectHandle *handle = effect->controlHandle_l();
10550 if (handle != NULL && !handle->destroyed_l()) {
10551 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010552 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010553 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010554 }
10555 desc->mEffect.clear();
10556 }
10557 mSuspendedEffects.removeItemsAt(index);
10558 }
10559 }
10560}
10561
10562// must be called with ThreadBase::mLock held
10563void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10564{
10565 sp<SuspendedEffectDesc> desc;
10566
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010567 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010568 if (suspend) {
10569 if (index >= 0) {
10570 desc = mSuspendedEffects.valueAt(index);
10571 } else {
10572 desc = new SuspendedEffectDesc();
10573 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010574 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010575 }
10576 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010577 Vector< sp<EffectModule> > effects;
10578 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010579 for (size_t i = 0; i < effects.size(); i++) {
10580 setEffectSuspended_l(&effects[i]->desc().type, true);
10581 }
10582 }
10583 } else {
10584 if (index < 0) {
10585 return;
10586 }
10587 desc = mSuspendedEffects.valueAt(index);
10588 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010589 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010590 desc->mRefCount = 1;
10591 }
10592 if (--desc->mRefCount == 0) {
10593 Vector<const effect_uuid_t *> types;
10594 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10595 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10596 continue;
10597 }
10598 types.add(&mSuspendedEffects.valueAt(i)->mType);
10599 }
10600 for (size_t i = 0; i < types.size(); i++) {
10601 setEffectSuspended_l(types[i], false);
10602 }
Steve Block3856b092011-10-20 11:56:00 +010010603 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010604 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10605 }
10606 }
10607}
10608
Eric Laurent6bffdb82011-09-23 08:40:41 -070010609
10610// The volume effect is used for automated tests only
10611#ifndef OPENSL_ES_H_
10612static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10613 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10614const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10615#endif //OPENSL_ES_H_
10616
Eric Laurentdb7c0792011-08-10 10:37:50 -070010617bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10618{
10619 // auxiliary effects and visualizer are never suspended on output mix
10620 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10621 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010622 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10623 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010624 return false;
10625 }
10626 return true;
10627}
10628
Glenn Kastend0539712012-01-30 12:56:03 -080010629void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010630{
Glenn Kastend0539712012-01-30 12:56:03 -080010631 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010632 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010633 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10634 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010635 }
Eric Laurent59255e42011-07-27 19:49:51 -070010636 }
Eric Laurent59255e42011-07-27 19:49:51 -070010637}
10638
10639sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10640 const effect_uuid_t *type)
10641{
Glenn Kasten090f0192012-01-30 13:00:02 -080010642 sp<EffectModule> effect = getEffectFromType_l(type);
10643 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010644}
10645
10646void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10647 bool enabled)
10648{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010649 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010650 if (enabled) {
10651 if (index < 0) {
10652 // if the effect is not suspend check if all effects are suspended
10653 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10654 if (index < 0) {
10655 return;
10656 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010657 if (!isEffectEligibleForSuspend(effect->desc())) {
10658 return;
10659 }
Eric Laurent59255e42011-07-27 19:49:51 -070010660 setEffectSuspended_l(&effect->desc().type, enabled);
10661 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010662 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010663 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010664 return;
10665 }
Eric Laurent59255e42011-07-27 19:49:51 -070010666 }
Steve Block3856b092011-10-20 11:56:00 +010010667 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010668 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010669 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10670 // if effect is requested to suspended but was not yet enabled, supend it now.
10671 if (desc->mEffect == 0) {
10672 desc->mEffect = effect;
10673 effect->setEnabled(false);
10674 effect->setSuspended(true);
10675 }
10676 } else {
10677 if (index < 0) {
10678 return;
10679 }
Steve Block3856b092011-10-20 11:56:00 +010010680 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010681 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010682 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10683 desc->mEffect.clear();
10684 effect->setSuspended(false);
10685 }
10686}
10687
Mathias Agopian65ab4712010-07-14 17:59:35 -070010688#undef LOG_TAG
10689#define LOG_TAG "AudioFlinger"
10690
10691// ----------------------------------------------------------------------------
10692
10693status_t AudioFlinger::onTransact(
10694 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10695{
10696 return BnAudioFlinger::onTransact(code, data, reply, flags);
10697}
10698
Mathias Agopian65ab4712010-07-14 17:59:35 -070010699}; // namespace android