blob: 5975b62622c5fc7e02be33342b13ed61060b7d81 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
vivek mehta2192bc92012-12-04 11:46:08 -08004** Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
5**
6** Copyright (c) 2012, The Linux Foundation. All rights reserved.
7** Not a Contribution, Apache license notifications and license are retained
8** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07009**
10** Licensed under the Apache License, Version 2.0 (the "License");
11** you may not use this file except in compliance with the License.
12** You may obtain a copy of the License at
13**
14** http://www.apache.org/licenses/LICENSE-2.0
15**
16** Unless required by applicable law or agreed to in writing, software
17** distributed under the License is distributed on an "AS IS" BASIS,
18** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19** See the License for the specific language governing permissions and
20** limitations under the License.
21*/
22
23
24#define LOG_TAG "AudioFlinger"
25//#define LOG_NDEBUG 0
26
27#include <math.h>
28#include <signal.h>
29#include <sys/time.h>
30#include <sys/resource.h>
31
Gloria Wang9ee159b2011-02-24 14:51:45 -080032#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/IServiceManager.h>
34#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070035#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
38#include <utils/String16.h>
39#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070040#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041
Dima Zavinfce7a472011-04-19 22:30:36 -070042#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080044#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#undef ADD_BATTERY_DATA
47
48#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080049#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080050#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070051#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include <private/media/AudioTrackShared.h>
54#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070057#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59#include "AudioMixer.h"
60#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080061#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070064#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070065#include <audio_effects/effect_ns.h>
66#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
Glenn Kasten3b21c502011-12-15 09:52:39 -080068#include <audio_utils/primitives.h>
69
Eric Laurentfeb0db62011-07-22 09:04:31 -070070#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080071
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070077
John Grossman4ff14ba2012-02-08 16:37:41 -080078#include <common_time/cc_helper.h>
79#include <common_time/local_clock.h>
80
Glenn Kasten58912562012-04-03 10:45:00 -070081#include "FastMixer.h"
82
83// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070084#include <media/nbaio/AudioStreamOutSink.h>
85#include <media/nbaio/MonoPipe.h>
86#include <media/nbaio/MonoPipeReader.h>
87#include <media/nbaio/Pipe.h>
88#include <media/nbaio/PipeReader.h>
89#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070090
Glenn Kasten1dc28b72012-04-24 10:01:03 -070091#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070092
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
John Grossman1c345192012-03-27 14:00:17 -070095// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
Eric Laurentde070132010-07-13 04:45:46 -0700107
vivek mehta2192bc92012-12-04 11:46:08 -0800108#ifdef QCOM_HARDWARE
109#define DIRECT_TRACK_EOS 1
Ravishankar Sarawadi20017912013-02-27 18:47:54 +0100110#define DIRECT_TRACK_HW_FAIL 6
vivek mehta2192bc92012-12-04 11:46:08 -0800111static const char lockName[] = "DirectTrack";
112#endif
113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114namespace android {
115
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800116static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
117static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800120static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121
122// retry counts for buffer fill timeout
123// 50 * ~20msecs = 1 second
124static const int8_t kMaxTrackRetries = 50;
125static const int8_t kMaxTrackStartupRetries = 50;
126// allow less retry attempts on direct output thread.
127// direct outputs can be a scarce resource in audio hardware and should
128// be released as quickly as possible.
129static const int8_t kMaxTrackRetriesDirect = 2;
130
131static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800132static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Glenn Kasten7dede872011-12-13 11:04:14 -0800134// don't warn about blocked writes or record buffer overflows more often than this
135static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700137// RecordThread loop sleep time upon application overrun or audio HAL read error
138static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700139
Glenn Kasten7dede872011-12-13 11:04:14 -0800140// maximum time to wait for setParameters to complete
141static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700142
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143// minimum sleep time for the mixer thread loop when tracks are active but in underrun
144static const uint32_t kMinThreadSleepTimeUs = 5000;
145// maximum divider applied to the active sleep time in the mixer thread loop
146static const uint32_t kMaxThreadSleepTimeShift = 2;
147
Glenn Kasten58912562012-04-03 10:45:00 -0700148// minimum normal mix buffer size, expressed in milliseconds rather than frames
149static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150// maximum normal mix buffer size
151static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700152
John Grossman4ff14ba2012-02-08 16:37:41 -0800153nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800154
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700155// Whether to use fast mixer
156static const enum {
157 FastMixer_Never, // never initialize or use: for debugging only
158 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
159 // normal mixer multiplier is 1
160 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700161 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700162 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700163 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700164 // FIXME for FastMixer_Dynamic:
165 // Supporting this option will require fixing HALs that can't handle large writes.
166 // For example, one HAL implementation returns an error from a large write,
167 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
168 // We could either fix the HAL implementations, or provide a wrapper that breaks
169 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
170} kUseFastMixer = FastMixer_Static;
171
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700172static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
173 // AudioFlinger::setParameters() updates, other threads read w/o lock
174
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700175// Priorities for requestPriority
176static const int kPriorityAudioApp = 2;
177static const int kPriorityFastMixer = 3;
178
Glenn Kasten3ed29202012-08-07 15:24:44 -0700179// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
180// for the track. The client then sub-divides this into smaller buffers for its use.
181// Currently the client uses double-buffering by default, but doesn't tell us about that.
182// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700183// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
184// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700185// See the client's minBufCount and mNotificationFramesAct calculations for details.
186static const int kFastTrackMultiplier = 2;
187
Mathias Agopian65ab4712010-07-14 17:59:35 -0700188// ----------------------------------------------------------------------------
189
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191// To collect the amplifier usage
192static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800193 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
194 if (service == NULL) {
195 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800196 return;
197 }
198
199 service->addBatteryData(params);
200}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700201#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800202
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700203static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700204{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700205 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 int rc;
207
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
209 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
210 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
211 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700212 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700213 }
214 rc = audio_hw_device_open(mod, dev);
215 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
216 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
217 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700218 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700219 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000220#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700221 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
222 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
223 rc = BAD_VALUE;
224 goto out;
225 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100226#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700227 return 0;
228
229out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 *dev = NULL;
231 return rc;
232}
233
vivek mehta2192bc92012-12-04 11:46:08 -0800234static uint32_t getInputChannelCount(uint32_t channels) {
235#ifdef QCOM_HARDWARE
236 // only mono or stereo and 5.1 are supported for input sources
237 return popcount((channels) & (AUDIO_CHANNEL_IN_STEREO | AUDIO_CHANNEL_IN_MONO | AUDIO_CHANNEL_IN_5POINT1));
238#else
239 return popcount(channels);
240#endif
241}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242// ----------------------------------------------------------------------------
243
244AudioFlinger::AudioFlinger()
245 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800246 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700247 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800248 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800249 mMasterMute(false),
250 mNextUniqueId(1),
251 mMode(AUDIO_MODE_INVALID),
252 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700254}
255
256void AudioFlinger::onFirstRef()
257{
Dima Zavin799a70e2011-04-18 16:57:27 -0700258 int rc = 0;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800259#ifdef QCOM_HARDWARE
260 mA2DPHandle = -1;
261#endif
Dima Zavinfce7a472011-04-19 22:30:36 -0700262
Eric Laurent93575202011-01-18 18:39:02 -0800263 Mutex::Autolock _l(mLock);
264
Dima Zavin799a70e2011-04-18 16:57:27 -0700265 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800266#ifdef QCOM_HARDWARE
267 mLPASessionId = -2; // -2 is invalid session ID
268 mIsEffectConfigChanged = false;
269 mLPAEffectChain = NULL;
270#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800271 char val_str[PROPERTY_VALUE_MAX] = { 0 };
272 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
273 uint32_t int_val;
274 if (1 == sscanf(val_str, "%u", &int_val)) {
275 mStandbyTimeInNsecs = milliseconds(int_val);
276 ALOGI("Using %u mSec as standby time.", int_val);
277 } else {
278 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
279 ALOGI("Using default %u mSec as standby time.",
280 (uint32_t)(mStandbyTimeInNsecs / 1000000));
281 }
282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283
Eric Laurenta4c5a552012-03-29 10:12:40 -0700284 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285}
286
287AudioFlinger::~AudioFlinger()
288{
289 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700290 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700291 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700292 }
293 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700294 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700295 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700297
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800298 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
299 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700300 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
301 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302 }
303}
304
Eric Laurenta4c5a552012-03-29 10:12:40 -0700305static const char * const audio_interfaces[] = {
306 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
307 AUDIO_HARDWARE_MODULE_ID_A2DP,
308 AUDIO_HARDWARE_MODULE_ID_USB,
309};
310#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
311
John Grossmanee578c02012-07-23 17:05:46 -0700312AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
313 audio_module_handle_t module,
314 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700315{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700316 // if module is 0, the request comes from an old policy manager and we should load
317 // well known modules
318 if (module == 0) {
319 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
320 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
321 loadHwModule_l(audio_interfaces[i]);
322 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700323 // then try to find a module supporting the requested device.
324 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
325 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
326 audio_hw_device_t *dev = audioHwDevice->hwDevice();
327 if ((dev->get_supported_devices != NULL) &&
328 (dev->get_supported_devices(dev) & devices) == devices)
329 return audioHwDevice;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800330#ifdef ICS_AUDIO_BLOB
331 else if (dev->get_supported_devices == NULL && i != 0 &&
332 devices == 0x80)
333 // Reasonably safe assumption: A non-primary HAL without
334 // get_supported_devices is a locally-built A2DP binary
335 return audioHwDevice;
336#endif
Eric Laurentf1c04f92012-08-28 14:26:53 -0700337 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700338 } else {
339 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700340 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
341 if (audioHwDevice != NULL) {
342 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700343 }
344 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700345
Dima Zavin799a70e2011-04-18 16:57:27 -0700346 return NULL;
347}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700349void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350{
351 const size_t SIZE = 256;
352 char buffer[SIZE];
353 String8 result;
354
355 result.append("Clients:\n");
356 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800357 sp<Client> client = mClients.valueAt(i).promote();
358 if (client != 0) {
359 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
360 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 }
362 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700363
364 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800365 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700366 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
367 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800368 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700369 result.append(buffer);
370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372}
373
374
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700375void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376{
377 const size_t SIZE = 256;
378 char buffer[SIZE];
379 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800380 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381
John Grossman4ff14ba2012-02-08 16:37:41 -0800382 snprintf(buffer, SIZE, "Hardware status: %d\n"
383 "Standby Time mSec: %u\n",
384 hardwareStatus,
385 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386 result.append(buffer);
387 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700390void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391{
392 const size_t SIZE = 256;
393 char buffer[SIZE];
394 String8 result;
395 snprintf(buffer, SIZE, "Permission Denial: "
396 "can't dump AudioFlinger from pid=%d, uid=%d\n",
397 IPCThreadState::self()->getCallingPid(),
398 IPCThreadState::self()->getCallingUid());
399 result.append(buffer);
400 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401}
402
403static bool tryLock(Mutex& mutex)
404{
405 bool locked = false;
406 for (int i = 0; i < kDumpLockRetries; ++i) {
407 if (mutex.tryLock() == NO_ERROR) {
408 locked = true;
409 break;
410 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800411 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 }
413 return locked;
414}
415
416status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
417{
Glenn Kasten44deb052012-02-05 18:09:08 -0800418 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 dumpPermissionDenial(fd, args);
420 } else {
421 // get state of hardware lock
422 bool hardwareLocked = tryLock(mHardwareLock);
423 if (!hardwareLocked) {
424 String8 result(kHardwareLockedString);
425 write(fd, result.string(), result.size());
426 } else {
427 mHardwareLock.unlock();
428 }
429
430 bool locked = tryLock(mLock);
431
432 // failed to lock - AudioFlinger is probably deadlocked
433 if (!locked) {
434 String8 result(kDeadlockedString);
435 write(fd, result.string(), result.size());
436 }
437
438 dumpClients(fd, args);
439 dumpInternals(fd, args);
440
441 // dump playback threads
442 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
443 mPlaybackThreads.valueAt(i)->dump(fd, args);
444 }
445
446 // dump record threads
447 for (size_t i = 0; i < mRecordThreads.size(); i++) {
448 mRecordThreads.valueAt(i)->dump(fd, args);
449 }
450
Dima Zavin799a70e2011-04-18 16:57:27 -0700451 // dump all hardware devs
452 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700453 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700454 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 }
456 if (locked) mLock.unlock();
457 }
458 return NO_ERROR;
459}
460
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800461sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
462{
463 // If pid is already in the mClients wp<> map, then use that entry
464 // (for which promote() is always != 0), otherwise create a new entry and Client.
465 sp<Client> client = mClients.valueFor(pid).promote();
466 if (client == 0) {
467 client = new Client(this, pid);
468 mClients.add(pid, client);
469 }
470
471 return client;
472}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473
474// IAudioFlinger interface
475
476
477sp<IAudioTrack> AudioFlinger::createTrack(
478 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800479 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800481 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700482 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800484 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800486 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800487 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 int *sessionId,
489 status_t *status)
490{
491 sp<PlaybackThread::Track> track;
492 sp<TrackHandle> trackHandle;
493 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494 status_t lStatus;
495 int lSessionId;
496
Glenn Kasten263709e2012-01-06 08:40:01 -0800497 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
498 // but if someone uses binder directly they could bypass that and cause us to crash
499 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000500 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 lStatus = BAD_VALUE;
502 goto Exit;
503 }
504
505 {
506 Mutex::Autolock _l(mLock);
507 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700508 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000510 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 lStatus = BAD_VALUE;
512 goto Exit;
513 }
514
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800515 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516
Steve Block3856b092011-10-20 11:56:00 +0100517 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700518 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700519 // check if an effect chain with the same session ID is present on another
520 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700521 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700522 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
523 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700524 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700525 if (sessions & PlaybackThread::EFFECT_SESSION) {
526 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700527 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700528 }
Eric Laurentde070132010-07-13 04:45:46 -0700529 }
530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 lSessionId = *sessionId;
532 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700533 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700534 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700535 if (sessionId != NULL) {
536 *sessionId = lSessionId;
537 }
538 }
Steve Block3856b092011-10-20 11:56:00 +0100539 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540
541 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800542 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700543
544 // move effect chain to this output thread if an effect on same session was waiting
545 // for a track to be created
546 if (lStatus == NO_ERROR && effectThread != NULL) {
547 Mutex::Autolock _dl(thread->mLock);
548 Mutex::Autolock _sl(effectThread->mLock);
549 moveEffectChain_l(lSessionId, effectThread, thread, true);
550 }
Eric Laurenta011e352012-03-29 15:51:43 -0700551
552 // Look for sync events awaiting for a session to be used.
553 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
554 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
555 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700556 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700557 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700558 } else {
559 mPendingSyncEvents[i]->cancel();
560 }
Eric Laurenta011e352012-03-29 15:51:43 -0700561 mPendingSyncEvents.removeAt(i);
562 i--;
563 }
564 }
565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 }
567 if (lStatus == NO_ERROR) {
568 trackHandle = new TrackHandle(track);
569 } else {
570 // remove local strong reference to Client before deleting the Track so that the Client
571 // destructor is called by the TrackBase destructor with mLock held
572 client.clear();
573 track.clear();
574 }
575
576Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700577 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 *status = lStatus;
579 }
580 return trackHandle;
581}
582
vivek mehta2192bc92012-12-04 11:46:08 -0800583#ifdef QCOM_HARDWARE
584sp<IDirectTrack> AudioFlinger::createDirectTrack(
585 pid_t pid,
586 uint32_t sampleRate,
587 audio_channel_mask_t channelMask,
588 audio_io_handle_t output,
589 int *sessionId,
590 IDirectTrackClient *client,
591 audio_stream_type_t streamType,
592 status_t *status)
593{
594 *status = NO_ERROR;
595 status_t lStatus = NO_ERROR;
596 sp<IDirectTrack> track = NULL;
597 DirectAudioTrack* directTrack = NULL;
598 Mutex::Autolock _l(mLock);
599
600 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
601 *sessionId, sampleRate, channelMask);
602 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
603 if(desc == NULL) {
604 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
605 lStatus = BAD_VALUE;
606 goto Exit;
607 }
608 desc->mStreamType = streamType;
609 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
610 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
611 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
612 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
613 // Check if the session ID is already associated with a track
614 uint32_t sessions = t->hasAudioSession(*sessionId);
615
616 // check if an effect with same session ID is waiting for a ssession to be created
617 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
618 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
619 // Clear reference to previous effect chain if any
620 t->mLock.lock();
621 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
622 mLPAEffectChain = t->getEffectChain_l(*sessionId);
623 t->mLock.unlock();
624 }
625 }
626 mLPASessionId = *sessionId;
627 if (mLPAEffectChain != NULL) {
628 mLPAEffectChain->setLPAFlag(true);
629 // For LPA, the volume will be applied in DSP. No need for volume
630 // control in the Effect chain, so setting it to unity.
631 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
632 mLPAEffectChain->setVolume_l(&volume,&volume);
633 } else {
634 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
635 }
636 mLPASampleRate = sampleRate;
637 mLPANumChannels = popcount(channelMask);
638 } else {
639 if(sessionId != NULL) {
640 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
641 }
642 }
643 }
644 mLock.unlock();
645 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
646 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
647 mLock.lock();
648 if (directTrack != 0) {
649 track = dynamic_cast<IDirectTrack *>(directTrack);
650 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
651 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
652 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
653 } else {
654 lStatus = BAD_VALUE;
655 }
656Exit:
657 if(lStatus) {
658 if (track != NULL) {
659 track.clear();
660 }
661 *status = lStatus;
662 }
663 return track;
664}
665
666void AudioFlinger::deleteEffectSession()
667{
668 Mutex::Autolock _l(mLock);
669 ALOGV("deleteSession");
670 // -2 is invalid session ID
671 mLPASessionId = -2;
672 if (mLPAEffectChain != NULL) {
673 mLPAEffectChain->setLPAFlag(false);
674 size_t i, numEffects = mLPAEffectChain->getNumEffects();
675 for(i = 0; i < numEffects; i++) {
676 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
677 effect->setInBuffer(mLPAEffectChain->inBuffer());
678 if (i == numEffects-1) {
679 effect->setOutBuffer(mLPAEffectChain->outBuffer());
680 } else {
681 effect->setOutBuffer(mLPAEffectChain->inBuffer());
682 }
683 effect->configure();
684 }
685 mLPAEffectChain.clear();
686 mLPAEffectChain = NULL;
687 }
688}
689
690// ToDo: Should we go ahead with this frameCount?
691#define DEAFULT_FRAME_COUNT 1200
692void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
693{
694 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
695 // This might be the first buffer to apply effects after effect config change
696 // should not skip effects processing
697 mIsEffectConfigChanged = false;
698
699 volatile size_t numEffects = 0;
700 if(mLPAEffectChain != NULL) {
701 numEffects = mLPAEffectChain->getNumEffects();
702 }
703
704 if( numEffects > 0) {
705 size_t i = 0;
706 int16_t *pIn = inBuffer;
707 int16_t *pOut = outBuffer;
708
709 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
710
711 while(frameCount > 0) {
712 if(mLPAEffectChain == NULL) {
713 ALOGV("LPA Effect Chain is removed - No effects processing !!");
714 numEffects = 0;
715 break;
716 }
717 mLPAEffectChain->lock();
718
719 numEffects = mLPAEffectChain->getNumEffects();
720 if(!numEffects) {
721 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
722 mLPAEffectChain->unlock();
723 break;
724 }
725
726 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
727 bool isEffectEnabled = false;
728 for(i = 0; i < numEffects; i++) {
729 // If effect configuration is changed while applying effects do not process further
730 if(mIsEffectConfigChanged) {
731 mLPAEffectChain->unlock();
732 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
733 return;
734 }
735 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
736 if(effect == NULL) {
737 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
738 mLPAEffectChain->unlock();
739 return;
740 }
741 if(i == 0) {
742 // For the first set input and output buffers different
743 isEffectEnabled = effect->isProcessEnabled();
744 effect->setInBuffer(pIn);
745 effect->setOutBuffer(pOut);
746 } else {
747 // For the remaining use previous effect's output buffer as input buffer
748 effect->setInBuffer(pOut);
749 effect->setOutBuffer(pOut);
750 }
751 // true indicates that it is being applied on LPA output
752 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
753 }
754
755 if(isEffectEnabled) {
756 // Clear the output buffer
757 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
758 } else {
759 // Copy input buffer content to the output buffer
760 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
761 }
762
763 mLPAEffectChain->process_l();
764
765 mLPAEffectChain->unlock();
766
767 // Update input and output buffer pointers
768 pIn += (outFrameCount * mLPANumChannels);
769 pOut += (outFrameCount * mLPANumChannels);
770 frameCount -= outFrameCount;
771 }
772 }
773
774 if (!numEffects) {
775 ALOGV("applyEffectsOn: There are no effects to be applied");
776 if(inBuffer != outBuffer) {
777 // No effect applied so just copy input buffer to output buffer
778 memcpy(outBuffer, inBuffer, size);
779 }
780 }
781}
782#endif
783
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800784uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785{
786 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800787#ifdef QCOM_HARDWARE
788 if (!mDirectAudioTracks.isEmpty()) {
789 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
790 if(desc != NULL) {
791 return desc->stream->common.get_sample_rate(&desc->stream->common);
792 }
793 }
794#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 PlaybackThread *thread = checkPlaybackThread_l(output);
796 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000797 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 return 0;
799 }
800 return thread->sampleRate();
801}
802
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800803int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804{
805 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800806#ifdef QCOM_HARDWARE
807 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
808 if(desc != NULL) {
809 return desc->stream->common.get_channels(&desc->stream->common);
810 }
811#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 PlaybackThread *thread = checkPlaybackThread_l(output);
813 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000814 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return 0;
816 }
817 return thread->channelCount();
818}
819
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800820audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
822 Mutex::Autolock _l(mLock);
823 PlaybackThread *thread = checkPlaybackThread_l(output);
824 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000825 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800826 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 }
828 return thread->format();
829}
830
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800831size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832{
833 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800834#ifdef QCOM_HARDWARE
835 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
836 if(desc != NULL) {
837 return desc->stream->common.get_buffer_size(&desc->stream->common);
838 }
839#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 PlaybackThread *thread = checkPlaybackThread_l(output);
841 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000842 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 return 0;
844 }
Glenn Kasten58912562012-04-03 10:45:00 -0700845 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
846 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 return thread->frameCount();
848}
849
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800850uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851{
852 Mutex::Autolock _l(mLock);
853 PlaybackThread *thread = checkPlaybackThread_l(output);
854 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000855 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 return 0;
857 }
858 return thread->latency();
859}
860
861status_t AudioFlinger::setMasterVolume(float value)
862{
Eric Laurenta1884f92011-08-23 08:25:03 -0700863 status_t ret = initCheck();
864 if (ret != NO_ERROR) {
865 return ret;
866 }
867
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 // check calling permissions
869 if (!settingsAllowed()) {
870 return PERMISSION_DENIED;
871 }
872
Dorian Snyderf32d5702013-03-01 14:25:46 -0800873#ifdef QCOM_HARDWARE
874 mA2DPHandle = -1;
875#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -0700876 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700877 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700878
John Grossmanee578c02012-07-23 17:05:46 -0700879 // Set master volume in the HALs which support it.
880 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
881 AutoMutex lock(mHardwareLock);
882 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800883
John Grossmanee578c02012-07-23 17:05:46 -0700884 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
885 if (dev->canSetMasterVolume()) {
886 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800887 }
John Grossmanee578c02012-07-23 17:05:46 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890
John Grossmanee578c02012-07-23 17:05:46 -0700891 // Now set the master volume in each playback thread. Playback threads
892 // assigned to HALs which do not have master volume support will apply
893 // master volume during the mix operation. Threads with HALs which do
894 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800895 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700896 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897
898 return NO_ERROR;
899}
900
Glenn Kastenf78aee72012-01-04 11:00:47 -0800901status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902{
Eric Laurenta1884f92011-08-23 08:25:03 -0700903 status_t ret = initCheck();
904 if (ret != NO_ERROR) {
905 return ret;
906 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907
908 // check calling permissions
909 if (!settingsAllowed()) {
910 return PERMISSION_DENIED;
911 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800912 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000913 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 return BAD_VALUE;
915 }
916
917 { // scope for the lock
918 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700919 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700921 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 mHardwareStatus = AUDIO_HW_IDLE;
923 }
924
925 if (NO_ERROR == ret) {
926 Mutex::Autolock _l(mLock);
927 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800928 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700929 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931
932 return ret;
933}
934
935status_t AudioFlinger::setMicMute(bool state)
936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return ret;
940 }
941
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 // check calling permissions
943 if (!settingsAllowed()) {
944 return PERMISSION_DENIED;
945 }
946
947 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700948 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700950 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 mHardwareStatus = AUDIO_HW_IDLE;
952 return ret;
953}
954
955bool AudioFlinger::getMicMute() const
956{
Eric Laurenta1884f92011-08-23 08:25:03 -0700957 status_t ret = initCheck();
958 if (ret != NO_ERROR) {
959 return false;
960 }
961
Dima Zavinfce7a472011-04-19 22:30:36 -0700962 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800963 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700964 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700966 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 mHardwareStatus = AUDIO_HW_IDLE;
968 return state;
969}
970
971status_t AudioFlinger::setMasterMute(bool muted)
972{
John Grossmand8f178d2012-07-20 14:51:35 -0700973 status_t ret = initCheck();
974 if (ret != NO_ERROR) {
975 return ret;
976 }
977
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978 // check calling permissions
979 if (!settingsAllowed()) {
980 return PERMISSION_DENIED;
981 }
982
John Grossmanee578c02012-07-23 17:05:46 -0700983 Mutex::Autolock _l(mLock);
984 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700985
John Grossmanee578c02012-07-23 17:05:46 -0700986 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100987#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700988 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
989 AutoMutex lock(mHardwareLock);
990 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700991
John Grossmanee578c02012-07-23 17:05:46 -0700992 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
993 if (dev->canSetMasterMute()) {
994 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700995 }
John Grossmanee578c02012-07-23 17:05:46 -0700996 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700997 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100998#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700999
John Grossmanee578c02012-07-23 17:05:46 -07001000 // Now set the master mute in each playback thread. Playback threads
1001 // assigned to HALs which do not have master mute support will apply master
1002 // mute during the mix operation. Threads with HALs which do support master
1003 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001004 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -07001005 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006
1007 return NO_ERROR;
1008}
1009
1010float AudioFlinger::masterVolume() const
1011{
Glenn Kasten98067102011-12-13 11:47:54 -08001012 Mutex::Autolock _l(mLock);
1013 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014}
1015
1016bool AudioFlinger::masterMute() const
1017{
Glenn Kasten98067102011-12-13 11:47:54 -08001018 Mutex::Autolock _l(mLock);
1019 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020}
1021
John Grossman4ff14ba2012-02-08 16:37:41 -08001022float AudioFlinger::masterVolume_l() const
1023{
John Grossman4ff14ba2012-02-08 16:37:41 -08001024 return mMasterVolume;
1025}
1026
John Grossmand8f178d2012-07-20 14:51:35 -07001027bool AudioFlinger::masterMute_l() const
1028{
John Grossmanee578c02012-07-23 17:05:46 -07001029 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001030}
1031
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001032status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1033 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034{
1035 // check calling permissions
1036 if (!settingsAllowed()) {
1037 return PERMISSION_DENIED;
1038 }
1039
Glenn Kasten263709e2012-01-06 08:40:01 -08001040 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001041 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 return BAD_VALUE;
1043 }
1044
1045 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001046#ifdef QCOM_HARDWARE
1047 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1048 AudioSessionDescriptor *desc = NULL;
1049 if (!mDirectAudioTracks.isEmpty()) {
1050 desc = mDirectAudioTracks.valueFor(output);
1051 if (desc != NULL) {
1052 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1053 if (desc->mStreamType == stream) {
1054 mStreamTypes[stream].volume = value;
Dorian Snyderf32d5702013-03-01 14:25:46 -08001055 desc->mVolumeScale = value;
vivek mehta2192bc92012-12-04 11:46:08 -08001056 desc->stream->set_volume(desc->stream,
1057 desc->mVolumeLeft * mStreamTypes[stream].volume,
1058 desc->mVolumeRight* mStreamTypes[stream].volume);
1059 return NO_ERROR;
1060 }
1061 }
1062 }
1063#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 PlaybackThread *thread = NULL;
1065 if (output) {
1066 thread = checkPlaybackThread_l(output);
1067 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001068#ifdef QCOM_HARDWARE
1069 if (desc != NULL) {
1070 return NO_ERROR;
1071 }
1072#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 return BAD_VALUE;
1074 }
vivek mehta2192bc92012-12-04 11:46:08 -08001075
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 }
1077
1078 mStreamTypes[stream].volume = value;
1079
1080 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001081 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001082 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 }
1084 } else {
1085 thread->setStreamVolume(stream, value);
1086 }
1087
1088 return NO_ERROR;
1089}
1090
Glenn Kastenfff6d712012-01-12 16:38:12 -08001091status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093 // check calling permissions
1094 if (!settingsAllowed()) {
1095 return PERMISSION_DENIED;
1096 }
1097
Glenn Kasten263709e2012-01-06 08:40:01 -08001098 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001099 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001100 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101 return BAD_VALUE;
1102 }
1103
Eric Laurent93575202011-01-18 18:39:02 -08001104 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 mStreamTypes[stream].mute = muted;
1106 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001107 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108
1109 return NO_ERROR;
1110}
1111
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001112float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113{
Glenn Kasten263709e2012-01-06 08:40:01 -08001114 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 return 0.0f;
1116 }
1117
1118 AutoMutex lock(mLock);
1119 float volume;
1120 if (output) {
1121 PlaybackThread *thread = checkPlaybackThread_l(output);
1122 if (thread == NULL) {
1123 return 0.0f;
1124 }
1125 volume = thread->streamVolume(stream);
1126 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001127 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 }
1129
1130 return volume;
1131}
1132
Glenn Kastenfff6d712012-01-12 16:38:12 -08001133bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134{
Glenn Kasten263709e2012-01-06 08:40:01 -08001135 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 return true;
1137 }
1138
Glenn Kasten6637baa2012-01-09 09:40:36 -08001139 AutoMutex lock(mLock);
1140 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141}
1142
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001143status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001145 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1147 // check calling permissions
1148 if (!settingsAllowed()) {
1149 return PERMISSION_DENIED;
1150 }
1151
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 // ioHandle == 0 means the parameters are global to the audio hardware interface
1153 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001154 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001155 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001156 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001157 AutoMutex lock(mHardwareLock);
1158 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1159 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1160 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1161 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1162 final_result = result ?: final_result;
1163 }
1164 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001165 }
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001166#ifdef QCOM_HARDWARE
1167 AudioParameter param = AudioParameter(keyValuePairs);
1168 String8 value, key;
1169 int i = 0;
1170
1171 key = String8(AudioParameter::keyADSPStatus);
1172 if (param.get(key, value) == NO_ERROR) {
1173 ALOGV("Set keyADSPStatus:%s", value.string());
1174 if (value == "ONLINE" || value == "OFFLINE") {
1175 if (!mDirectAudioTracks.isEmpty()) {
1176 for (i=0; i < mDirectAudioTracks.size(); i++) {
1177 mDirectAudioTracks.valueAt(i)->stream->common.set_parameters(
1178 &mDirectAudioTracks.valueAt(i)->stream->common, keyValuePairs.string());
1179 }
1180 }
1181 }
1182 }
1183#else
Eric Laurent59bd0da2011-08-01 09:52:20 -07001184 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1185 AudioParameter param = AudioParameter(keyValuePairs);
1186 String8 value;
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001187#endif
1188
Eric Laurent59bd0da2011-08-01 09:52:20 -07001189 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001190 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1191 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001192 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1193 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001194 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001195 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1196 // collect all of the thread's session IDs
1197 KeyedVector<int, bool> ids = thread->sessionIds();
1198 // suspend effects associated with those session IDs
1199 for (size_t j = 0; j < ids.size(); ++j) {
1200 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001201 thread->setEffectSuspended(FX_IID_AEC,
1202 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001203 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001204 thread->setEffectSuspended(FX_IID_NS,
1205 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001206 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001207 }
1208 }
Eric Laurentbee53372011-08-29 12:42:48 -07001209 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001210 }
1211 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001212 String8 screenState;
1213 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1214 bool isOff = screenState == "off";
1215 if (isOff != (gScreenState & 1)) {
1216 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1217 }
1218 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001219 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 }
1221
vivek mehta2192bc92012-12-04 11:46:08 -08001222#ifdef QCOM_HARDWARE
1223 AudioSessionDescriptor *desc = NULL;
1224 if (!mDirectAudioTracks.isEmpty()) {
1225 desc = mDirectAudioTracks.valueFor(ioHandle);
1226 if (desc != NULL) {
1227 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1228 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
Mingming Yin9b3dd172013-01-10 18:42:38 -08001229 AudioParameter param = AudioParameter(keyValuePairs);
1230 String8 key = String8(AudioParameter::keyRouting);
1231 int device;
1232 if (param.getInt(key, device) == NO_ERROR) {
1233 if(mLPAEffectChain != NULL){
1234 mLPAEffectChain->setDevice_l(device);
1235 audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1236 }
1237 }
vivek mehta2192bc92012-12-04 11:46:08 -08001238 }
1239 }
1240#endif
1241
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1243 // and the thread is exited once the lock is released
1244 sp<ThreadBase> thread;
1245 {
1246 Mutex::Autolock _l(mLock);
1247 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001248 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001250 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001251 // indicate output device change to all input threads for pre processing
1252 AudioParameter param = AudioParameter(keyValuePairs);
1253 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001254 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1255 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001256 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1257 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001258 for (size_t i = 0; i < recordThreads.size(); i++) {
1259 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001260 }
1261 }
vivek mehta2192bc92012-12-04 11:46:08 -08001262 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 }
vivek mehta2192bc92012-12-04 11:46:08 -08001264 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001266 if (thread != 0) {
1267 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 }
1269 return BAD_VALUE;
1270}
1271
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001272String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001274// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1276
Eric Laurenta4c5a552012-03-29 10:12:40 -07001277 Mutex::Autolock _l(mLock);
1278
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001280 String8 out_s8;
1281
Dima Zavin799a70e2011-04-18 16:57:27 -07001282 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001283 char *s;
1284 {
1285 AutoMutex lock(mHardwareLock);
1286 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001287 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001288 s = dev->get_parameters(dev, keys.string());
1289 mHardwareStatus = AUDIO_HW_IDLE;
1290 }
John Grossmanef7740b2012-02-09 11:28:36 -08001291 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001292 free(s);
1293 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001294 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 }
1296
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1298 if (playbackThread != NULL) {
1299 return playbackThread->getParameters(keys);
1300 }
1301 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1302 if (recordThread != NULL) {
1303 return recordThread->getParameters(keys);
1304 }
1305 return String8("");
1306}
1307
Glenn Kastendd8104c2012-07-02 12:42:44 -07001308size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1309 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310{
Eric Laurenta1884f92011-08-23 08:25:03 -07001311 status_t ret = initCheck();
1312 if (ret != NO_ERROR) {
1313 return 0;
1314 }
1315
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001316 AutoMutex lock(mHardwareLock);
1317 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001318 struct audio_config config = {
1319 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001320 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001321 format: format,
1322 };
John Grossmanee578c02012-07-23 17:05:46 -07001323 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001324#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001325 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001326#else
1327 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1328#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001329 mHardwareStatus = AUDIO_HW_IDLE;
1330 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331}
1332
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001333unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001335 Mutex::Autolock _l(mLock);
1336
1337 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1338 if (recordThread != NULL) {
1339 return recordThread->getInputFramesLost();
1340 }
1341 return 0;
1342}
1343
1344status_t AudioFlinger::setVoiceVolume(float value)
1345{
Eric Laurenta1884f92011-08-23 08:25:03 -07001346 status_t ret = initCheck();
1347 if (ret != NO_ERROR) {
1348 return ret;
1349 }
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351 // check calling permissions
1352 if (!settingsAllowed()) {
1353 return PERMISSION_DENIED;
1354 }
1355
1356 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001357 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001358 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001359 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360 mHardwareStatus = AUDIO_HW_IDLE;
1361
1362 return ret;
1363}
1364
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001365status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1366 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001367{
1368 status_t status;
1369
1370 Mutex::Autolock _l(mLock);
1371
1372 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1373 if (playbackThread != NULL) {
1374 return playbackThread->getRenderPosition(halFrames, dspFrames);
1375 }
1376
1377 return BAD_VALUE;
1378}
1379
1380void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1381{
1382
1383 Mutex::Autolock _l(mLock);
1384
vivek mehta2192bc92012-12-04 11:46:08 -08001385 sp<IBinder> binder = client->asBinder();
1386 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 sp<NotificationClient> notificationClient = new NotificationClient(this,
1388 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001389 binder);
Dorian Snyderf32d5702013-03-01 14:25:46 -08001390 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391
vivek mehta2192bc92012-12-04 11:46:08 -08001392 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393
1394 sp<IBinder> binder = client->asBinder();
1395 binder->linkToDeath(notificationClient);
1396
1397 // the config change is always sent from playback or record threads to avoid deadlock
1398 // with AudioSystem::gLock
1399 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001400 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401 }
1402
1403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001404 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 }
1406 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08001407#ifdef QCOM_HARDWARE
1408 // Send the notification to the client only once.
1409 if (mA2DPHandle != -1) {
1410 ALOGV("A2DP active. Notifying the registered client");
1411 client->ioConfigChanged(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
1412 }
1413#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414}
1415
vivek mehta2192bc92012-12-04 11:46:08 -08001416#ifdef QCOM_HARDWARE
1417status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1418{
1419 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1420 Mutex::Autolock _l(mLock);
1421
1422 sp<IBinder> binder = client->asBinder();
1423 int index = mNotificationClients.indexOfKey(binder);
1424 if (index >= 0) {
1425 mNotificationClients.removeItemsAt(index);
1426 return true;
1427 }
1428
1429 return false;
1430}
1431#endif
1432
1433void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434{
1435 Mutex::Autolock _l(mLock);
1436
vivek mehta2192bc92012-12-04 11:46:08 -08001437 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001438
vivek mehta2192bc92012-12-04 11:46:08 -08001439 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001440 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001441 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001442 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001443 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001444 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001445 ALOGV(" pid %d @ %d", ref->mPid, i);
1446 if (ref->mPid == pid) {
1447 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001448 mAudioSessionRefs.removeAt(i);
1449 delete ref;
1450 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001451 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001452 } else {
1453 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001454 }
1455 }
1456 if (removed) {
1457 purgeStaleEffects_l();
1458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459}
1460
1461// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001462void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463{
vivek mehta2192bc92012-12-04 11:46:08 -08001464#ifdef QCOM_HARDWARE
1465 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1466 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1467 mIsEffectConfigChanged = true;
1468 }
1469#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 size_t size = mNotificationClients.size();
1471 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001472 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1473 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 }
1475}
1476
1477// removeClient_l() must be called with AudioFlinger::mLock held
1478void AudioFlinger::removeClient_l(pid_t pid)
1479{
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 mClients.removeItem(pid);
1482}
1483
Eric Laurent717e1282012-06-29 16:36:52 -07001484// getEffectThread_l() must be called with AudioFlinger::mLock held
1485sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1486{
1487 sp<PlaybackThread> thread;
1488
1489 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1490 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1491 ALOG_ASSERT(thread == 0);
1492 thread = mPlaybackThreads.valueAt(i);
1493 }
1494 }
1495
1496 return thread;
1497}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498
1499// ----------------------------------------------------------------------------
1500
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001501AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001502 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001503 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001504 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001505 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001506 // mChannelMask
1507 mChannelCount(0),
1508 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1509 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001510 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1511 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001512 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001513 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514{
1515}
1516
1517AudioFlinger::ThreadBase::~ThreadBase()
1518{
1519 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001520 // do not lock the mutex in destructor
1521 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001522 if (mPowerManager != 0) {
1523 sp<IBinder> binder = mPowerManager->asBinder();
1524 binder->unlinkToDeath(mDeathRecipient);
1525 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526}
1527
1528void AudioFlinger::ThreadBase::exit()
1529{
Steve Block3856b092011-10-20 11:56:00 +01001530 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001531 // do any cleanup required for exit to succeed
1532 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001534 // This lock prevents the following race in thread (uniprocessor for illustration):
1535 // if (!exitPending()) {
1536 // // context switch from here to exit()
1537 // // exit() calls requestExit(), what exitPending() observes
1538 // // exit() calls signal(), which is dropped since no waiters
1539 // // context switch back from exit() to here
1540 // mWaitWorkCV.wait(...);
1541 // // now thread is hung
1542 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001543 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001545 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001547 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1548 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 requestExitAndWait();
1550}
1551
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1553{
1554 status_t status;
1555
Steve Block3856b092011-10-20 11:56:00 +01001556 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 Mutex::Autolock _l(mLock);
1558
1559 mNewParameters.add(keyValuePairs);
1560 mWaitWorkCV.signal();
1561 // wait condition with timeout in case the thread loop has exited
1562 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001563 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 status = mParamStatus;
1565 mWaitWorkCV.signal();
1566 } else {
1567 status = TIMED_OUT;
1568 }
1569 return status;
1570}
1571
vivek mehta2192bc92012-12-04 11:46:08 -08001572#ifdef QCOM_HARDWARE
1573void AudioFlinger::ThreadBase::effectConfigChanged() {
1574 mAudioFlinger->mLock.lock();
1575 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1576 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1577 mAudioFlinger->mLock.unlock();
1578}
1579#endif
1580
Eric Laurent896adcd2012-09-13 11:18:23 -07001581void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582{
1583 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001584 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585}
1586
Eric Laurent896adcd2012-09-13 11:18:23 -07001587// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1588void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589{
Eric Laurent896adcd2012-09-13 11:18:23 -07001590 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1591 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1592 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1593 mWaitWorkCV.signal();
1594}
1595
1596// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1597void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1598{
1599 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1600 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1601 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1602 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 mWaitWorkCV.signal();
1604}
1605
1606void AudioFlinger::ThreadBase::processConfigEvents()
1607{
1608 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001609 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001610 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001611 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 mConfigEvents.removeAt(0);
1613 // release mLock before locking AudioFlinger mLock: lock order is always
1614 // AudioFlinger then ThreadBase to avoid cross deadlock
1615 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001616 switch(event->type()) {
1617 case CFG_EVENT_PRIO: {
1618 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1619 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1620 if (err != 0) {
1621 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1622 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1623 }
1624 } break;
1625 case CFG_EVENT_IO: {
1626 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1627 mAudioFlinger->mLock.lock();
1628 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1629 mAudioFlinger->mLock.unlock();
1630 } break;
1631 default:
1632 ALOGE("processConfigEvents() unknown event type %d", event->type());
1633 break;
1634 }
1635 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 mLock.lock();
1637 }
1638 mLock.unlock();
1639}
1640
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001641void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642{
1643 const size_t SIZE = 256;
1644 char buffer[SIZE];
1645 String8 result;
1646
1647 bool locked = tryLock(mLock);
1648 if (!locked) {
1649 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1650 write(fd, buffer, strlen(buffer));
1651 }
1652
Eric Laurent612bbb52012-03-14 15:03:26 -07001653 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1654 result.append(buffer);
1655 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1656 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1658 result.append(buffer);
1659 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1660 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001661 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1662 result.append(buffer);
1663 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 result.append(buffer);
1665 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1666 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001667 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1668 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1670 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001671 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672 result.append(buffer);
1673
1674 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1675 result.append(buffer);
1676 result.append(" Index Command");
1677 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1678 snprintf(buffer, SIZE, "\n %02d ", i);
1679 result.append(buffer);
1680 result.append(mNewParameters[i]);
1681 }
1682
1683 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1684 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001686 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687 result.append(buffer);
1688 }
1689 result.append("\n");
1690
1691 write(fd, result.string(), result.size());
1692
1693 if (locked) {
1694 mLock.unlock();
1695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696}
1697
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001698void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001699{
1700 const size_t SIZE = 256;
1701 char buffer[SIZE];
1702 String8 result;
1703
1704 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1705 write(fd, buffer, strlen(buffer));
1706
1707 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1708 sp<EffectChain> chain = mEffectChains[i];
1709 if (chain != 0) {
1710 chain->dump(fd, args);
1711 }
1712 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001713}
1714
Eric Laurentfeb0db62011-07-22 09:04:31 -07001715void AudioFlinger::ThreadBase::acquireWakeLock()
1716{
1717 Mutex::Autolock _l(mLock);
1718 acquireWakeLock_l();
1719}
1720
1721void AudioFlinger::ThreadBase::acquireWakeLock_l()
1722{
1723 if (mPowerManager == 0) {
1724 // use checkService() to avoid blocking if power service is not up yet
1725 sp<IBinder> binder =
1726 defaultServiceManager()->checkService(String16("power"));
1727 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001728 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001729 } else {
1730 mPowerManager = interface_cast<IPowerManager>(binder);
1731 binder->linkToDeath(mDeathRecipient);
1732 }
1733 }
1734 if (mPowerManager != 0) {
1735 sp<IBinder> binder = new BBinder();
1736 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1737 binder,
1738 String16(mName));
1739 if (status == NO_ERROR) {
1740 mWakeLockToken = binder;
1741 }
Steve Block3856b092011-10-20 11:56:00 +01001742 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001743 }
1744}
1745
1746void AudioFlinger::ThreadBase::releaseWakeLock()
1747{
1748 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001749 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001750}
1751
1752void AudioFlinger::ThreadBase::releaseWakeLock_l()
1753{
1754 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001755 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001756 if (mPowerManager != 0) {
1757 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1758 }
1759 mWakeLockToken.clear();
1760 }
1761}
1762
1763void AudioFlinger::ThreadBase::clearPowerManager()
1764{
1765 Mutex::Autolock _l(mLock);
1766 releaseWakeLock_l();
1767 mPowerManager.clear();
1768}
1769
1770void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1771{
1772 sp<ThreadBase> thread = mThread.promote();
1773 if (thread != 0) {
1774 thread->clearPowerManager();
1775 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001776 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001777}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001778
Eric Laurent59255e42011-07-27 19:49:51 -07001779void AudioFlinger::ThreadBase::setEffectSuspended(
1780 const effect_uuid_t *type, bool suspend, int sessionId)
1781{
1782 Mutex::Autolock _l(mLock);
1783 setEffectSuspended_l(type, suspend, sessionId);
1784}
1785
1786void AudioFlinger::ThreadBase::setEffectSuspended_l(
1787 const effect_uuid_t *type, bool suspend, int sessionId)
1788{
Glenn Kasten090f0192012-01-30 13:00:02 -08001789 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001790 if (chain != 0) {
1791 if (type != NULL) {
1792 chain->setEffectSuspended_l(type, suspend);
1793 } else {
1794 chain->setEffectSuspendedAll_l(suspend);
1795 }
1796 }
1797
1798 updateSuspendedSessions_l(type, suspend, sessionId);
1799}
1800
1801void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1802{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001803 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001804 if (index < 0) {
1805 return;
1806 }
1807
Glenn Kasten0a7af182012-07-09 16:09:19 -07001808 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1809 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001810
1811 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001812 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001813 for (int j = 0; j < desc->mRefCount; j++) {
1814 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1815 chain->setEffectSuspendedAll_l(true);
1816 } else {
Steve Block3856b092011-10-20 11:56:00 +01001817 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001818 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001819 chain->setEffectSuspended_l(&desc->mType, true);
1820 }
1821 }
1822 }
1823}
1824
Eric Laurent59255e42011-07-27 19:49:51 -07001825void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1826 bool suspend,
1827 int sessionId)
1828{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001829 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001830
1831 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1832
1833 if (suspend) {
1834 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001835 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001836 } else {
1837 mSuspendedSessions.add(sessionId, sessionEffects);
1838 }
1839 } else {
1840 if (index < 0) {
1841 return;
1842 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001843 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001844 }
1845
1846
1847 int key = EffectChain::kKeyForSuspendAll;
1848 if (type != NULL) {
1849 key = type->timeLow;
1850 }
1851 index = sessionEffects.indexOfKey(key);
1852
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001853 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001854 if (suspend) {
1855 if (index >= 0) {
1856 desc = sessionEffects.valueAt(index);
1857 } else {
1858 desc = new SuspendedSessionDesc();
1859 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001860 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001861 }
1862 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001863 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001864 }
1865 desc->mRefCount++;
1866 } else {
1867 if (index < 0) {
1868 return;
1869 }
1870 desc = sessionEffects.valueAt(index);
1871 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001872 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001873 sessionEffects.removeItemsAt(index);
1874 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001875 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001876 sessionId);
1877 mSuspendedSessions.removeItem(sessionId);
1878 }
1879 }
1880 }
1881 if (!sessionEffects.isEmpty()) {
1882 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1883 }
1884}
1885
1886void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1887 bool enabled,
1888 int sessionId)
1889{
1890 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001891 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1892}
Eric Laurent59255e42011-07-27 19:49:51 -07001893
Eric Laurenta85a74a2011-10-19 11:44:54 -07001894void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1895 bool enabled,
1896 int sessionId)
1897{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001898 if (mType != RECORD) {
1899 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1900 // another session. This gives the priority to well behaved effect control panels
1901 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001902 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1903 // global effects
1904 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001905 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1906 }
1907 }
Eric Laurent59255e42011-07-27 19:49:51 -07001908
1909 sp<EffectChain> chain = getEffectChain_l(sessionId);
1910 if (chain != 0) {
1911 chain->checkSuspendOnEffectEnabled(effect, enabled);
1912 }
1913}
1914
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915// ----------------------------------------------------------------------------
1916
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001917AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1918 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001919 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001920 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001921 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001922 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001923 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001924 // mStreamTypes[] initialized in constructor body
1925 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001926 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001927 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001928 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001929 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001930 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001931 // index 0 is reserved for normal mixer's submix
1932 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kasten480b4682012-02-28 12:30:08 -08001934 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001935
John Grossmanee578c02012-07-23 17:05:46 -07001936 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1937 // it would be safer to explicitly pass initial masterVolume/masterMute as
1938 // parameter.
1939 //
1940 // If the HAL we are using has support for master volume or master mute,
1941 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1942 // and the mute set to false).
1943 mMasterVolume = audioFlinger->masterVolume_l();
1944 mMasterMute = audioFlinger->masterMute_l();
1945 if (mOutput && mOutput->audioHwDev) {
1946 if (mOutput->audioHwDev->canSetMasterVolume()) {
1947 mMasterVolume = 1.0;
1948 }
1949
1950 if (mOutput->audioHwDev->canSetMasterMute()) {
1951 mMasterMute = false;
1952 }
1953 }
1954
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 readOutputParameters();
1956
Glenn Kasten263709e2012-01-06 08:40:01 -08001957 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001958 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1959 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1960 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001961 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1962 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001964 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1965 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966}
1967
1968AudioFlinger::PlaybackThread::~PlaybackThread()
1969{
1970 delete [] mMixBuffer;
1971}
1972
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001973void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974{
1975 dumpInternals(fd, args);
1976 dumpTracks(fd, args);
1977 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978}
1979
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001980void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981{
1982 const size_t SIZE = 256;
1983 char buffer[SIZE];
1984 String8 result;
1985
Glenn Kasten58912562012-04-03 10:45:00 -07001986 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1987 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1988 const stream_type_t *st = &mStreamTypes[i];
1989 if (i > 0) {
1990 result.appendFormat(", ");
1991 }
1992 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1993 if (st->mute) {
1994 result.append("M");
1995 }
1996 }
1997 result.append("\n");
1998 write(fd, result.string(), result.length());
1999 result.clear();
2000
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
2002 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002003 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 for (size_t i = 0; i < mTracks.size(); ++i) {
2005 sp<Track> track = mTracks[i];
2006 if (track != 0) {
2007 track->dump(buffer, SIZE);
2008 result.append(buffer);
2009 }
2010 }
2011
2012 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
2013 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002014 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08002016 sp<Track> track = mActiveTracks[i].promote();
2017 if (track != 0) {
2018 track->dump(buffer, SIZE);
2019 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
2021 }
2022 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07002023
2024 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2025 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
2026 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
2027 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028}
2029
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002030void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031{
2032 const size_t SIZE = 256;
2033 char buffer[SIZE];
2034 String8 result;
2035
2036 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
2037 result.append(buffer);
2038 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
2039 result.append(buffer);
2040 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
2041 result.append(buffer);
2042 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
2043 result.append(buffer);
2044 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
2045 result.append(buffer);
2046 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
2047 result.append(buffer);
2048 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
2049 result.append(buffer);
2050 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002051 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052
2053 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054}
2055
2056// Thread virtuals
2057status_t AudioFlinger::PlaybackThread::readyToRun()
2058{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002059 status_t status = initCheck();
2060 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002061 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002062 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002063 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002065 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066}
2067
2068void AudioFlinger::PlaybackThread::onFirstRef()
2069{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002070 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071}
2072
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002073// ThreadBase virtuals
2074void AudioFlinger::PlaybackThread::preExit()
2075{
2076 ALOGV(" preExit()");
2077 // FIXME this is using hard-coded strings but in the future, this functionality will be
2078 // converted to use audio HAL extensions required to support tunneling
2079 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2080}
2081
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002083sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002085 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002087 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002088 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 int frameCount,
2090 const sp<IMemory>& sharedBuffer,
2091 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002092 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002093 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 status_t *status)
2095{
2096 sp<Track> track;
2097 status_t lStatus;
2098
Glenn Kasten73d22752012-03-19 13:38:30 -07002099 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2100
2101 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002102 if (flags & IAudioFlinger::TRACK_FAST) {
2103 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002104 // not timed
2105 (!isTimed) &&
2106 // either of these use cases:
2107 (
2108 // use case 1: shared buffer with any frame count
2109 (
2110 (sharedBuffer != 0)
2111 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002112 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002113 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002114 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002115 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002116 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002117 )
2118 ) &&
2119 // PCM data
2120 audio_is_linear_pcm(format) &&
2121 // mono or stereo
2122 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2123 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002124#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002125 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002126 (sampleRate == mSampleRate) &&
2127#endif
2128 // normal mixer has an associated fast mixer
2129 hasFastMixer() &&
2130 // there are sufficient fast track slots available
2131 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002132 // FIXME test that MixerThread for this fast track has a capable output HAL
2133 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002134 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002135 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2136 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002137 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002138 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002139 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002140 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002141 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002142 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002143 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002144 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2145 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2146 audio_is_linear_pcm(format),
2147 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002148 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002149 // For compatibility with AudioTrack calculation, buffer depth is forced
2150 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2151 // This is probably too conservative, but legacy application code may depend on it.
2152 // If you change this calculation, also review the start threshold which is related.
2153 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2154 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2155 if (minBufCount < 2) {
2156 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002157 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002158 int minFrameCount = mNormalFrameCount * minBufCount;
2159 if (frameCount < minFrameCount) {
2160 frameCount = minFrameCount;
2161 }
2162 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002163 }
2164
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002166 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2167 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002168 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002169 "for output %p with format %d",
2170 sampleRate, format, channelMask, mOutput, mFormat);
2171 lStatus = BAD_VALUE;
2172 goto Exit;
2173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 }
2175 } else {
2176 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2177 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002178 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 lStatus = BAD_VALUE;
2180 goto Exit;
2181 }
2182 }
2183
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002184 lStatus = initCheck();
2185 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002186 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 goto Exit;
2188 }
2189
2190 { // scope for mLock
2191 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002192
2193 // all tracks in same audio session must share the same routing strategy otherwise
2194 // conflicts will happen when tracks are moved from one output to another by audio policy
2195 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002196 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002197 for (size_t i = 0; i < mTracks.size(); ++i) {
2198 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002199 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002200 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002201 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002202 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002203 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002204 lStatus = BAD_VALUE;
2205 goto Exit;
2206 }
2207 }
2208 }
2209
John Grossman4ff14ba2012-02-08 16:37:41 -08002210 if (!isTimed) {
2211 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002212 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002213 } else {
2214 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2215 channelMask, frameCount, sharedBuffer, sessionId);
2216 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002217 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218 lStatus = NO_MEMORY;
2219 goto Exit;
2220 }
2221 mTracks.add(track);
2222
2223 sp<EffectChain> chain = getEffectChain_l(sessionId);
2224 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002225 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002227 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002228 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002230
Eric Laurent896adcd2012-09-13 11:18:23 -07002231 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2232 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2233 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2234 // so ask activity manager to do this on our behalf
2235 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002236 }
2237 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002238
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 lStatus = NO_ERROR;
2240
2241Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002242 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 *status = lStatus;
2244 }
2245 return track;
2246}
2247
Eric Laurente737cda2012-05-22 18:55:44 -07002248uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2249{
2250 if (mFastMixer != NULL) {
2251 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2252 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2253 }
2254 return latency;
2255}
2256
2257uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2258{
2259 return latency;
2260}
2261
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262uint32_t AudioFlinger::PlaybackThread::latency() const
2263{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002264 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002265 return latency_l();
2266}
2267uint32_t AudioFlinger::PlaybackThread::latency_l() const
2268{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002269 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002270 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002271 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 return 0;
2273 }
2274}
2275
Glenn Kasten6637baa2012-01-09 09:40:36 -08002276void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002278 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002279 // Don't apply master volume in SW if our HAL can do it for us.
2280 if (mOutput && mOutput->audioHwDev &&
2281 mOutput->audioHwDev->canSetMasterVolume()) {
2282 mMasterVolume = 1.0;
2283 } else {
2284 mMasterVolume = value;
2285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286}
2287
Glenn Kasten6637baa2012-01-09 09:40:36 -08002288void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002290 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002291 // Don't apply master mute in SW if our HAL can do it for us.
2292 if (mOutput && mOutput->audioHwDev &&
2293 mOutput->audioHwDev->canSetMasterMute()) {
2294 mMasterMute = false;
2295 } else {
2296 mMasterMute = muted;
2297 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298}
2299
Glenn Kasten6637baa2012-01-09 09:40:36 -08002300void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002302 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304}
2305
Glenn Kasten6637baa2012-01-09 09:40:36 -08002306void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002308 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310}
2311
Glenn Kastenfff6d712012-01-12 16:38:12 -08002312float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002314 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 return mStreamTypes[stream].volume;
2316}
2317
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318// addTrack_l() must be called with ThreadBase::mLock held
2319status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2320{
2321 status_t status = ALREADY_EXISTS;
2322
2323 // set retry count for buffer fill
2324 track->mRetryCount = kMaxTrackStartupRetries;
2325 if (mActiveTracks.indexOf(track) < 0) {
2326 // the track is newly added, make sure it fills up all its
2327 // buffers before playing. This is to ensure the client will
2328 // effectively get the latency it requested.
2329 track->mFillingUpStatus = Track::FS_FILLING;
2330 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002331 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 mActiveTracks.add(track);
2333 if (track->mainBuffer() != mMixBuffer) {
2334 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2335 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002336 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002337 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 }
2339 }
2340
2341 status = NO_ERROR;
2342 }
2343
Steve Block3856b092011-10-20 11:56:00 +01002344 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 mWaitWorkCV.broadcast();
2346
2347 return status;
2348}
2349
2350// destroyTrack_l() must be called with ThreadBase::mLock held
2351void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2352{
2353 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002354 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002356 removeTrack_l(track);
2357 }
2358}
2359
2360void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2361{
Eric Laurent29864602012-05-08 18:57:51 -07002362 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002363 mTracks.remove(track);
2364 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002365 // redundant as track is about to be destroyed, for dumpsys only
2366 track->mName = -1;
2367 if (track->isFastTrack()) {
2368 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002369 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002370 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2371 mFastTrackAvailMask |= 1 << index;
2372 // redundant as track is about to be destroyed, for dumpsys only
2373 track->mFastIndex = -1;
2374 }
Eric Laurentb469b942011-05-09 12:09:06 -07002375 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2376 if (chain != 0) {
2377 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 }
2379}
2380
2381String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2382{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002383 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002384 char *s;
2385
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002386 Mutex::Autolock _l(mLock);
2387 if (initCheck() != NO_ERROR) {
2388 return out_s8;
2389 }
2390
Dima Zavin799a70e2011-04-18 16:57:27 -07002391 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002392 out_s8 = String8(s);
2393 free(s);
2394 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002397// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2399 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002400 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401
Steve Block3856b092011-10-20 11:56:00 +01002402 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
2404 switch (event) {
2405 case AudioSystem::OUTPUT_OPENED:
2406 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002407 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 desc.samplingRate = mSampleRate;
2409 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002410 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411 desc.latency = latency();
2412 param2 = &desc;
2413 break;
2414
2415 case AudioSystem::STREAM_CONFIG_CHANGED:
2416 param2 = &param;
2417 case AudioSystem::OUTPUT_CLOSED:
2418 default:
2419 break;
2420 }
2421 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2422}
2423
2424void AudioFlinger::PlaybackThread::readOutputParameters()
2425{
Dima Zavin799a70e2011-04-18 16:57:27 -07002426 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002427 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2428 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002430 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002431 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002432 if (mFrameCount & 15) {
2433 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2434 mFrameCount);
2435 }
2436
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002437 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002438 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002439 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002440 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002441 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2442 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2443 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2444 maxNormalFrameCount = maxNormalFrameCount & ~15;
2445 if (maxNormalFrameCount < minNormalFrameCount) {
2446 maxNormalFrameCount = minNormalFrameCount;
2447 }
2448 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2449 if (multiplier <= 1.0) {
2450 multiplier = 1.0;
2451 } else if (multiplier <= 2.0) {
2452 if (2 * mFrameCount <= maxNormalFrameCount) {
2453 multiplier = 2.0;
2454 } else {
2455 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2456 }
2457 } else {
2458 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2459 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2460 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2461 // FIXME this rounding up should not be done if no HAL SRC
2462 uint32_t truncMult = (uint32_t) multiplier;
2463 if ((truncMult & 1)) {
2464 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2465 ++truncMult;
2466 }
2467 }
2468 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002469 }
Glenn Kasten58912562012-04-03 10:45:00 -07002470 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002471 mNormalFrameCount = multiplier * mFrameCount;
2472 // round up to nearest 16 frames to satisfy AudioMixer
2473 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002474 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475
Glenn Kastene9dd0172012-01-27 18:08:45 -08002476 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002477 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2478 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479
Eric Laurentde070132010-07-13 04:45:46 -07002480 // force reconfiguration of effect chains and engines to take new buffer size and audio
2481 // parameters into account
2482 // Note that mLock is not held when readOutputParameters() is called from the constructor
2483 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2484 // matter.
2485 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2486 Vector< sp<EffectChain> > effectChains = mEffectChains;
2487 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002488 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490}
2491
Eric Laurente737cda2012-05-22 18:55:44 -07002492
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2494{
Glenn Kastena0d68332012-01-27 16:47:15 -08002495 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 return BAD_VALUE;
2497 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002498 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002499 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 return INVALID_OPERATION;
2501 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002502 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503
Eric Laurent1afc26d2012-09-23 15:20:50 -07002504 if (isSuspended()) {
2505 // return an estimation of rendered frames when the output is suspended
2506 int32_t frames = mBytesWritten - latency_l();
2507 if (frames < 0) {
2508 frames = 0;
2509 }
2510 *dspFrames = (uint32_t)frames;
2511 return NO_ERROR;
2512 } else {
2513 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515}
2516
Glenn Kasten106e8a42012-08-02 13:37:12 -07002517uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518{
2519 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002520 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002522 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 }
2524
2525 for (size_t i = 0; i < mTracks.size(); ++i) {
2526 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002527 if (sessionId == track->sessionId() &&
2528 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002529 result |= TRACK_SESSION;
2530 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
2532 }
2533
Eric Laurent39e94f82010-07-28 01:32:47 -07002534 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535}
2536
Eric Laurentde070132010-07-13 04:45:46 -07002537uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2538{
Dima Zavinfce7a472011-04-19 22:30:36 -07002539 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002540 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002541 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2542 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002543 }
2544 for (size_t i = 0; i < mTracks.size(); i++) {
2545 sp<Track> track = mTracks[i];
2546 if (sessionId == track->sessionId() &&
2547 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002548 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002549 }
2550 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002551 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002552}
2553
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554
Glenn Kastenaed850d2012-01-26 09:46:34 -08002555AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002556{
2557 Mutex::Autolock _l(mLock);
2558 return mOutput;
2559}
2560
2561AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2562{
2563 Mutex::Autolock _l(mLock);
2564 AudioStreamOut *output = mOutput;
2565 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002566 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2567 // must push a NULL and wait for ack
2568 mOutputSink.clear();
2569 mPipeSink.clear();
2570 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002571 return output;
2572}
2573
2574// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002575audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002576{
2577 if (mOutput == NULL) {
2578 return NULL;
2579 }
2580 return &mOutput->stream->common;
2581}
2582
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002583uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002584{
Eric Laurentab9071b2012-06-04 13:45:29 -07002585 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002586}
2587
Eric Laurenta011e352012-03-29 15:51:43 -07002588status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2589{
2590 if (!isValidSyncEvent(event)) {
2591 return BAD_VALUE;
2592 }
2593
2594 Mutex::Autolock _l(mLock);
2595
2596 for (size_t i = 0; i < mTracks.size(); ++i) {
2597 sp<Track> track = mTracks[i];
2598 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002599 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002600 return NO_ERROR;
2601 }
2602 }
2603
2604 return NAME_NOT_FOUND;
2605}
2606
Glenn Kasten106e8a42012-08-02 13:37:12 -07002607bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002608{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002609 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002610}
2611
Eric Laurent44a957f2012-05-15 15:26:05 -07002612void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2613{
2614 size_t count = tracksToRemove.size();
2615 if (CC_UNLIKELY(count)) {
2616 for (size_t i = 0 ; i < count ; i++) {
2617 const sp<Track>& track = tracksToRemove.itemAt(i);
2618 if ((track->sharedBuffer() != 0) &&
2619 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2620 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2621 }
2622 }
2623 }
2624
2625}
2626
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627// ----------------------------------------------------------------------------
2628
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002629AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002630 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002631 : PlaybackThread(audioFlinger, output, id, device, type),
2632 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002633 // mFastMixer below
2634 mFastMixerFutex(0)
2635 // mOutputSink below
2636 // mPipeSink below
2637 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002639 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002640 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002641 "mFrameCount=%d, mNormalFrameCount=%d",
2642 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2643 mNormalFrameCount);
2644 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2645
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002647 if (mChannelCount != FCC_2) {
2648 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 }
Glenn Kasten58912562012-04-03 10:45:00 -07002650
2651 // create an NBAIO sink for the HAL output stream, and negotiate
2652 mOutputSink = new AudioStreamOutSink(output->stream);
2653 size_t numCounterOffers = 0;
2654 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2655 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2656 ALOG_ASSERT(index == 0);
2657
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002658 // initialize fast mixer depending on configuration
2659 bool initFastMixer;
2660 switch (kUseFastMixer) {
2661 case FastMixer_Never:
2662 initFastMixer = false;
2663 break;
2664 case FastMixer_Always:
2665 initFastMixer = true;
2666 break;
2667 case FastMixer_Static:
2668 case FastMixer_Dynamic:
2669 initFastMixer = mFrameCount < mNormalFrameCount;
2670 break;
2671 }
2672 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002673
2674 // create a MonoPipe to connect our submix to FastMixer
2675 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002676 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2677 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2678 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2679 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002680 const NBAIO_Format offers[1] = {format};
2681 size_t numCounterOffers = 0;
2682 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2683 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002684 monoPipe->setAvgFrames((mScreenState & 1) ?
2685 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002686 mPipeSink = monoPipe;
2687
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002688#ifdef TEE_SINK_FRAMES
2689 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2690 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2691 numCounterOffers = 0;
2692 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2693 ALOG_ASSERT(index == 0);
2694 mTeeSink = teeSink;
2695 PipeReader *teeSource = new PipeReader(*teeSink);
2696 numCounterOffers = 0;
2697 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2698 ALOG_ASSERT(index == 0);
2699 mTeeSource = teeSource;
2700#endif
2701
Glenn Kasten58912562012-04-03 10:45:00 -07002702 // create fast mixer and configure it initially with just one fast track for our submix
2703 mFastMixer = new FastMixer();
2704 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002705#ifdef STATE_QUEUE_DUMP
2706 sq->setObserverDump(&mStateQueueObserverDump);
2707 sq->setMutatorDump(&mStateQueueMutatorDump);
2708#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002709 FastMixerState *state = sq->begin();
2710 FastTrack *fastTrack = &state->mFastTracks[0];
2711 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2712 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2713 fastTrack->mVolumeProvider = NULL;
2714 fastTrack->mGeneration++;
2715 state->mFastTracksGen++;
2716 state->mTrackMask = 1;
2717 // fast mixer will use the HAL output sink
2718 state->mOutputSink = mOutputSink.get();
2719 state->mOutputSinkGen++;
2720 state->mFrameCount = mFrameCount;
2721 state->mCommand = FastMixerState::COLD_IDLE;
2722 // already done in constructor initialization list
2723 //mFastMixerFutex = 0;
2724 state->mColdFutexAddr = &mFastMixerFutex;
2725 state->mColdGen++;
2726 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002727 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002728 sq->end();
2729 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2730
2731 // start the fast mixer
2732 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002733 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002734 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002735 if (err != 0) {
2736 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002737 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002738 }
Glenn Kasten58912562012-04-03 10:45:00 -07002739
Glenn Kastenc15d6652012-05-30 14:52:57 -07002740#ifdef AUDIO_WATCHDOG
2741 // create and start the watchdog
2742 mAudioWatchdog = new AudioWatchdog();
2743 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2744 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2745 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002746 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002747 if (err != 0) {
2748 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002749 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002750 }
2751#endif
2752
Glenn Kasten58912562012-04-03 10:45:00 -07002753 } else {
2754 mFastMixer = NULL;
2755 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002756
2757 switch (kUseFastMixer) {
2758 case FastMixer_Never:
2759 case FastMixer_Dynamic:
2760 mNormalSink = mOutputSink;
2761 break;
2762 case FastMixer_Always:
2763 mNormalSink = mPipeSink;
2764 break;
2765 case FastMixer_Static:
2766 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2767 break;
2768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769}
2770
2771AudioFlinger::MixerThread::~MixerThread()
2772{
Glenn Kasten58912562012-04-03 10:45:00 -07002773 if (mFastMixer != NULL) {
2774 FastMixerStateQueue *sq = mFastMixer->sq();
2775 FastMixerState *state = sq->begin();
2776 if (state->mCommand == FastMixerState::COLD_IDLE) {
2777 int32_t old = android_atomic_inc(&mFastMixerFutex);
2778 if (old == -1) {
2779 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2780 }
2781 }
2782 state->mCommand = FastMixerState::EXIT;
2783 sq->end();
2784 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2785 mFastMixer->join();
2786 // Though the fast mixer thread has exited, it's state queue is still valid.
2787 // We'll use that extract the final state which contains one remaining fast track
2788 // corresponding to our sub-mix.
2789 state = sq->begin();
2790 ALOG_ASSERT(state->mTrackMask == 1);
2791 FastTrack *fastTrack = &state->mFastTracks[0];
2792 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2793 delete fastTrack->mBufferProvider;
2794 sq->end(false /*didModify*/);
2795 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002796#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002797 if (mAudioWatchdog != 0) {
2798 mAudioWatchdog->requestExit();
2799 mAudioWatchdog->requestExitAndWait();
2800 mAudioWatchdog.clear();
2801 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002802#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804 delete mAudioMixer;
2805}
2806
Glenn Kasten83efdd02012-02-24 07:21:32 -08002807class CpuStats {
2808public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002809 CpuStats();
2810 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002811#ifdef DEBUG_CPU_USAGE
2812private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002813 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2814 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2815
2816 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2817
2818 int mCpuNum; // thread's current CPU number
2819 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002820#endif
2821};
2822
Glenn Kasten190a46f2012-03-06 11:27:10 -08002823CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002824#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002825 : mCpuNum(-1), mCpukHz(-1)
2826#endif
2827{
2828}
2829
2830void CpuStats::sample(const String8 &title) {
2831#ifdef DEBUG_CPU_USAGE
2832 // get current thread's delta CPU time in wall clock ns
2833 double wcNs;
2834 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2835
2836 // record sample for wall clock statistics
2837 if (valid) {
2838 mWcStats.sample(wcNs);
2839 }
2840
2841 // get the current CPU number
2842 int cpuNum = sched_getcpu();
2843
2844 // get the current CPU frequency in kHz
2845 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2846
2847 // check if either CPU number or frequency changed
2848 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2849 mCpuNum = cpuNum;
2850 mCpukHz = cpukHz;
2851 // ignore sample for purposes of cycles
2852 valid = false;
2853 }
2854
2855 // if no change in CPU number or frequency, then record sample for cycle statistics
2856 if (valid && mCpukHz > 0) {
2857 double cycles = wcNs * cpukHz * 0.000001;
2858 mHzStats.sample(cycles);
2859 }
2860
2861 unsigned n = mWcStats.n();
2862 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002863 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002864 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002865 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2866 double perLoop = elapsed / (double) n;
2867 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002868 double perLoop1k = perLoop * 0.001;
2869 double mean = mWcStats.mean();
2870 double stddev = mWcStats.stddev();
2871 double minimum = mWcStats.minimum();
2872 double maximum = mWcStats.maximum();
2873 double meanCycles = mHzStats.mean();
2874 double stddevCycles = mHzStats.stddev();
2875 double minCycles = mHzStats.minimum();
2876 double maxCycles = mHzStats.maximum();
2877 mCpuUsage.resetElapsed();
2878 mWcStats.reset();
2879 mHzStats.reset();
2880 ALOGD("CPU usage for %s over past %.1f secs\n"
2881 " (%u mixer loops at %.1f mean ms per loop):\n"
2882 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2883 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2884 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2885 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002886 elapsed * .000000001, n, perLoop * .000001,
2887 mean * .001,
2888 stddev * .001,
2889 minimum * .001,
2890 maximum * .001,
2891 mean / perLoop100,
2892 stddev / perLoop100,
2893 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002894 maximum / perLoop100,
2895 meanCycles / perLoop1k,
2896 stddevCycles / perLoop1k,
2897 minCycles / perLoop1k,
2898 maxCycles / perLoop1k);
2899
Glenn Kasten83efdd02012-02-24 07:21:32 -08002900 }
2901 }
2902#endif
2903};
2904
Glenn Kasten37d825e2012-02-24 07:21:48 -08002905void AudioFlinger::PlaybackThread::checkSilentMode_l()
2906{
2907 if (!mMasterMute) {
2908 char value[PROPERTY_VALUE_MAX];
2909 if (property_get("ro.audio.silent", value, "0") > 0) {
2910 char *endptr;
2911 unsigned long ul = strtoul(value, &endptr, 0);
2912 if (*endptr == '\0' && ul != 0) {
2913 ALOGD("Silence is golden");
2914 // The setprop command will not allow a property to be changed after
2915 // the first time it is set, so we don't have to worry about un-muting.
2916 setMasterMute_l(true);
2917 }
2918 }
2919 }
2920}
2921
Glenn Kasten000f0e32012-03-01 17:10:56 -08002922bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923{
2924 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002925
Glenn Kasten000f0e32012-03-01 17:10:56 -08002926 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002927
2928 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002930
Glenn Kasten000f0e32012-03-01 17:10:56 -08002931 // DUPLICATING
2932 // FIXME could this be made local to while loop?
2933 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002934
Glenn Kasten66fcab92012-02-24 14:59:21 -08002935 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002936 sleepTime = idleSleepTime;
2937
Glenn Kasten9f34a362012-03-20 16:46:41 -07002938 if (mType == MIXER) {
2939 sleepTimeShift = 0;
2940 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002941
Glenn Kasten83efdd02012-02-24 07:21:32 -08002942 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002943 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944
Eric Laurentfeb0db62011-07-22 09:04:31 -07002945 acquireWakeLock();
2946
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 while (!exitPending())
2948 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002949 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002950
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002951 Vector< sp<EffectChain> > effectChains;
2952
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 processConfigEvents();
2954
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 { // scope for mLock
2956
2957 Mutex::Autolock _l(mLock);
2958
2959 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002960 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 }
2962
Glenn Kastenfa26a852012-03-06 11:28:04 -08002963 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002964
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002966 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002967 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002969
2970 threadLoop_standby();
2971
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 }
2974
Glenn Kasten3e074702012-02-28 18:40:35 -08002975 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 // we're about to wait, flush the binder command buffer
2977 IPCThreadState::self()->flushCommands();
2978
Glenn Kastenfa26a852012-03-06 11:28:04 -08002979 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002980
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981 if (exitPending()) break;
2982
Eric Laurentfeb0db62011-07-22 09:04:31 -07002983 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002985 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002987 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002988 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989
Eric Laurentda747442012-04-25 18:53:13 -07002990 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002991 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002992 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002993
Glenn Kasten37d825e2012-02-24 07:21:48 -08002994 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995
Glenn Kasten000f0e32012-03-01 17:10:56 -08002996 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002998 if (mType == MIXER) {
2999 sleepTimeShift = 0;
3000 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003001
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002 continue;
3003 }
3004 }
3005
Glenn Kasten81028042012-04-30 18:15:12 -07003006 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07003007 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008
3009 // prevent any changes in effect chain list and in each effect chain
3010 // during mixing and effect process as the audio buffers could be deleted
3011 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003012 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08003013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014
Glenn Kastenfec279f2012-03-08 07:47:15 -08003015 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003016 threadLoop_mix();
3017 } else {
3018 threadLoop_sleepTime();
3019 }
3020
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003021 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003022 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07003023 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003024 }
3025
3026 // only process effects if we're going to write
3027 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003028 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08003029#ifdef QCOM_HARDWARE
3030 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
3031#endif
3032 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003033 }
3034 }
3035
3036 // enable changes in effect chain
3037 unlockEffectChains(effectChains);
3038
3039 // sleepTime == 0 means we must write to audio hardware
3040 if (sleepTime == 0) {
3041
3042 threadLoop_write();
3043
3044if (mType == MIXER) {
3045 // write blocked detection
3046 nsecs_t now = systemTime();
3047 nsecs_t delta = now - mLastWriteTime;
3048 if (!mStandby && delta > maxPeriod) {
3049 mNumDelayedWrites++;
3050 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003051#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003052 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003053#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003054 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3055 ns2ms(delta), mNumDelayedWrites, this);
3056 lastWarning = now;
3057 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003058 }
3059}
3060
3061 mStandby = false;
3062 } else {
3063 usleep(sleepTime);
3064 }
3065
Glenn Kasten58912562012-04-03 10:45:00 -07003066 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003067 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003068 // same lock. This will also mutate and push a new fast mixer state.
3069 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003070 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003071
Glenn Kastenfa26a852012-03-06 11:28:04 -08003072 // FIXME I don't understand the need for this here;
3073 // it was in the original code but maybe the
3074 // assignment in saveOutputTracks() makes this unnecessary?
3075 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003076
3077 // Effect chains will be actually deleted here if they were removed from
3078 // mEffectChains list during mixing or effects processing
3079 effectChains.clear();
3080
3081 // FIXME Note that the above .clear() is no longer necessary since effectChains
3082 // is now local to this block, but will keep it for now (at least until merge done).
3083 }
3084
Glenn Kasten9f34a362012-03-20 16:46:41 -07003085 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3086 if (mType == MIXER || mType == DIRECT) {
3087 // put output stream into standby mode
3088 if (!mStandby) {
3089 mOutput->stream->common.standby(&mOutput->stream->common);
3090 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003091 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003092
3093 releaseWakeLock();
3094
3095 ALOGV("Thread %p type %d exiting", this, mType);
3096 return false;
3097}
3098
Glenn Kasten58912562012-04-03 10:45:00 -07003099void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3100{
Glenn Kasten58912562012-04-03 10:45:00 -07003101 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3102}
3103
3104void AudioFlinger::MixerThread::threadLoop_write()
3105{
3106 // FIXME we should only do one push per cycle; confirm this is true
3107 // Start the fast mixer if it's not already running
3108 if (mFastMixer != NULL) {
3109 FastMixerStateQueue *sq = mFastMixer->sq();
3110 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003111 if (state->mCommand != FastMixerState::MIX_WRITE &&
3112 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003113 if (state->mCommand == FastMixerState::COLD_IDLE) {
3114 int32_t old = android_atomic_inc(&mFastMixerFutex);
3115 if (old == -1) {
3116 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3117 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003118#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003119 if (mAudioWatchdog != 0) {
3120 mAudioWatchdog->resume();
3121 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003122#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003123 }
3124 state->mCommand = FastMixerState::MIX_WRITE;
3125 sq->end();
3126 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003127 if (kUseFastMixer == FastMixer_Dynamic) {
3128 mNormalSink = mPipeSink;
3129 }
Glenn Kasten58912562012-04-03 10:45:00 -07003130 } else {
3131 sq->end(false /*didModify*/);
3132 }
3133 }
3134 PlaybackThread::threadLoop_write();
3135}
3136
Glenn Kasten000f0e32012-03-01 17:10:56 -08003137// shared by MIXER and DIRECT, overridden by DUPLICATING
3138void AudioFlinger::PlaybackThread::threadLoop_write()
3139{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003140 // FIXME rewrite to reduce number of system calls
3141 mLastWriteTime = systemTime();
3142 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003143 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003144
Eric Laurent67c0a582012-05-01 19:31:12 -07003145 // If an NBAIO sink is present, use it to write the normal mixer's submix
3146 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003147#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003148 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003149#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003150 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003151#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003152 // update the setpoint when gScreenState changes
3153 uint32_t screenState = gScreenState;
3154 if (screenState != mScreenState) {
3155 mScreenState = screenState;
3156 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3157 if (pipe != NULL) {
3158 pipe->setAvgFrames((mScreenState & 1) ?
3159 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3160 }
3161 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003162 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003163#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003164 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003165#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003166 if (framesWritten > 0) {
3167 bytesWritten = framesWritten << mBitShift;
3168 } else {
3169 bytesWritten = framesWritten;
3170 }
3171 // otherwise use the HAL / AudioStreamOut directly
3172 } else {
3173 // Direct output thread.
3174 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003175 }
3176
Eric Laurent67c0a582012-05-01 19:31:12 -07003177 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003178 mNumWrites++;
3179 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003180}
3181
Glenn Kasten58912562012-04-03 10:45:00 -07003182void AudioFlinger::MixerThread::threadLoop_standby()
3183{
3184 // Idle the fast mixer if it's currently running
3185 if (mFastMixer != NULL) {
3186 FastMixerStateQueue *sq = mFastMixer->sq();
3187 FastMixerState *state = sq->begin();
3188 if (!(state->mCommand & FastMixerState::IDLE)) {
3189 state->mCommand = FastMixerState::COLD_IDLE;
3190 state->mColdFutexAddr = &mFastMixerFutex;
3191 state->mColdGen++;
3192 mFastMixerFutex = 0;
3193 sq->end();
3194 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3195 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003196 if (kUseFastMixer == FastMixer_Dynamic) {
3197 mNormalSink = mOutputSink;
3198 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003199#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003200 if (mAudioWatchdog != 0) {
3201 mAudioWatchdog->pause();
3202 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003203#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003204 } else {
3205 sq->end(false /*didModify*/);
3206 }
3207 }
3208 PlaybackThread::threadLoop_standby();
3209}
3210
Glenn Kasten000f0e32012-03-01 17:10:56 -08003211// shared by MIXER and DIRECT, overridden by DUPLICATING
3212void AudioFlinger::PlaybackThread::threadLoop_standby()
3213{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003214 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003215 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003216}
3217
3218void AudioFlinger::MixerThread::threadLoop_mix()
3219{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003220 // obtain the presentation timestamp of the next output buffer
3221 int64_t pts;
3222 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003223
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003224#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003225 if (mNormalSink != 0) {
3226 status = mNormalSink->getNextWriteTimestamp(&pts);
3227 } else {
3228 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003229 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003230#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003231
Glenn Kasten952eeb22012-03-06 11:30:57 -08003232 if (status != NO_ERROR) {
3233 pts = AudioBufferProvider::kInvalidPTS;
3234 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003235
Glenn Kasten952eeb22012-03-06 11:30:57 -08003236 // mix buffers...
3237 mAudioMixer->process(pts);
3238 // increase sleep time progressively when application underrun condition clears.
3239 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3240 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3241 // such that we would underrun the audio HAL.
3242 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3243 sleepTimeShift--;
3244 }
3245 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003246 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003247 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003248}
3249
3250void AudioFlinger::MixerThread::threadLoop_sleepTime()
3251{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003252 // If no tracks are ready, sleep once for the duration of an output
3253 // buffer size, then write 0s to the output
3254 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003255 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003256 sleepTime = activeSleepTime >> sleepTimeShift;
3257 if (sleepTime < kMinThreadSleepTimeUs) {
3258 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003260 // reduce sleep time in case of consecutive application underruns to avoid
3261 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3262 // duration we would end up writing less data than needed by the audio HAL if
3263 // the condition persists.
3264 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3265 sleepTimeShift++;
3266 }
3267 } else {
3268 sleepTime = idleSleepTime;
3269 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003270 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003271 memset (mMixBuffer, 0, mixBufferSize);
3272 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003273 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003274 }
3275 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276}
3277
3278// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003279AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003280 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281{
3282
Glenn Kasten29c23c32012-01-26 13:37:52 -08003283 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003285 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 size_t mixedTracks = 0;
3287 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003288 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003289 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003290 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291
3292 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003293 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294
Eric Laurent571d49c2010-08-11 05:20:11 -07003295 if (masterMute) {
3296 masterVolume = 0;
3297 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003299 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003301 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003302 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 masterVolume = (float)((v + (1 << 23)) >> 24);
3304 chain.clear();
3305 }
3306
Glenn Kasten288ed212012-04-25 17:52:27 -07003307 // prepare a new state to push
3308 FastMixerStateQueue *sq = NULL;
3309 FastMixerState *state = NULL;
3310 bool didModify = false;
3311 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3312 if (mFastMixer != NULL) {
3313 sq = mFastMixer->sq();
3314 state = sq->begin();
3315 }
3316
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003318 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 if (t == 0) continue;
3320
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003321 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003323
Glenn Kasten288ed212012-04-25 17:52:27 -07003324 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003325 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003326
3327 // It's theoretically possible (though unlikely) for a fast track to be created
3328 // and then removed within the same normal mix cycle. This is not a problem, as
3329 // the track never becomes active so it's fast mixer slot is never touched.
3330 // The converse, of removing an (active) track and then creating a new track
3331 // at the identical fast mixer slot within the same normal mix cycle,
3332 // is impossible because the slot isn't marked available until the end of each cycle.
3333 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003334 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3335 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003336 FastTrack *fastTrack = &state->mFastTracks[j];
3337
3338 // Determine whether the track is currently in underrun condition,
3339 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003340 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3341 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003342 uint32_t recentFull = (underruns.mBitFields.mFull -
3343 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3344 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3345 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3346 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3347 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3348 uint32_t recentUnderruns = recentPartial + recentEmpty;
3349 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003350 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003351 // or stopped which can occur when flush() is called while active
3352 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003353 track->mUnderrunCount += recentUnderruns;
3354 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003355
Glenn Kastend08f48c2012-05-01 18:14:02 -07003356 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003357 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003358 bool isActive = true;
3359 switch (track->mState) {
3360 case TrackBase::STOPPING_1:
3361 // track stays active in STOPPING_1 state until first underrun
3362 if (recentUnderruns > 0) {
3363 track->mState = TrackBase::STOPPING_2;
3364 }
3365 break;
3366 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003367 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003368 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003369 break;
3370 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003371 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003372 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003373 break;
3374 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003375 if (recentFull > 0 || recentPartial > 0) {
3376 // track has provided at least some frames recently: reset retry count
3377 track->mRetryCount = kMaxTrackRetries;
3378 }
3379 if (recentUnderruns == 0) {
3380 // no recent underruns: stay active
3381 break;
3382 }
3383 // there has recently been an underrun of some kind
3384 if (track->sharedBuffer() == 0) {
3385 // were any of the recent underruns "empty" (no frames available)?
3386 if (recentEmpty == 0) {
3387 // no, then ignore the partial underruns as they are allowed indefinitely
3388 break;
3389 }
3390 // there has recently been an "empty" underrun: decrement the retry counter
3391 if (--(track->mRetryCount) > 0) {
3392 break;
3393 }
3394 // indicate to client process that the track was disabled because of underrun;
3395 // it will then automatically call start() when data is available
3396 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3397 // remove from active list, but state remains ACTIVE [confusing but true]
3398 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003399 break;
3400 }
3401 // fall through
3402 case TrackBase::STOPPING_2:
3403 case TrackBase::PAUSED:
3404 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003405 case TrackBase::STOPPED:
3406 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003407 // Check for presentation complete if track is inactive
3408 // We have consumed all the buffers of this track.
3409 // This would be incomplete if we auto-paused on underrun
3410 {
3411 size_t audioHALFrames =
3412 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3413 size_t framesWritten =
3414 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003415 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003416 // track stays in active list until presentation is complete
3417 break;
3418 }
3419 }
3420 if (track->isStopping_2()) {
3421 track->mState = TrackBase::STOPPED;
3422 }
3423 if (track->isStopped()) {
3424 // Can't reset directly, as fast mixer is still polling this track
3425 // track->reset();
3426 // So instead mark this track as needing to be reset after push with ack
3427 resetMask |= 1 << i;
3428 }
3429 isActive = false;
3430 break;
3431 case TrackBase::IDLE:
3432 default:
3433 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003434 }
3435
3436 if (isActive) {
3437 // was it previously inactive?
3438 if (!(state->mTrackMask & (1 << j))) {
3439 ExtendedAudioBufferProvider *eabp = track;
3440 VolumeProvider *vp = track;
3441 fastTrack->mBufferProvider = eabp;
3442 fastTrack->mVolumeProvider = vp;
3443 fastTrack->mSampleRate = track->mSampleRate;
3444 fastTrack->mChannelMask = track->mChannelMask;
3445 fastTrack->mGeneration++;
3446 state->mTrackMask |= 1 << j;
3447 didModify = true;
3448 // no acknowledgement required for newly active tracks
3449 }
3450 // cache the combined master volume and stream type volume for fast mixer; this
3451 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3452 track->mCachedVolume = track->isMuted() ?
3453 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3454 ++fastTracks;
3455 } else {
3456 // was it previously active?
3457 if (state->mTrackMask & (1 << j)) {
3458 fastTrack->mBufferProvider = NULL;
3459 fastTrack->mGeneration++;
3460 state->mTrackMask &= ~(1 << j);
3461 didModify = true;
3462 // If any fast tracks were removed, we must wait for acknowledgement
3463 // because we're about to decrement the last sp<> on those tracks.
3464 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003465 } else {
3466 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003467 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003468 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003469 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003470 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003471 }
3472 continue;
3473 }
3474
3475 { // local variable scope to avoid goto warning
3476
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 audio_track_cblk_t* cblk = track->cblk();
3478
3479 // The first time a track is added we wait
3480 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003481 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003482 // make sure that we have enough frames to mix one full buffer.
3483 // enforce this condition only once to enable draining the buffer in case the client
3484 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003485 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003486 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003487 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003488 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003489 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003490 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003491 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003492 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003493 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003494 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003495 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003496 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003497 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3498 // the minimum track buffer size is normally twice the number of frames necessary
3499 // to fill one buffer and the resampler should not leave more than one buffer worth
3500 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003501 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003502 }
3503 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003504 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 !track->isPaused() && !track->isTerminated())
3506 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003507 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508
3509 mixedTracks++;
3510
3511 // track->mainBuffer() != mMixBuffer means there is an effect chain
3512 // connected to the track
3513 chain.clear();
3514 if (track->mainBuffer() != mMixBuffer) {
3515 chain = getEffectChain_l(track->sessionId());
3516 // Delegate volume control to effect in track effect chain if needed
3517 if (chain != 0) {
3518 tracksWithEffect++;
3519 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003520 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003521 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 }
3523 }
3524
3525
3526 int param = AudioMixer::VOLUME;
3527 if (track->mFillingUpStatus == Track::FS_FILLED) {
3528 // no ramp for the first volume setting
3529 track->mFillingUpStatus = Track::FS_ACTIVE;
3530 if (track->mState == TrackBase::RESUMING) {
3531 track->mState = TrackBase::ACTIVE;
3532 param = AudioMixer::RAMP_VOLUME;
3533 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003534 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 } else if (cblk->server != 0) {
3536 // If the track is stopped before the first frame was mixed,
3537 // do not apply ramp
3538 param = AudioMixer::RAMP_VOLUME;
3539 }
3540
3541 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003542 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003543 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003544 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003545 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 if (track->isPausing()) {
3547 track->setPaused();
3548 }
3549 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003550
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003552 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003554 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003555 vl = vlr & 0xFFFF;
3556 vr = vlr >> 16;
3557 // track volumes come from shared memory, so can't be trusted and must be clamped
3558 if (vl > MAX_GAIN_INT) {
3559 ALOGV("Track left volume out of range: %04X", vl);
3560 vl = MAX_GAIN_INT;
3561 }
3562 if (vr > MAX_GAIN_INT) {
3563 ALOGV("Track right volume out of range: %04X", vr);
3564 vr = MAX_GAIN_INT;
3565 }
3566 // now apply the master volume and stream type volume
3567 vl = (uint32_t)(v * vl) << 12;
3568 vr = (uint32_t)(v * vr) << 12;
3569 // assuming master volume and stream type volume each go up to 1.0,
3570 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571
Glenn Kasten05632a52012-01-03 14:22:33 -08003572 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3573 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003574 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003575 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003576 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003577 }
3578 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003580 // Delegate volume control to effect in track effect chain if needed
3581 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3582 // Do not ramp volume if volume is controlled by effect
3583 param = AudioMixer::VOLUME;
3584 track->mHasVolumeController = true;
3585 } else {
3586 // force no volume ramp when volume controller was just disabled or removed
3587 // from effect chain to avoid volume spike
3588 if (track->mHasVolumeController) {
3589 param = AudioMixer::VOLUME;
3590 }
3591 track->mHasVolumeController = false;
3592 }
3593
3594 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003595 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003596 vl = (vl + (1 << 11)) >> 12;
3597 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3598 vr = (vr + (1 << 11)) >> 12;
3599 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003600
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003601 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 -07003602
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003604 mAudioMixer->setBufferProvider(name, track);
3605 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003607 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3608 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3609 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003611 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 AudioMixer::TRACK,
3613 AudioMixer::FORMAT, (void *)track->format());
3614 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003615 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003617 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003619 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 AudioMixer::RESAMPLE,
3621 AudioMixer::SAMPLE_RATE,
3622 (void *)(cblk->sampleRate));
3623 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003624 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 AudioMixer::TRACK,
3626 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3627 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003628 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 AudioMixer::TRACK,
3630 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3631
3632 // reset retry count
3633 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003634
Eric Laurent27741442012-01-17 19:20:12 -08003635 // If one track is ready, set the mixer ready if:
3636 // - the mixer was not ready during previous round OR
3637 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003638 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003639 mixerStatus != MIXER_TRACKS_ENABLED) {
3640 mixerStatus = MIXER_TRACKS_READY;
3641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003643 // clear effect chain input buffer if an active track underruns to avoid sending
3644 // previous audio buffer again to effects
3645 chain = getEffectChain_l(track->sessionId());
3646 if (chain != 0) {
3647 chain->clearInputBuffer();
3648 }
3649
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003650 //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 -07003651 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003652 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653 // We have consumed all the buffers of this track.
3654 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003655 // TODO: use actual buffer filling status instead of latency when available from
3656 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003657 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003658 size_t framesWritten =
3659 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003660 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003661 if (track->isStopped()) {
3662 track->reset();
3663 }
Eric Laurenta011e352012-03-29 15:51:43 -07003664 tracksToRemove->add(track);
3665 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003667 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668 // No buffers for this track. Give it a few chances to
3669 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003670 if (--(track->mRetryCount) <= 0) {
3671 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003673 // indicate to client process that the track was disabled because of underrun;
3674 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003675 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003676 // If one track is not ready, mark the mixer also not ready if:
3677 // - the mixer was ready during previous round OR
3678 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003679 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003680 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681 mixerStatus = MIXER_TRACKS_ENABLED;
3682 }
3683 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003684 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 }
Glenn Kasten58912562012-04-03 10:45:00 -07003686
3687 } // local variable scope to avoid goto warning
3688track_is_ready: ;
3689
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 }
3691
Glenn Kasten288ed212012-04-25 17:52:27 -07003692 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003693 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003694 if (didModify) {
3695 state->mFastTracksGen++;
3696 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3697 if (kUseFastMixer == FastMixer_Dynamic &&
3698 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3699 state->mCommand = FastMixerState::COLD_IDLE;
3700 state->mColdFutexAddr = &mFastMixerFutex;
3701 state->mColdGen++;
3702 mFastMixerFutex = 0;
3703 if (kUseFastMixer == FastMixer_Dynamic) {
3704 mNormalSink = mOutputSink;
3705 }
3706 // If we go into cold idle, need to wait for acknowledgement
3707 // so that fast mixer stops doing I/O.
3708 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003709 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003710 }
3711 sq->end();
3712 }
3713 if (sq != NULL) {
3714 sq->end(didModify);
3715 sq->push(block);
3716 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003717#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003718 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3719 mAudioWatchdog->pause();
3720 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003721#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003722
3723 // Now perform the deferred reset on fast tracks that have stopped
3724 while (resetMask != 0) {
3725 size_t i = __builtin_ctz(resetMask);
3726 ALOG_ASSERT(i < count);
3727 resetMask &= ~(1 << i);
3728 sp<Track> t = mActiveTracks[i].promote();
3729 if (t == 0) continue;
3730 Track* track = t.get();
3731 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3732 track->reset();
3733 }
Glenn Kasten58912562012-04-03 10:45:00 -07003734
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 // remove all the tracks that need to be...
3736 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003737 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 for (size_t i=0 ; i<count ; i++) {
3739 const sp<Track>& track = tracksToRemove->itemAt(i);
3740 mActiveTracks.remove(track);
3741 if (track->mainBuffer() != mMixBuffer) {
3742 chain = getEffectChain_l(track->sessionId());
3743 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003744 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003745 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 }
3747 }
3748 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003749 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 }
3751 }
3752 }
3753
3754 // mix buffer must be cleared if all tracks are connected to an
3755 // effect chain as in this case the mixer will not write to
3756 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003757 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3758 // FIXME as a performance optimization, should remember previous zero status
3759 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 }
3761
Glenn Kasten58912562012-04-03 10:45:00 -07003762 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003763 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003764 if (fastTracks > 0) {
3765 mixerStatus = MIXER_TRACKS_READY;
3766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 return mixerStatus;
3768}
3769
Glenn Kasten66fcab92012-02-24 14:59:21 -08003770/*
3771The derived values that are cached:
3772 - mixBufferSize from frame count * frame size
3773 - activeSleepTime from activeSleepTimeUs()
3774 - idleSleepTime from idleSleepTimeUs()
3775 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3776 - maxPeriod from frame count and sample rate (MIXER only)
3777
3778The parameters that affect these derived values are:
3779 - frame count
3780 - frame size
3781 - sample rate
3782 - device type: A2DP or not
3783 - device latency
3784 - format: PCM or not
3785 - active sleep time
3786 - idle sleep time
3787*/
3788
3789void AudioFlinger::PlaybackThread::cacheParameters_l()
3790{
Glenn Kasten58912562012-04-03 10:45:00 -07003791 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003792 activeSleepTime = activeSleepTimeUs();
3793 idleSleepTime = idleSleepTimeUs();
3794}
3795
Eric Laurent22167852012-06-20 12:26:32 -07003796void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797{
Steve Block3856b092011-10-20 11:56:00 +01003798 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003799 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003801
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 size_t size = mTracks.size();
3803 for (size_t i = 0; i < size; i++) {
3804 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003805 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003806 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 }
3809 }
3810}
3811
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003813int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003815 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816}
3817
3818// deleteTrackName_l() must be called with ThreadBase::mLock held
3819void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3820{
Steve Block3856b092011-10-20 11:56:00 +01003821 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 mAudioMixer->deleteTrackName(name);
3823}
3824
3825// checkForNewParameters_l() must be called with ThreadBase::mLock held
3826bool AudioFlinger::MixerThread::checkForNewParameters_l()
3827{
Glenn Kasten58912562012-04-03 10:45:00 -07003828 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3829 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 bool reconfig = false;
3831
3832 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003833
3834 if (mFastMixer != NULL) {
3835 FastMixerStateQueue *sq = mFastMixer->sq();
3836 FastMixerState *state = sq->begin();
3837 if (!(state->mCommand & FastMixerState::IDLE)) {
3838 previousCommand = state->mCommand;
3839 state->mCommand = FastMixerState::HOT_IDLE;
3840 sq->end();
3841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3842 } else {
3843 sq->end(false /*didModify*/);
3844 }
3845 }
3846
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 status_t status = NO_ERROR;
3848 String8 keyValuePair = mNewParameters[0];
3849 AudioParameter param = AudioParameter(keyValuePair);
3850 int value;
3851
3852 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3853 reconfig = true;
3854 }
3855 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003856 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 status = BAD_VALUE;
3858 } else {
3859 reconfig = true;
3860 }
3861 }
3862 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003863 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 status = BAD_VALUE;
3865 } else {
3866 reconfig = true;
3867 }
3868 }
3869 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3870 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003871 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 // if frame count is changed after track creation
3873 if (!mTracks.isEmpty()) {
3874 status = INVALID_OPERATION;
3875 } else {
3876 reconfig = true;
3877 }
3878 }
3879 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003880#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003881 // when changing the audio output device, call addBatteryData to notify
3882 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003883 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003884 uint32_t params = 0;
3885 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003886 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003887 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3888 }
3889
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003890 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003891 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003892 // check if any other device (except speaker) is on
3893 if (value & deviceWithoutSpeaker ) {
3894 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3895 }
3896
3897 if (params != 0) {
3898 addBatteryData(params);
3899 }
3900 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003901#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003902
Mathias Agopian65ab4712010-07-14 17:59:35 -07003903 // forward device change to effects that have requested to be
3904 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003905 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003907 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908 }
3909 }
3910
3911 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003912 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003913 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003915 mOutput->stream->common.standby(&mOutput->stream->common);
3916 mStandby = true;
3917 mBytesWritten = 0;
3918 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003919 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 }
3921 if (status == NO_ERROR && reconfig) {
3922 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003923 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3924 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003926 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003928 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 if (name < 0) break;
3930 mTracks[i]->mName = name;
3931 // limit track sample rate to 2 x new output sample rate
3932 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3933 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3934 }
3935 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003936 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 }
3938 }
3939
3940 mNewParameters.removeAt(0);
3941
3942 mParamStatus = status;
3943 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003944 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3945 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003946 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947 }
Glenn Kasten58912562012-04-03 10:45:00 -07003948
3949 if (!(previousCommand & FastMixerState::IDLE)) {
3950 ALOG_ASSERT(mFastMixer != NULL);
3951 FastMixerStateQueue *sq = mFastMixer->sq();
3952 FastMixerState *state = sq->begin();
3953 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3954 state->mCommand = previousCommand;
3955 sq->end();
3956 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3957 }
3958
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 return reconfig;
3960}
3961
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003962void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963{
3964 const size_t SIZE = 256;
3965 char buffer[SIZE];
3966 String8 result;
3967
3968 PlaybackThread::dumpInternals(fd, args);
3969
3970 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3971 result.append(buffer);
3972 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003973
3974 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3975 FastMixerDumpState copy = mFastMixerDumpState;
3976 copy.dump(fd);
3977
Glenn Kasten39993082012-05-31 13:40:27 -07003978#ifdef STATE_QUEUE_DUMP
3979 // Similar for state queue
3980 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3981 observerCopy.dump(fd);
3982 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3983 mutatorCopy.dump(fd);
3984#endif
3985
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003986 // Write the tee output to a .wav file
3987 NBAIO_Source *teeSource = mTeeSource.get();
3988 if (teeSource != NULL) {
3989 char teePath[64];
3990 struct timeval tv;
3991 gettimeofday(&tv, NULL);
3992 struct tm tm;
3993 localtime_r(&tv.tv_sec, &tm);
3994 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3995 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3996 if (teeFd >= 0) {
3997 char wavHeader[44];
3998 memcpy(wavHeader,
3999 "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",
4000 sizeof(wavHeader));
4001 NBAIO_Format format = teeSource->format();
4002 unsigned channelCount = Format_channelCount(format);
4003 ALOG_ASSERT(channelCount <= FCC_2);
4004 unsigned sampleRate = Format_sampleRate(format);
4005 wavHeader[22] = channelCount; // number of channels
4006 wavHeader[24] = sampleRate; // sample rate
4007 wavHeader[25] = sampleRate >> 8;
4008 wavHeader[32] = channelCount * 2; // block alignment
4009 write(teeFd, wavHeader, sizeof(wavHeader));
4010 size_t total = 0;
4011 bool firstRead = true;
4012 for (;;) {
4013#define TEE_SINK_READ 1024
4014 short buffer[TEE_SINK_READ * FCC_2];
4015 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07004016 ssize_t actual = teeSource->read(buffer, count,
4017 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004018 bool wasFirstRead = firstRead;
4019 firstRead = false;
4020 if (actual <= 0) {
4021 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
4022 continue;
4023 }
4024 break;
4025 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07004026 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004027 write(teeFd, buffer, actual * channelCount * sizeof(short));
4028 total += actual;
4029 }
4030 lseek(teeFd, (off_t) 4, SEEK_SET);
4031 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
4032 write(teeFd, &temp, sizeof(temp));
4033 lseek(teeFd, (off_t) 40, SEEK_SET);
4034 temp = total * channelCount * sizeof(short);
4035 write(teeFd, &temp, sizeof(temp));
4036 close(teeFd);
4037 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
4038 } else {
4039 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
4040 }
4041 }
4042
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004043#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07004044 if (mAudioWatchdog != 0) {
4045 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4046 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4047 wdCopy.dump(fd);
4048 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004049#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050}
4051
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004052uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053{
Glenn Kasten58912562012-04-03 10:45:00 -07004054 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055}
4056
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004057uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004058{
Glenn Kasten58912562012-04-03 10:45:00 -07004059 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004060}
4061
Glenn Kasten66fcab92012-02-24 14:59:21 -08004062void AudioFlinger::MixerThread::cacheParameters_l()
4063{
4064 PlaybackThread::cacheParameters_l();
4065
4066 // FIXME: Relaxed timing because of a certain device that can't meet latency
4067 // Should be reduced to 2x after the vendor fixes the driver issue
4068 // increase threshold again due to low power audio mode. The way this warning
4069 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004070 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004071}
4072
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004074AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004075 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004076 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004077 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079}
4080
4081AudioFlinger::DirectOutputThread::~DirectOutputThread()
4082{
4083}
4084
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004085AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4086 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004087)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004089 sp<Track> trackToRemove;
4090
Glenn Kastenfec279f2012-03-08 07:47:15 -08004091 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092
Glenn Kasten952eeb22012-03-06 11:30:57 -08004093 // find out which tracks need to be processed
4094 if (mActiveTracks.size() != 0) {
4095 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004096 // The track died recently
4097 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098
Glenn Kasten952eeb22012-03-06 11:30:57 -08004099 Track* const track = t.get();
4100 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101
Glenn Kasten952eeb22012-03-06 11:30:57 -08004102 // The first time a track is added we wait
4103 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004104 uint32_t minFrames;
4105 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4106 minFrames = mNormalFrameCount;
4107 } else {
4108 minFrames = 1;
4109 }
4110 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004111 !track->isPaused() && !track->isTerminated())
4112 {
4113 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114
Glenn Kasten952eeb22012-03-06 11:30:57 -08004115 if (track->mFillingUpStatus == Track::FS_FILLED) {
4116 track->mFillingUpStatus = Track::FS_ACTIVE;
4117 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004118 if (track->mState == TrackBase::RESUMING) {
4119 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004120 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004121 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004122
Glenn Kasten952eeb22012-03-06 11:30:57 -08004123 // compute volume for this track
4124 float left, right;
4125 if (track->isMuted() || mMasterMute || track->isPausing() ||
4126 mStreamTypes[track->streamType()].mute) {
4127 left = right = 0;
4128 if (track->isPausing()) {
4129 track->setPaused();
4130 }
4131 } else {
4132 float typeVolume = mStreamTypes[track->streamType()].volume;
4133 float v = mMasterVolume * typeVolume;
4134 uint32_t vlr = cblk->getVolumeLR();
4135 float v_clamped = v * (vlr & 0xFFFF);
4136 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4137 left = v_clamped/MAX_GAIN;
4138 v_clamped = v * (vlr >> 16);
4139 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4140 right = v_clamped/MAX_GAIN;
4141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142
Glenn Kasten952eeb22012-03-06 11:30:57 -08004143 if (left != mLeftVolFloat || right != mRightVolFloat) {
4144 mLeftVolFloat = left;
4145 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146
Glenn Kasten952eeb22012-03-06 11:30:57 -08004147 // Convert volumes from float to 8.24
4148 uint32_t vl = (uint32_t)(left * (1 << 24));
4149 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150
Glenn Kasten952eeb22012-03-06 11:30:57 -08004151 // Delegate volume control to effect in track effect chain if needed
4152 // only one effect chain can be present on DirectOutputThread, so if
4153 // there is one, the track is connected to it
4154 if (!mEffectChains.isEmpty()) {
4155 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004156 mEffectChains[0]->setVolume_l(&vl, &vr);
4157 left = (float)vl / (1 << 24);
4158 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004159 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004160 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004161 }
4162
4163 // reset retry count
4164 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004165 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004166 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004167 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004168 // clear effect chain input buffer if an active track underruns to avoid sending
4169 // previous audio buffer again to effects
4170 if (!mEffectChains.isEmpty()) {
4171 mEffectChains[0]->clearInputBuffer();
4172 }
4173
Glenn Kasten952eeb22012-03-06 11:30:57 -08004174 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004175 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004176 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004177 // We have consumed all the buffers of this track.
4178 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004179 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004180 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004181 size_t framesWritten =
4182 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004183 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004184 if (track->isStopped()) {
4185 track->reset();
4186 }
Eric Laurenta011e352012-03-29 15:51:43 -07004187 trackToRemove = track;
4188 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004189 } else {
4190 // No buffers for this track. Give it a few chances to
4191 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004192 if (--(track->mRetryCount) <= 0) {
4193 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004194 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004196 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 }
4198 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004199 }
4200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004202 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004203 // remove all the tracks that need to be...
4204 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004205 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004206 mActiveTracks.remove(trackToRemove);
4207 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004208 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004209 trackToRemove->sessionId());
4210 mEffectChains[0]->decActiveTrackCnt();
4211 }
4212 if (trackToRemove->isTerminated()) {
4213 removeTrack_l(trackToRemove);
4214 }
4215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216
Glenn Kastenfec279f2012-03-08 07:47:15 -08004217 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004218}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219
Glenn Kasten000f0e32012-03-01 17:10:56 -08004220void AudioFlinger::DirectOutputThread::threadLoop_mix()
4221{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004222 AudioBufferProvider::Buffer buffer;
4223 size_t frameCount = mFrameCount;
4224 int8_t *curBuf = (int8_t *)mMixBuffer;
4225 // output audio to hardware
4226 while (frameCount) {
4227 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004228 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004229 if (CC_UNLIKELY(buffer.raw == NULL)) {
4230 memset(curBuf, 0, frameCount * mFrameSize);
4231 break;
4232 }
4233 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4234 frameCount -= buffer.frameCount;
4235 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004236 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004237 }
4238 sleepTime = 0;
4239 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004240 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004241
Glenn Kasten000f0e32012-03-01 17:10:56 -08004242}
4243
4244void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4245{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004246 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004247 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004248 sleepTime = activeSleepTime;
4249 } else {
4250 sleepTime = idleSleepTime;
4251 }
4252 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004253 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004254 sleepTime = 0;
4255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256}
4257
4258// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004259int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4260 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261{
4262 return 0;
4263}
4264
4265// deleteTrackName_l() must be called with ThreadBase::mLock held
4266void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4267{
4268}
4269
4270// checkForNewParameters_l() must be called with ThreadBase::mLock held
4271bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4272{
4273 bool reconfig = false;
4274
4275 while (!mNewParameters.isEmpty()) {
4276 status_t status = NO_ERROR;
4277 String8 keyValuePair = mNewParameters[0];
4278 AudioParameter param = AudioParameter(keyValuePair);
4279 int value;
4280
4281 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4282 // do not accept frame count changes if tracks are open as the track buffer
4283 // size depends on frame count and correct behavior would not be garantied
4284 // if frame count is changed after track creation
4285 if (!mTracks.isEmpty()) {
4286 status = INVALID_OPERATION;
4287 } else {
4288 reconfig = true;
4289 }
4290 }
4291 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004292 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004293 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004295 mOutput->stream->common.standby(&mOutput->stream->common);
4296 mStandby = true;
4297 mBytesWritten = 0;
4298 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004299 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 }
4301 if (status == NO_ERROR && reconfig) {
4302 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004303 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304 }
4305 }
4306
4307 mNewParameters.removeAt(0);
4308
4309 mParamStatus = status;
4310 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004311 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4312 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004313 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 }
4315 return reconfig;
4316}
4317
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004318uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319{
4320 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004321 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004322 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 } else {
4324 time = 10000;
4325 }
4326 return time;
4327}
4328
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004329uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330{
4331 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004332 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004333 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 } else {
4335 time = 10000;
4336 }
4337 return time;
4338}
4339
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004340uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004341{
4342 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004343 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004344 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4345 } else {
4346 time = 10000;
4347 }
4348 return time;
4349}
4350
Glenn Kasten66fcab92012-02-24 14:59:21 -08004351void AudioFlinger::DirectOutputThread::cacheParameters_l()
4352{
4353 PlaybackThread::cacheParameters_l();
4354
4355 // use shorter standby delay as on normal output to release
4356 // hardware resources as soon as possible
4357 standbyDelay = microseconds(activeSleepTime*2);
4358}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004359
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360// ----------------------------------------------------------------------------
4361
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004362AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004363 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004364 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004365 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367 addOutputTrack(mainThread);
4368}
4369
4370AudioFlinger::DuplicatingThread::~DuplicatingThread()
4371{
4372 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4373 mOutputTracks[i]->destroy();
4374 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375}
4376
Glenn Kasten000f0e32012-03-01 17:10:56 -08004377void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004379 // mix buffers...
4380 if (outputsReady(outputTracks)) {
4381 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4382 } else {
4383 memset(mMixBuffer, 0, mixBufferSize);
4384 }
4385 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004386 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004387 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004388}
4389
4390void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4391{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004392 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004393 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004394 sleepTime = activeSleepTime;
4395 } else {
4396 sleepTime = idleSleepTime;
4397 }
4398 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004399 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4400 writeFrames = mNormalFrameCount;
4401 memset(mMixBuffer, 0, mixBufferSize);
4402 } else {
4403 // flush remaining overflow buffers in output tracks
4404 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004405 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004406 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004407 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004408}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409
Glenn Kasten000f0e32012-03-01 17:10:56 -08004410void AudioFlinger::DuplicatingThread::threadLoop_write()
4411{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004412 for (size_t i = 0; i < outputTracks.size(); i++) {
4413 outputTracks[i]->write(mMixBuffer, writeFrames);
4414 }
4415 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004416}
Glenn Kasten688a6402012-02-29 07:57:06 -08004417
Glenn Kasten000f0e32012-03-01 17:10:56 -08004418void AudioFlinger::DuplicatingThread::threadLoop_standby()
4419{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004420 // DuplicatingThread implements standby by stopping all tracks
4421 for (size_t i = 0; i < outputTracks.size(); i++) {
4422 outputTracks[i]->stop();
4423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424}
4425
Glenn Kastenfa26a852012-03-06 11:28:04 -08004426void AudioFlinger::DuplicatingThread::saveOutputTracks()
4427{
4428 outputTracks = mOutputTracks;
4429}
4430
4431void AudioFlinger::DuplicatingThread::clearOutputTracks()
4432{
4433 outputTracks.clear();
4434}
4435
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4437{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004438 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004439 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004440 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004441 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442 this,
4443 mSampleRate,
4444 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004445 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 frameCount);
4447 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004448 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004450 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004451 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452 }
4453}
4454
4455void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4456{
4457 Mutex::Autolock _l(mLock);
4458 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004459 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 mOutputTracks[i]->destroy();
4461 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004462 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 return;
4464 }
4465 }
Steve Block3856b092011-10-20 11:56:00 +01004466 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467}
4468
Glenn Kasten438b0362012-03-06 11:24:48 -08004469// caller must hold mLock
4470void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471{
4472 mWaitTimeMs = UINT_MAX;
4473 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4474 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004475 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4477 if (waitTimeMs < mWaitTimeMs) {
4478 mWaitTimeMs = waitTimeMs;
4479 }
4480 }
4481 }
4482}
4483
4484
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004485bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486{
4487 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004488 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004490 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 return false;
4492 }
4493 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004494 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004496 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497 return false;
4498 }
4499 }
4500 return true;
4501}
4502
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004503uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504{
4505 return (mWaitTimeMs * 1000) / 2;
4506}
4507
Glenn Kasten66fcab92012-02-24 14:59:21 -08004508void AudioFlinger::DuplicatingThread::cacheParameters_l()
4509{
4510 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4511 updateWaitTime_l();
4512
4513 MixerThread::cacheParameters_l();
4514}
4515
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516// ----------------------------------------------------------------------------
4517
4518// TrackBase constructor must be called with AudioFlinger::mLock held
4519AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004520 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521 const sp<Client>& client,
4522 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004523 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004524 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 const sp<IMemory>& sharedBuffer,
4527 int sessionId)
4528 : RefBase(),
4529 mThread(thread),
4530 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004531 mCblk(NULL),
4532 // mBuffer
4533 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534 mFrameCount(0),
4535 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004536 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004538 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004540 // mChannelCount
4541 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542{
Steve Block3856b092011-10-20 11:56:00 +01004543 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544
Steve Blockb8a80522011-12-20 16:23:08 +00004545 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004546 size_t size = sizeof(audio_track_cblk_t);
4547 uint8_t channelCount = popcount(channelMask);
4548 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4549 if (sharedBuffer == 0) {
4550 size += bufferSize;
4551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004553 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 mCblkMemory = client->heap()->allocate(size);
4555 if (mCblkMemory != 0) {
4556 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004557 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 new(mCblk) audio_track_cblk_t();
4559 // clear all buffers
4560 mCblk->frameCount = frameCount;
4561 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004562// uncomment the following lines to quickly test 32-bit wraparound
4563// mCblk->user = 0xffff0000;
4564// mCblk->server = 0xffff0000;
4565// mCblk->userBase = 0xffff0000;
4566// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004567 mChannelCount = channelCount;
4568 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 if (sharedBuffer == 0) {
4570 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4571 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4572 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004573 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 mCblk->flags = CBLK_UNDERRUN_ON;
4575 } else {
4576 mBuffer = sharedBuffer->pointer();
4577 }
4578 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4579 }
4580 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004581 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 client->heap()->dump("AudioTrack");
4583 return;
4584 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004585 } else {
4586 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004587 // construct the shared structure in-place.
4588 new(mCblk) audio_track_cblk_t();
4589 // clear all buffers
4590 mCblk->frameCount = frameCount;
4591 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004592// uncomment the following lines to quickly test 32-bit wraparound
4593// mCblk->user = 0xffff0000;
4594// mCblk->server = 0xffff0000;
4595// mCblk->userBase = 0xffff0000;
4596// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004597 mChannelCount = channelCount;
4598 mChannelMask = channelMask;
4599 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4600 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4601 // Force underrun condition to avoid false underrun callback until first data is
4602 // written to buffer (other flags are cleared)
4603 mCblk->flags = CBLK_UNDERRUN_ON;
4604 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606}
4607
4608AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4609{
Glenn Kastena0d68332012-01-27 16:47:15 -08004610 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004611 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004613 } else {
4614 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 }
4616 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004617 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004618 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004619 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004621 // If the client's reference count drops to zero, the associated destructor
4622 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4623 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 mClient.clear();
4625 }
4626}
4627
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004628// AudioBufferProvider interface
4629// getNextBuffer() = 0;
4630// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4632{
Glenn Kastene0feee32011-12-13 11:53:26 -08004633 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004635 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004636 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 buffer->frameCount = 0;
4638}
4639
4640bool AudioFlinger::ThreadBase::TrackBase::step() {
4641 bool result;
4642 audio_track_cblk_t* cblk = this->cblk();
4643
4644 result = cblk->stepServer(mFrameCount);
4645 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004646 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004647 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 }
4649 return result;
4650}
4651
4652void AudioFlinger::ThreadBase::TrackBase::reset() {
4653 audio_track_cblk_t* cblk = this->cblk();
4654
4655 cblk->user = 0;
4656 cblk->server = 0;
4657 cblk->userBase = 0;
4658 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004659 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004660 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661}
4662
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4664 return (int)mCblk->sampleRate;
4665}
4666
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4668 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004669 size_t frameSize = cblk->frameSize;
4670 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4671 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672
4673 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004674 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4675 "TrackBase::getBuffer buffer out of range:\n"
4676 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4677 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004679 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680
4681 return bufferStart;
4682}
4683
Eric Laurenta011e352012-03-29 15:51:43 -07004684status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4685{
4686 mSyncEvents.add(event);
4687 return NO_ERROR;
4688}
4689
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690// ----------------------------------------------------------------------------
4691
4692// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4693AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004694 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004696 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004698 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004699 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 int frameCount,
4701 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004702 int sessionId,
4703 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004704 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004705 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004706 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004707 // mRetryCount initialized later when needed
4708 mSharedBuffer(sharedBuffer),
4709 mStreamType(streamType),
4710 mName(-1), // see note below
4711 mMainBuffer(thread->mixBuffer()),
4712 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004713 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004714 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004715 mFlags(flags),
4716 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004717 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004718 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719{
4720 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4722 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004723 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004724 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004725 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004726 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004727 if (mName < 0) {
4728 ALOGE("no more track names available");
4729 return;
4730 }
4731 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004732 if (flags & IAudioFlinger::TRACK_FAST) {
4733 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4734 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4735 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004736 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004737 // FIXME This is too eager. We allocate a fast track index before the
4738 // fast track becomes active. Since fast tracks are a scarce resource,
4739 // this means we are potentially denying other more important fast tracks from
4740 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004741 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004742 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004743 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004744 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004745 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004748 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749}
4750
4751AudioFlinger::PlaybackThread::Track::~Track()
4752{
Steve Block3856b092011-10-20 11:56:00 +01004753 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754}
4755
4756void AudioFlinger::PlaybackThread::Track::destroy()
4757{
4758 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4759 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004760 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761 // we must acquire a strong reference on this Track before locking mLock
4762 // here so that the destructor is called only when exiting this function.
4763 // On the other hand, as long as Track::destroy() is only called by
4764 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4765 // this Track with its member mTrack.
4766 sp<Track> keep(this);
4767 { // scope for mLock
4768 sp<ThreadBase> thread = mThread.promote();
4769 if (thread != 0) {
4770 if (!isOutputTrack()) {
4771 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004772 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004773
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004774#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004775 // to track the speaker usage
4776 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004777#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004778 }
4779 AudioSystem::releaseOutput(thread->id());
4780 }
4781 Mutex::Autolock _l(thread->mLock);
4782 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4783 playbackThread->destroyTrack_l(this);
4784 }
4785 }
4786}
4787
Glenn Kasten288ed212012-04-25 17:52:27 -07004788/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4789{
Glenn Kastene213c862012-04-25 13:46:15 -07004790 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 -07004791 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004792}
4793
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4795{
Glenn Kasten83d86532012-01-17 14:39:34 -08004796 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004797 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004798 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004799 } else {
4800 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4801 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004802 track_state state = mState;
4803 char stateChar;
4804 switch (state) {
4805 case IDLE:
4806 stateChar = 'I';
4807 break;
4808 case TERMINATED:
4809 stateChar = 'T';
4810 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004811 case STOPPING_1:
4812 stateChar = 's';
4813 break;
4814 case STOPPING_2:
4815 stateChar = '5';
4816 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004817 case STOPPED:
4818 stateChar = 'S';
4819 break;
4820 case RESUMING:
4821 stateChar = 'R';
4822 break;
4823 case ACTIVE:
4824 stateChar = 'A';
4825 break;
4826 case PAUSING:
4827 stateChar = 'p';
4828 break;
4829 case PAUSED:
4830 stateChar = 'P';
4831 break;
Eric Laurent29864602012-05-08 18:57:51 -07004832 case FLUSHED:
4833 stateChar = 'F';
4834 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004835 default:
4836 stateChar = '?';
4837 break;
4838 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004839 char nowInUnderrun;
4840 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4841 case UNDERRUN_FULL:
4842 nowInUnderrun = ' ';
4843 break;
4844 case UNDERRUN_PARTIAL:
4845 nowInUnderrun = '<';
4846 break;
4847 case UNDERRUN_EMPTY:
4848 nowInUnderrun = '*';
4849 break;
4850 default:
4851 nowInUnderrun = '?';
4852 break;
4853 }
Glenn Kastene213c862012-04-25 13:46:15 -07004854 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4855 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004856 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857 mStreamType,
4858 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004859 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860 mSessionId,
4861 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004862 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004863 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 mMute,
4865 mFillingUpStatus,
4866 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004867 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4868 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869 mCblk->server,
4870 mCblk->user,
4871 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004872 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004873 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004874 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004875 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876}
4877
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004878// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004879status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004880 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004882 audio_track_cblk_t* cblk = this->cblk();
4883 uint32_t framesReady;
4884 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004886 // Check if last stepServer failed, try to step now
4887 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004888 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4889 // Since the fast mixer is higher priority than client callback thread,
4890 // it does not result in priority inversion for client.
4891 // But a non-blocking solution would be preferable to avoid
4892 // fast mixer being unable to tryLock(), and
4893 // to avoid the extra context switches if the client wakes up,
4894 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004895 if (!step()) goto getNextBuffer_exit;
4896 ALOGV("stepServer recovered");
4897 mStepServerFailed = false;
4898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899
Glenn Kasten288ed212012-04-25 17:52:27 -07004900 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004901 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004902
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004903 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904 uint32_t s = cblk->server;
4905 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4906
4907 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4908 if (framesReq > framesReady) {
4909 framesReq = framesReady;
4910 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004911 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 framesReq = bufferEnd - s;
4913 }
4914
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004915 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004916 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919
4920getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004921 buffer->raw = NULL;
4922 buffer->frameCount = 0;
4923 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4924 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004925}
4926
Glenn Kasten288ed212012-04-25 17:52:27 -07004927// Note that framesReady() takes a mutex on the control block using tryLock().
4928// This could result in priority inversion if framesReady() is called by the normal mixer,
4929// as the normal mixer thread runs at lower
4930// priority than the client's callback thread: there is a short window within framesReady()
4931// during which the normal mixer could be preempted, and the client callback would block.
4932// Another problem can occur if framesReady() is called by the fast mixer:
4933// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4934// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4935size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004936 return mCblk->framesReady();
4937}
4938
Glenn Kasten288ed212012-04-25 17:52:27 -07004939// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004941 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942
John Grossman4ff14ba2012-02-08 16:37:41 -08004943 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4945 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004946 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 return true;
4948 }
4949 return false;
4950}
4951
Glenn Kasten3acbd052012-02-28 10:39:56 -08004952status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004953 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954{
4955 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004956 ALOGV("start(%d), calling pid %d session %d",
4957 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004958
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 sp<ThreadBase> thread = mThread.promote();
4960 if (thread != 0) {
4961 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004962 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 // here the track could be either new, or restarted
4964 // in both cases "unstop" the track
4965 if (mState == PAUSED) {
4966 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004967 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 } else {
4969 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004970 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971 }
4972
4973 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4974 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004975 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004977
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004978#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004979 // to track the speaker usage
4980 if (status == NO_ERROR) {
4981 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4982 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004983#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 }
4985 if (status == NO_ERROR) {
4986 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4987 playbackThread->addTrack_l(this);
4988 } else {
4989 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004990 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 }
4992 } else {
4993 status = BAD_VALUE;
4994 }
4995 return status;
4996}
4997
4998void AudioFlinger::PlaybackThread::Track::stop()
4999{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005000 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 sp<ThreadBase> thread = mThread.promote();
5002 if (thread != 0) {
5003 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08005004 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07005005 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 // If the track is not active (PAUSED and buffers full), flush buffers
5007 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5008 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5009 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07005010 mState = STOPPED;
5011 } else if (!isFastTrack()) {
5012 mState = STOPPED;
5013 } else {
5014 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
5015 // and then to STOPPED and reset() when presentation is complete
5016 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07005018 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019 }
5020 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
5021 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005022 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005024
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005025#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005026 // to track the speaker usage
5027 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005028#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005029 }
5030 }
5031}
5032
5033void AudioFlinger::PlaybackThread::Track::pause()
5034{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005035 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 sp<ThreadBase> thread = mThread.promote();
5037 if (thread != 0) {
5038 Mutex::Autolock _l(thread->mLock);
5039 if (mState == ACTIVE || mState == RESUMING) {
5040 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01005041 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042 if (!isOutputTrack()) {
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}
5055
5056void AudioFlinger::PlaybackThread::Track::flush()
5057{
Steve Block3856b092011-10-20 11:56:00 +01005058 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059 sp<ThreadBase> thread = mThread.promote();
5060 if (thread != 0) {
5061 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005062 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005063 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 return;
5065 }
5066 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005067 // FLUSHED state
5068 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005069 // do not reset the track if it is still in the process of being stopped or paused.
5070 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005071 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005072 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005073 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5074 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5075 reset();
5076 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 }
5078}
5079
5080void AudioFlinger::PlaybackThread::Track::reset()
5081{
5082 // Do not reset twice to avoid discarding data written just after a flush and before
5083 // the audioflinger thread detects the track is stopped.
5084 if (!mResetDone) {
5085 TrackBase::reset();
5086 // Force underrun condition to avoid false underrun callback until first data is
5087 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005088 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5089 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 mFillingUpStatus = FS_FILLING;
5091 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005092 if (mState == FLUSHED) {
5093 mState = IDLE;
5094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 }
5096}
5097
5098void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5099{
5100 mMute = muted;
5101}
5102
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5104{
5105 status_t status = DEAD_OBJECT;
5106 sp<ThreadBase> thread = mThread.promote();
5107 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005108 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005109 sp<AudioFlinger> af = mClient->audioFlinger();
5110
5111 Mutex::Autolock _l(af->mLock);
5112
5113 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005114
Eric Laurent109347d2012-07-02 12:31:03 -07005115 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005116 Mutex::Autolock _dl(playbackThread->mLock);
5117 Mutex::Autolock _sl(srcThread->mLock);
5118 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5119 if (chain == 0) {
5120 return INVALID_OPERATION;
5121 }
5122
5123 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5124 if (effect == 0) {
5125 return INVALID_OPERATION;
5126 }
5127 srcThread->removeEffect_l(effect);
5128 playbackThread->addEffect_l(effect);
5129 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5130 if (effect->state() == EffectModule::ACTIVE ||
5131 effect->state() == EffectModule::STOPPING) {
5132 effect->start();
5133 }
5134
5135 sp<EffectChain> dstChain = effect->chain().promote();
5136 if (dstChain == 0) {
5137 srcThread->addEffect_l(effect);
5138 return INVALID_OPERATION;
5139 }
5140 AudioSystem::unregisterEffect(effect->id());
5141 AudioSystem::registerEffect(&effect->desc(),
5142 srcThread->id(),
5143 dstChain->strategy(),
5144 AUDIO_SESSION_OUTPUT_MIX,
5145 effect->id());
5146 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005147 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 }
5149 return status;
5150}
5151
5152void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5153{
5154 mAuxEffectId = EffectId;
5155 mAuxBuffer = buffer;
5156}
5157
Eric Laurenta011e352012-03-29 15:51:43 -07005158bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5159 size_t audioHalFrames)
5160{
5161 // a track is considered presented when the total number of frames written to audio HAL
5162 // corresponds to the number of frames written when presentationComplete() is called for the
5163 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5164 if (mPresentationCompleteFrames == 0) {
5165 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5166 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5167 mPresentationCompleteFrames, audioHalFrames);
5168 }
5169 if (framesWritten >= mPresentationCompleteFrames) {
5170 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5171 mSessionId, framesWritten);
5172 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005173 return true;
5174 }
5175 return false;
5176}
5177
5178void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5179{
5180 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5181 if (mSyncEvents[i]->type() == type) {
5182 mSyncEvents[i]->trigger();
5183 mSyncEvents.removeAt(i);
5184 i--;
5185 }
5186 }
5187}
5188
Glenn Kasten58912562012-04-03 10:45:00 -07005189// implement VolumeBufferProvider interface
5190
5191uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5192{
5193 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5194 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5195 uint32_t vlr = mCblk->getVolumeLR();
5196 uint32_t vl = vlr & 0xFFFF;
5197 uint32_t vr = vlr >> 16;
5198 // track volumes come from shared memory, so can't be trusted and must be clamped
5199 if (vl > MAX_GAIN_INT) {
5200 vl = MAX_GAIN_INT;
5201 }
5202 if (vr > MAX_GAIN_INT) {
5203 vr = MAX_GAIN_INT;
5204 }
5205 // now apply the cached master volume and stream type volume;
5206 // this is trusted but lacks any synchronization or barrier so may be stale
5207 float v = mCachedVolume;
5208 vl *= v;
5209 vr *= v;
5210 // re-combine into U4.16
5211 vlr = (vr << 16) | (vl & 0xFFFF);
5212 // FIXME look at mute, pause, and stop flags
5213 return vlr;
5214}
Eric Laurenta011e352012-03-29 15:51:43 -07005215
Eric Laurent29864602012-05-08 18:57:51 -07005216status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5217{
5218 if (mState == TERMINATED || mState == PAUSED ||
5219 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5220 (mState == STOPPED)))) {
5221 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5222 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5223 event->cancel();
5224 return INVALID_OPERATION;
5225 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005226 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005227 return NO_ERROR;
5228}
5229
John Grossman4ff14ba2012-02-08 16:37:41 -08005230// timed audio tracks
5231
5232sp<AudioFlinger::PlaybackThread::TimedTrack>
5233AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005234 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 const sp<Client>& client,
5236 audio_stream_type_t streamType,
5237 uint32_t sampleRate,
5238 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005239 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005240 int frameCount,
5241 const sp<IMemory>& sharedBuffer,
5242 int sessionId) {
5243 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005244 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005245
Glenn Kastena0356762012-03-19 10:38:51 -07005246 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005247 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5248 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005249}
5250
5251AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005252 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005253 const sp<Client>& client,
5254 audio_stream_type_t streamType,
5255 uint32_t sampleRate,
5256 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005257 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005258 int frameCount,
5259 const sp<IMemory>& sharedBuffer,
5260 int sessionId)
5261 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005262 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005263 mQueueHeadInFlight(false),
5264 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005265 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005266 mTimedSilenceBuffer(NULL),
5267 mTimedSilenceBufferSize(0),
5268 mTimedAudioOutputOnTime(false),
5269 mMediaTimeTransformValid(false)
5270{
5271 LocalClock lc;
5272 mLocalTimeFreq = lc.getLocalFreq();
5273
5274 mLocalTimeToSampleTransform.a_zero = 0;
5275 mLocalTimeToSampleTransform.b_zero = 0;
5276 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5277 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5278 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5279 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005280
5281 mMediaTimeToSampleTransform.a_zero = 0;
5282 mMediaTimeToSampleTransform.b_zero = 0;
5283 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5284 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5285 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5286 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005287}
5288
5289AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5290 mClient->releaseTimedTrack();
5291 delete [] mTimedSilenceBuffer;
5292}
5293
5294status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5295 size_t size, sp<IMemory>* buffer) {
5296
5297 Mutex::Autolock _l(mTimedBufferQueueLock);
5298
5299 trimTimedBufferQueue_l();
5300
5301 // lazily initialize the shared memory heap for timed buffers
5302 if (mTimedMemoryDealer == NULL) {
5303 const int kTimedBufferHeapSize = 512 << 10;
5304
5305 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5306 "AudioFlingerTimed");
5307 if (mTimedMemoryDealer == NULL)
5308 return NO_MEMORY;
5309 }
5310
5311 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5312 if (newBuffer == NULL) {
5313 newBuffer = mTimedMemoryDealer->allocate(size);
5314 if (newBuffer == NULL)
5315 return NO_MEMORY;
5316 }
5317
5318 *buffer = newBuffer;
5319 return NO_ERROR;
5320}
5321
5322// caller must hold mTimedBufferQueueLock
5323void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5324 int64_t mediaTimeNow;
5325 {
5326 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5327 if (!mMediaTimeTransformValid)
5328 return;
5329
5330 int64_t targetTimeNow;
5331 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5332 ? mCCHelper.getCommonTime(&targetTimeNow)
5333 : mCCHelper.getLocalTime(&targetTimeNow);
5334
5335 if (OK != res)
5336 return;
5337
5338 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5339 &mediaTimeNow)) {
5340 return;
5341 }
5342 }
5343
John Grossman1c345192012-03-27 14:00:17 -07005344 size_t trimEnd;
5345 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005346 int64_t bufEnd;
5347
John Grossmanc95cfbb2012-04-12 11:53:11 -07005348 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5349 // We have a next buffer. Just use its PTS as the PTS of the frame
5350 // following the last frame in this buffer. If the stream is sparse
5351 // (ie, there are deliberate gaps left in the stream which should be
5352 // filled with silence by the TimedAudioTrack), then this can result
5353 // in one extra buffer being left un-trimmed when it could have
5354 // been. In general, this is not typical, and we would rather
5355 // optimized away the TS calculation below for the more common case
5356 // where PTSes are contiguous.
5357 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5358 } else {
5359 // We have no next buffer. Compute the PTS of the frame following
5360 // the last frame in this buffer by computing the duration of of
5361 // this frame in media time units and adding it to the PTS of the
5362 // buffer.
5363 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5364 / mCblk->frameSize;
5365
5366 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5367 &bufEnd)) {
5368 ALOGE("Failed to convert frame count of %lld to media time"
5369 " duration" " (scale factor %d/%u) in %s",
5370 frameCount,
5371 mMediaTimeToSampleTransform.a_to_b_numer,
5372 mMediaTimeToSampleTransform.a_to_b_denom,
5373 __PRETTY_FUNCTION__);
5374 break;
5375 }
5376 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005377 }
John Grossman9fbdee12012-03-26 17:51:46 -07005378
5379 if (bufEnd > mediaTimeNow)
5380 break;
5381
5382 // Is the buffer we want to use in the middle of a mix operation right
5383 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5384 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005385 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005386 mTrimQueueHeadOnRelease = true;
5387 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005388 }
5389
John Grossman9fbdee12012-03-26 17:51:46 -07005390 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005391 if (trimStart < trimEnd) {
5392 // Update the bookkeeping for framesReady()
5393 for (size_t i = trimStart; i < trimEnd; ++i) {
5394 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5395 }
5396
5397 // Now actually remove the buffers from the queue.
5398 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005399 }
5400}
5401
John Grossman1c345192012-03-27 14:00:17 -07005402void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5403 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005404 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5405 "%s called (reason \"%s\"), but timed buffer queue has no"
5406 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005407
5408 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5409 mTimedBufferQueue.removeAt(0);
5410}
5411
5412void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5413 const TimedBuffer& buf,
5414 const char* logTag) {
5415 uint32_t bufBytes = buf.buffer()->size();
5416 uint32_t consumedAlready = buf.position();
5417
Eric Laurentb388e532012-04-14 13:32:48 -07005418 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005419 "Bad bookkeeping while updating frames pending. Timed buffer is"
5420 " only %u bytes long, but claims to have consumed %u"
5421 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005422 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005423
5424 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005425 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5426 "Bad bookkeeping while updating frames pending. Should have at"
5427 " least %u queued frames, but we think we have only %u. (update"
5428 " reason: \"%s\")",
5429 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005430
5431 mFramesPendingInQueue -= bufFrames;
5432}
5433
John Grossman4ff14ba2012-02-08 16:37:41 -08005434status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5435 const sp<IMemory>& buffer, int64_t pts) {
5436
5437 {
5438 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5439 if (!mMediaTimeTransformValid)
5440 return INVALID_OPERATION;
5441 }
5442
5443 Mutex::Autolock _l(mTimedBufferQueueLock);
5444
John Grossman1c345192012-03-27 14:00:17 -07005445 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5446 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005447 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5448
5449 return NO_ERROR;
5450}
5451
5452status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5453 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5454
John Grossman1c345192012-03-27 14:00:17 -07005455 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5456 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5457 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005458
5459 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5460 target == TimedAudioTrack::COMMON_TIME)) {
5461 return BAD_VALUE;
5462 }
5463
5464 Mutex::Autolock lock(mMediaTimeTransformLock);
5465 mMediaTimeTransform = xform;
5466 mMediaTimeTransformTarget = target;
5467 mMediaTimeTransformValid = true;
5468
5469 return NO_ERROR;
5470}
5471
5472#define min(a, b) ((a) < (b) ? (a) : (b))
5473
5474// implementation of getNextBuffer for tracks whose buffers have timestamps
5475status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5476 AudioBufferProvider::Buffer* buffer, int64_t pts)
5477{
5478 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005479 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005480 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005481 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005482 return INVALID_OPERATION;
5483 }
5484
John Grossman4ff14ba2012-02-08 16:37:41 -08005485 Mutex::Autolock _l(mTimedBufferQueueLock);
5486
John Grossman9fbdee12012-03-26 17:51:46 -07005487 ALOG_ASSERT(!mQueueHeadInFlight,
5488 "getNextBuffer called without releaseBuffer!");
5489
John Grossman4ff14ba2012-02-08 16:37:41 -08005490 while (true) {
5491
5492 // if we have no timed buffers, then fail
5493 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005494 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005495 buffer->frameCount = 0;
5496 return NOT_ENOUGH_DATA;
5497 }
5498
5499 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5500
5501 // calculate the PTS of the head of the timed buffer queue expressed in
5502 // local time
5503 int64_t headLocalPTS;
5504 {
5505 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5506
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005507 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005508
5509 if (mMediaTimeTransform.a_to_b_denom == 0) {
5510 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005511 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005512 return NO_ERROR;
5513 }
5514
5515 int64_t transformedPTS;
5516 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5517 &transformedPTS)) {
5518 // the transform failed. this shouldn't happen, but if it does
5519 // then just drop this buffer
5520 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005521 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005522 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005523 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005524 return NO_ERROR;
5525 }
5526
5527 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5528 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5529 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005530 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005531 buffer->frameCount = 0;
5532 return INVALID_OPERATION;
5533 }
5534 } else {
5535 headLocalPTS = transformedPTS;
5536 }
5537 }
5538
5539 // adjust the head buffer's PTS to reflect the portion of the head buffer
5540 // that has already been consumed
5541 int64_t effectivePTS = headLocalPTS +
5542 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5543
5544 // Calculate the delta in samples between the head of the input buffer
5545 // queue and the start of the next output buffer that will be written.
5546 // If the transformation fails because of over or underflow, it means
5547 // that the sample's position in the output stream is so far out of
5548 // whack that it should just be dropped.
5549 int64_t sampleDelta;
5550 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5551 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005552 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5553 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005554 continue;
5555 }
5556 if (!mLocalTimeToSampleTransform.doForwardTransform(
5557 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005558 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005559 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005560 continue;
5561 }
5562
John Grossman1c345192012-03-27 14:00:17 -07005563 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5564 " sampleDelta=[%d.%08x]",
5565 head.pts(), head.position(), pts,
5566 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5567 + (sampleDelta >> 32)),
5568 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005569
5570 // if the delta between the ideal placement for the next input sample and
5571 // the current output position is within this threshold, then we will
5572 // concatenate the next input samples to the previous output
5573 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005574 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005575
5576 // if this is the first buffer of audio that we're emitting from this track
5577 // then it should be almost exactly on time.
5578 const int64_t kSampleStartupThreshold = 1LL << 32;
5579
5580 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005581 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005582 // the next input is close enough to being on time, so concatenate it
5583 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005584 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005585
John Grossman1c345192012-03-27 14:00:17 -07005586 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5587 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005588 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005589 }
5590
5591 // Looks like our output is not on time. Reset our on timed status.
5592 // Next time we mix samples from our input queue, then should be within
5593 // the StartupThreshold.
5594 mTimedAudioOutputOnTime = false;
5595 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005596 // the gap between the current output position and the proper start of
5597 // the next input sample is too big, so fill it with silence
5598 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5599
John Grossman9fbdee12012-03-26 17:51:46 -07005600 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005601 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5602 return NO_ERROR;
5603 } else {
5604 // the next input sample is late
5605 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5606 size_t onTimeSamplePosition =
5607 head.position() + lateFrames * mCblk->frameSize;
5608
5609 if (onTimeSamplePosition > head.buffer()->size()) {
5610 // all the remaining samples in the head are too late, so
5611 // drop it and move on
5612 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005613 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005614 continue;
5615 } else {
5616 // skip over the late samples
5617 head.setPosition(onTimeSamplePosition);
5618
5619 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005620 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005621
5622 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5623 return NO_ERROR;
5624 }
5625 }
5626 }
5627}
5628
5629// Yield samples from the timed buffer queue head up to the given output
5630// buffer's capacity.
5631//
5632// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005633void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005634 AudioBufferProvider::Buffer* buffer) {
5635
5636 const TimedBuffer& head = mTimedBufferQueue[0];
5637
5638 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5639 head.position());
5640
5641 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5642 mCblk->frameSize);
5643 size_t framesRequested = buffer->frameCount;
5644 buffer->frameCount = min(framesLeftInHead, framesRequested);
5645
John Grossman9fbdee12012-03-26 17:51:46 -07005646 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005647 mTimedAudioOutputOnTime = true;
5648}
5649
5650// Yield samples of silence up to the given output buffer's capacity
5651//
5652// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005653void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005654 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5655
5656 // lazily allocate a buffer filled with silence
5657 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5658 delete [] mTimedSilenceBuffer;
5659 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5660 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5661 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5662 }
5663
5664 buffer->raw = mTimedSilenceBuffer;
5665 size_t framesRequested = buffer->frameCount;
5666 buffer->frameCount = min(numFrames, framesRequested);
5667
5668 mTimedAudioOutputOnTime = false;
5669}
5670
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005671// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005672void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5673 AudioBufferProvider::Buffer* buffer) {
5674
5675 Mutex::Autolock _l(mTimedBufferQueueLock);
5676
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005677 // If the buffer which was just released is part of the buffer at the head
5678 // of the queue, be sure to update the amt of the buffer which has been
5679 // consumed. If the buffer being returned is not part of the head of the
5680 // queue, its either because the buffer is part of the silence buffer, or
5681 // because the head of the timed queue was trimmed after the mixer called
5682 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005683 if (buffer->raw == mTimedSilenceBuffer) {
5684 ALOG_ASSERT(!mQueueHeadInFlight,
5685 "Queue head in flight during release of silence buffer!");
5686 goto done;
5687 }
5688
5689 ALOG_ASSERT(mQueueHeadInFlight,
5690 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5691 " head in flight.");
5692
5693 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005694 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005695
5696 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005697 void* end = reinterpret_cast<void*>(
5698 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5699 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005700
John Grossman9fbdee12012-03-26 17:51:46 -07005701 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5702 "released buffer not within the head of the timed buffer"
5703 " queue; qHead = [%p, %p], released buffer = %p",
5704 start, end, buffer->raw);
5705
5706 head.setPosition(head.position() +
5707 (buffer->frameCount * mCblk->frameSize));
5708 mQueueHeadInFlight = false;
5709
John Grossman1c345192012-03-27 14:00:17 -07005710 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5711 "Bad bookkeeping during releaseBuffer! Should have at"
5712 " least %u queued frames, but we think we have only %u",
5713 buffer->frameCount, mFramesPendingInQueue);
5714
5715 mFramesPendingInQueue -= buffer->frameCount;
5716
John Grossman9fbdee12012-03-26 17:51:46 -07005717 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5718 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005719 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005720 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005721 }
John Grossman9fbdee12012-03-26 17:51:46 -07005722 } else {
5723 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5724 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005725 }
5726
John Grossman9fbdee12012-03-26 17:51:46 -07005727done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005728 buffer->raw = 0;
5729 buffer->frameCount = 0;
5730}
5731
Glenn Kasten288ed212012-04-25 17:52:27 -07005732size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005733 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005734 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005735}
5736
5737AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5738 : mPTS(0), mPosition(0) {}
5739
5740AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5741 const sp<IMemory>& buffer, int64_t pts)
5742 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5743
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744// ----------------------------------------------------------------------------
5745
5746// RecordTrack constructor must be called with AudioFlinger::mLock held
5747AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005748 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749 const sp<Client>& client,
5750 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005751 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005752 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 int sessionId)
5755 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005756 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005757 mOverflow(false)
5758{
5759 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005760 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5761 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5762 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5763 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5764 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5765 } else {
5766 mCblk->frameSize = sizeof(int8_t);
5767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768 }
5769}
5770
5771AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5772{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005773 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774}
5775
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005776// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005777status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778{
5779 audio_track_cblk_t* cblk = this->cblk();
5780 uint32_t framesAvail;
5781 uint32_t framesReq = buffer->frameCount;
5782
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005783 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005784 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005786 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005787 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 }
5789
5790 framesAvail = cblk->framesAvailable_l();
5791
Glenn Kastenf6b16782011-12-15 09:51:17 -08005792 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 uint32_t s = cblk->server;
5794 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5795
5796 if (framesReq > framesAvail) {
5797 framesReq = framesAvail;
5798 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005799 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 framesReq = bufferEnd - s;
5801 }
5802
5803 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804 buffer->frameCount = framesReq;
5805 return NO_ERROR;
5806 }
5807
5808getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005809 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 buffer->frameCount = 0;
5811 return NOT_ENOUGH_DATA;
5812}
5813
Glenn Kasten3acbd052012-02-28 10:39:56 -08005814status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005815 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816{
5817 sp<ThreadBase> thread = mThread.promote();
5818 if (thread != 0) {
5819 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005820 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 } else {
5822 return BAD_VALUE;
5823 }
5824}
5825
5826void AudioFlinger::RecordThread::RecordTrack::stop()
5827{
5828 sp<ThreadBase> thread = mThread.promote();
5829 if (thread != 0) {
5830 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005831 recordThread->mLock.lock();
5832 bool doStop = recordThread->stop_l(this);
5833 if (doStop) {
5834 TrackBase::reset();
5835 // Force overrun condition to avoid false overrun callback until first data is
5836 // read from buffer
5837 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5838 }
5839 recordThread->mLock.unlock();
5840 if (doStop) {
5841 AudioSystem::stopInput(recordThread->id());
5842 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 }
5844}
5845
Glenn Kasten510a3d62012-07-16 14:24:34 -07005846/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5847{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005848 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005849}
5850
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5852{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005853 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005854 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005856 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 mSessionId,
5858 mFrameCount,
5859 mState,
5860 mCblk->sampleRate,
5861 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005862 mCblk->user,
5863 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864}
5865
5866
5867// ----------------------------------------------------------------------------
5868
5869AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005870 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 DuplicatingThread *sourceThread,
5872 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005873 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005874 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005876 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5877 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 mActive(false), mSourceThread(sourceThread)
5879{
5880
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 if (mCblk != NULL) {
5882 mCblk->flags |= CBLK_DIRECTION_OUT;
5883 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 mOutBuffer.frameCount = 0;
5885 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005886 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005887 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5888 mCblk, mBuffer, mCblk->buffers,
5889 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005891 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 }
5893}
5894
5895AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5896{
5897 clearBufferQueue();
5898}
5899
Glenn Kasten3acbd052012-02-28 10:39:56 -08005900status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005901 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005903 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 if (status != NO_ERROR) {
5905 return status;
5906 }
5907
5908 mActive = true;
5909 mRetryCount = 127;
5910 return status;
5911}
5912
5913void AudioFlinger::PlaybackThread::OutputTrack::stop()
5914{
5915 Track::stop();
5916 clearBufferQueue();
5917 mOutBuffer.frameCount = 0;
5918 mActive = false;
5919}
5920
5921bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5922{
5923 Buffer *pInBuffer;
5924 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005925 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 bool outputBufferFull = false;
5927 inBuffer.frameCount = frames;
5928 inBuffer.i16 = data;
5929
5930 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5931
5932 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005933 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 sp<ThreadBase> thread = mThread.promote();
5935 if (thread != 0) {
5936 MixerThread *mixerThread = (MixerThread *)thread.get();
5937 if (mCblk->frameCount > frames){
5938 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5939 uint32_t startFrames = (mCblk->frameCount - frames);
5940 pInBuffer = new Buffer;
5941 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5942 pInBuffer->frameCount = startFrames;
5943 pInBuffer->i16 = pInBuffer->mBuffer;
5944 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5945 mBufferQueue.add(pInBuffer);
5946 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005947 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 }
5949 }
5950 }
5951 }
5952
5953 while (waitTimeLeftMs) {
5954 // First write pending buffers, then new data
5955 if (mBufferQueue.size()) {
5956 pInBuffer = mBufferQueue.itemAt(0);
5957 } else {
5958 pInBuffer = &inBuffer;
5959 }
5960
5961 if (pInBuffer->frameCount == 0) {
5962 break;
5963 }
5964
5965 if (mOutBuffer.frameCount == 0) {
5966 mOutBuffer.frameCount = pInBuffer->frameCount;
5967 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005968 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005969 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 outputBufferFull = true;
5971 break;
5972 }
5973 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5974 if (waitTimeLeftMs >= waitTimeMs) {
5975 waitTimeLeftMs -= waitTimeMs;
5976 } else {
5977 waitTimeLeftMs = 0;
5978 }
5979 }
5980
5981 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5982 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5983 mCblk->stepUser(outFrames);
5984 pInBuffer->frameCount -= outFrames;
5985 pInBuffer->i16 += outFrames * channelCount;
5986 mOutBuffer.frameCount -= outFrames;
5987 mOutBuffer.i16 += outFrames * channelCount;
5988
5989 if (pInBuffer->frameCount == 0) {
5990 if (mBufferQueue.size()) {
5991 mBufferQueue.removeAt(0);
5992 delete [] pInBuffer->mBuffer;
5993 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005994 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 } else {
5996 break;
5997 }
5998 }
5999 }
6000
6001 // If we could not write all frames, allocate a buffer and queue it for next time.
6002 if (inBuffer.frameCount) {
6003 sp<ThreadBase> thread = mThread.promote();
6004 if (thread != 0 && !thread->standby()) {
6005 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
6006 pInBuffer = new Buffer;
6007 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
6008 pInBuffer->frameCount = inBuffer.frameCount;
6009 pInBuffer->i16 = pInBuffer->mBuffer;
6010 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
6011 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01006012 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006014 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 }
6016 }
6017 }
6018
6019 // Calling write() with a 0 length buffer, means that no more data will be written:
6020 // If no more buffers are pending, fill output track buffer to make sure it is started
6021 // by output mixer.
6022 if (frames == 0 && mBufferQueue.size() == 0) {
6023 if (mCblk->user < mCblk->frameCount) {
6024 frames = mCblk->frameCount - mCblk->user;
6025 pInBuffer = new Buffer;
6026 pInBuffer->mBuffer = new int16_t[frames * channelCount];
6027 pInBuffer->frameCount = frames;
6028 pInBuffer->i16 = pInBuffer->mBuffer;
6029 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
6030 mBufferQueue.add(pInBuffer);
6031 } else if (mActive) {
6032 stop();
6033 }
6034 }
6035
6036 return outputBufferFull;
6037}
6038
6039status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
6040{
6041 int active;
6042 status_t result;
6043 audio_track_cblk_t* cblk = mCblk;
6044 uint32_t framesReq = buffer->frameCount;
6045
Steve Block3856b092011-10-20 11:56:00 +01006046// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 buffer->frameCount = 0;
6048
6049 uint32_t framesAvail = cblk->framesAvailable();
6050
6051
6052 if (framesAvail == 0) {
6053 Mutex::Autolock _l(cblk->lock);
6054 goto start_loop_here;
6055 while (framesAvail == 0) {
6056 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006057 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006058 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006059 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 }
6061 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6062 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006063 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 }
6065 // read the server count again
6066 start_loop_here:
6067 framesAvail = cblk->framesAvailable_l();
6068 }
6069 }
6070
6071// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006072// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073// }
6074
6075 if (framesReq > framesAvail) {
6076 framesReq = framesAvail;
6077 }
6078
6079 uint32_t u = cblk->user;
6080 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6081
Marco Nelissena1472d92012-03-30 14:36:54 -07006082 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 framesReq = bufferEnd - u;
6084 }
6085
6086 buffer->frameCount = framesReq;
6087 buffer->raw = (void *)cblk->buffer(u);
6088 return NO_ERROR;
6089}
6090
6091
6092void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6093{
6094 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095
6096 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006097 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 delete [] pBuffer->mBuffer;
6099 delete pBuffer;
6100 }
6101 mBufferQueue.clear();
6102}
6103
6104// ----------------------------------------------------------------------------
6105
6106AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6107 : RefBase(),
6108 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006109 // 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 -07006110 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006111 mPid(pid),
6112 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113{
6114 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6115}
6116
6117// Client destructor must be called with AudioFlinger::mLock held
6118AudioFlinger::Client::~Client()
6119{
6120 mAudioFlinger->removeClient_l(mPid);
6121}
6122
Glenn Kasten435dbe62012-01-30 10:15:48 -08006123sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124{
6125 return mMemoryDealer;
6126}
6127
John Grossman4ff14ba2012-02-08 16:37:41 -08006128// Reserve one of the limited slots for a timed audio track associated
6129// with this client
6130bool AudioFlinger::Client::reserveTimedTrack()
6131{
6132 const int kMaxTimedTracksPerClient = 4;
6133
6134 Mutex::Autolock _l(mTimedTrackLock);
6135
6136 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6137 ALOGW("can not create timed track - pid %d has exceeded the limit",
6138 mPid);
6139 return false;
6140 }
6141
6142 mTimedTrackCount++;
6143 return true;
6144}
6145
6146// Release a slot for a timed audio track
6147void AudioFlinger::Client::releaseTimedTrack()
6148{
6149 Mutex::Autolock _l(mTimedTrackLock);
6150 mTimedTrackCount--;
6151}
6152
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153// ----------------------------------------------------------------------------
6154
6155AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6156 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006157 sp<IBinder> binder)
6158 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159{
6160}
6161
6162AudioFlinger::NotificationClient::~NotificationClient()
6163{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164}
6165
6166void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6167{
6168 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006169 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170}
6171
6172// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006173#ifdef QCOM_HARDWARE
6174AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6175 int output, AudioSessionDescriptor *outputDesc,
6176 IDirectTrackClient* client, audio_output_flags_t outflag)
6177 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6178 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6179{
6180 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6181 createEffectThread();
6182
6183 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6184 mAudioFlinger->registerClient(mAudioFlingerClient);
6185
6186 allocateBufPool();
6187 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08006188 outputDesc->mVolumeScale = 1.0;
vivek mehta2192bc92012-12-04 11:46:08 -08006189 mDeathRecipient = new PMDeathRecipient(this);
6190 acquireWakeLock();
6191}
6192
6193AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6194 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6195 requestAndWaitForEffectsThreadExit();
6196 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6197 mAudioFlinger->deleteEffectSession();
6198 deallocateBufPool();
6199 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006200 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006201 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006202
Mingming Yin9b3dd172013-01-10 18:42:38 -08006203 {
6204 Mutex::Autolock _l(pmLock);
6205 if (mPowerManager != 0) {
6206 sp<IBinder> binder = mPowerManager->asBinder();
6207 binder->unlinkToDeath(mDeathRecipient);
6208 }
vivek mehta2192bc92012-12-04 11:46:08 -08006209 }
vivek mehta2192bc92012-12-04 11:46:08 -08006210}
6211
6212status_t AudioFlinger::DirectAudioTrack::start() {
6213 if(mIsPaused) {
6214 mIsPaused = false;
6215 mOutputDesc->stream->start(mOutputDesc->stream);
6216 }
6217 mOutputDesc->mActive = true;
6218 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6219 return NO_ERROR;
6220}
6221
6222void AudioFlinger::DirectAudioTrack::stop() {
6223 mOutputDesc->mActive = false;
6224 mOutputDesc->stream->stop(mOutputDesc->stream);
6225 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6226}
6227
6228void AudioFlinger::DirectAudioTrack::pause() {
6229 if(!mIsPaused) {
6230 mIsPaused = true;
6231 mOutputDesc->stream->pause(mOutputDesc->stream);
6232 mOutputDesc->mActive = false;
6233 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6234 }
6235}
6236
6237ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6238 ALOGV("Writing to AudioSessionOut");
6239 int isAvail = 0;
6240 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6241 if (!isAvail) {
6242 return 0;
6243 }
6244
6245 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6246 mEffectLock.lock();
6247 List<BufferInfo>::iterator it = mEffectsPool.begin();
6248 BufferInfo buf = *it;
6249 mEffectsPool.erase(it);
6250 memcpy((char *) buf.localBuf, (char *)buffer, size);
6251 buf.bytesToWrite = size;
6252 mEffectsPool.push_back(buf);
6253 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6254 mEffectLock.unlock();
6255 }
6256 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6257}
6258
6259void AudioFlinger::DirectAudioTrack::flush() {
6260 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6261 mEffectsPool.clear();
6262 mEffectsPool = mBufPool;
6263 }
6264 mOutputDesc->stream->flush(mOutputDesc->stream);
6265}
6266
6267void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6268}
6269
6270void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
Mingming Yin9b3dd172013-01-10 18:42:38 -08006271 mOutputDesc->mVolumeLeft = left;
6272 mOutputDesc->mVolumeRight = right;
Dorian Snyderf32d5702013-03-01 14:25:46 -08006273 mOutputDesc->stream->set_volume(mOutputDesc->stream,
6274 left * mOutputDesc->mVolumeScale,
6275 right* mOutputDesc->mVolumeScale);
vivek mehta2192bc92012-12-04 11:46:08 -08006276}
6277
6278int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6279 int64_t time;
6280 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6281 ALOGV("Timestamp %lld",time);
6282 return time;
6283}
6284
6285void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006286#ifdef QCOM_HARDWARE
6287 if (delayUs == 0 ) {
6288 ALOGV("Notify Audio Track of EOS event");
6289 mClient->notify(DIRECT_TRACK_EOS);
6290 } else {
6291 ALOGV("Notify Audio Track of hardware failure event");
6292 mClient->notify(DIRECT_TRACK_HW_FAIL);
6293 }
6294#else
vivek mehta2192bc92012-12-04 11:46:08 -08006295 ALOGV("Notify Audio Track of EOS event");
6296 mClient->notify(DIRECT_TRACK_EOS);
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006297#endif
vivek mehta2192bc92012-12-04 11:46:08 -08006298}
6299
6300void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6301 void *dsp_buf = NULL;
6302 void *local_buf = NULL;
6303
6304 //1. get the ion buffer information
6305 struct buf_info* buf = NULL;
6306 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6307 ALOGV("get buffer info %p",buf);
6308 if (!buf) {
6309 ALOGV("buffer is NULL");
6310 return;
6311 }
6312 int nSize = buf->bufsize;
6313 int bufferCount = buf->nBufs;
6314
6315 //2. allocate the buffer pool, allocate local buffers
6316 for (int i = 0; i < bufferCount; i++) {
6317 dsp_buf = (void *)buf->buffers[i];
6318 local_buf = malloc(nSize);
6319 memset(local_buf, 0, nSize);
6320 // Store this information for internal mapping / maintanence
6321 BufferInfo buf(local_buf, dsp_buf, nSize);
6322 buf.bytesToWrite = 0;
6323 mBufPool.push_back(buf);
6324 mEffectsPool.push_back(buf);
6325
6326 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6327 }
6328 free(buf);
6329}
6330
6331void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6332
6333 //1. Deallocate the local memory
6334 //2. Remove all the buffers from bufpool
6335 while (!mBufPool.empty()) {
6336 List<BufferInfo>::iterator it = mBufPool.begin();
6337 BufferInfo &memBuffer = *it;
6338 // free the local buffer corresponding to mem buffer
6339 if (memBuffer.localBuf) {
6340 free(memBuffer.localBuf);
6341 memBuffer.localBuf = NULL;
6342 }
6343 ALOGV("Removing from bufpool");
6344 mBufPool.erase(it);
6345 }
6346}
6347
6348status_t AudioFlinger::DirectAudioTrack::onTransact(
6349 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6350{
6351 return BnDirectTrack::onTransact(code, data, reply, flags);
6352}
6353
6354void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6355 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6356 return NULL;
6357}
6358
6359void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6360 while(1) {
6361 mEffectLock.lock();
6362 if (!mEffectConfigChanged && !mKillEffectsThread) {
6363 mEffectCv.wait(mEffectLock);
6364 }
6365
6366 if(mKillEffectsThread) {
6367 mEffectLock.unlock();
6368 break;
6369 }
6370
6371 if (mEffectConfigChanged) {
6372 mEffectConfigChanged = false;
6373 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6374 it != mEffectsPool.end(); it++) {
6375 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6376 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6377 (int16_t *)it->localBuf,
6378 (int16_t *)it->dspBuf,
6379 it->bytesToWrite);
6380 if (mEffectConfigChanged) {
6381 break;
6382 }
6383 }
6384
6385 }
6386 mEffectLock.unlock();
6387 }
6388 ALOGV("Effects thread is dead");
6389 mEffectsThreadAlive = false;
6390}
6391
6392void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6393 if (!mEffectsThreadAlive)
6394 return;
6395 mKillEffectsThread = true;
6396 mEffectCv.signal();
6397 pthread_join(mEffectsThread,NULL);
6398 ALOGV("effects thread killed");
6399}
6400
6401void AudioFlinger::DirectAudioTrack::createEffectThread() {
6402 //Create the effects thread
6403 pthread_attr_t attr;
6404 pthread_attr_init(&attr);
6405 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6406 mEffectsThreadAlive = true;
6407 ALOGV("Creating Effects Thread");
6408 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6409}
6410AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6411{
6412 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6413 pBaseClass = (DirectAudioTrack*)obj;
6414}
6415
6416void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6417 pBaseClass->mAudioFlinger.clear();
6418 ALOGW("AudioFlinger server died!");
6419}
6420
6421void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6422 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6423 ALOGV("ioConfigChanged() event %d", event);
6424 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6425 ALOGV("Received notification for change in effect module");
6426 // Seek to current media time - flush the decoded buffers with the driver
6427 pBaseClass->mEffectConfigChanged = true;
6428 // Signal effects thread to re-apply effects
6429 ALOGV("Signalling Effects Thread");
6430 pBaseClass->mEffectCv.signal();
6431
6432 }
6433 ALOGV("ioConfigChanged Out");
6434}
6435
6436void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6437{
6438 Mutex::Autolock _l(pmLock);
6439
6440 if (mPowerManager == 0) {
6441 // use checkService() to avoid blocking if power service is not up yet
6442 sp<IBinder> binder =
6443 defaultServiceManager()->checkService(String16("power"));
6444 if (binder == 0) {
6445 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6446 } else {
6447 mPowerManager = interface_cast<IPowerManager>(binder);
6448 binder->linkToDeath(mDeathRecipient);
6449 }
6450 }
6451 if (mPowerManager != 0 && mWakeLockToken == 0) {
6452 sp<IBinder> binder = new BBinder();
6453 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6454 binder,
6455 String16(lockName));
6456 if (status == NO_ERROR) {
6457 mWakeLockToken = binder;
6458 }
6459 ALOGV("acquireWakeLock() status %d", status);
6460 }
6461}
6462
6463void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6464{
6465 Mutex::Autolock _l(pmLock);
6466
6467 if (mWakeLockToken != 0) {
6468 ALOGV("releaseWakeLock()");
6469 if (mPowerManager != 0) {
6470 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6471 }
6472 mWakeLockToken.clear();
6473 }
6474}
6475
6476void AudioFlinger::DirectAudioTrack::clearPowerManager()
6477{
vivek mehta2192bc92012-12-04 11:46:08 -08006478 releaseWakeLock();
Mingming Yin9b3dd172013-01-10 18:42:38 -08006479 Mutex::Autolock _l(pmLock);
vivek mehta2192bc92012-12-04 11:46:08 -08006480 mPowerManager.clear();
6481}
6482
6483void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6484{
6485 parentClass->clearPowerManager();
6486 ALOGW("power manager service died !!!");
6487}
6488#endif
6489
6490// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491
6492AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6493 : BnAudioTrack(),
6494 mTrack(track)
6495{
6496}
6497
6498AudioFlinger::TrackHandle::~TrackHandle() {
6499 // just stop the track on deletion, associated resources
6500 // will be freed from the main thread once all pending buffers have
6501 // been played. Unless it's not in the active track list, in which
6502 // case we free everything now...
6503 mTrack->destroy();
6504}
6505
Glenn Kasten90716c52012-01-26 13:40:12 -08006506sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6507 return mTrack->getCblk();
6508}
6509
Glenn Kasten3acbd052012-02-28 10:39:56 -08006510status_t AudioFlinger::TrackHandle::start() {
6511 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512}
6513
6514void AudioFlinger::TrackHandle::stop() {
6515 mTrack->stop();
6516}
6517
6518void AudioFlinger::TrackHandle::flush() {
6519 mTrack->flush();
6520}
6521
6522void AudioFlinger::TrackHandle::mute(bool e) {
6523 mTrack->mute(e);
6524}
6525
6526void AudioFlinger::TrackHandle::pause() {
6527 mTrack->pause();
6528}
6529
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6531{
6532 return mTrack->attachAuxEffect(EffectId);
6533}
6534
John Grossman4ff14ba2012-02-08 16:37:41 -08006535status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6536 sp<IMemory>* buffer) {
6537 if (!mTrack->isTimedTrack())
6538 return INVALID_OPERATION;
6539
6540 PlaybackThread::TimedTrack* tt =
6541 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6542 return tt->allocateTimedBuffer(size, buffer);
6543}
6544
6545status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6546 int64_t pts) {
6547 if (!mTrack->isTimedTrack())
6548 return INVALID_OPERATION;
6549
6550 PlaybackThread::TimedTrack* tt =
6551 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6552 return tt->queueTimedBuffer(buffer, pts);
6553}
6554
6555status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6556 const LinearTransform& xform, int target) {
6557
6558 if (!mTrack->isTimedTrack())
6559 return INVALID_OPERATION;
6560
6561 PlaybackThread::TimedTrack* tt =
6562 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6563 return tt->setMediaTimeTransform(
6564 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6565}
6566
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567status_t AudioFlinger::TrackHandle::onTransact(
6568 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6569{
6570 return BnAudioTrack::onTransact(code, data, reply, flags);
6571}
6572
6573// ----------------------------------------------------------------------------
6574
6575sp<IAudioRecord> AudioFlinger::openRecord(
6576 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006577 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006579 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006580 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006582 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006583 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 int *sessionId,
6585 status_t *status)
6586{
6587 sp<RecordThread::RecordTrack> recordTrack;
6588 sp<RecordHandle> recordHandle;
6589 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 status_t lStatus;
6591 RecordThread *thread;
6592 size_t inFrameCount;
6593 int lSessionId;
6594
6595 // check calling permissions
6596 if (!recordingAllowed()) {
6597 lStatus = PERMISSION_DENIED;
6598 goto Exit;
6599 }
6600
6601 // add client to list
6602 { // scope for mLock
6603 Mutex::Autolock _l(mLock);
6604 thread = checkRecordThread_l(input);
6605 if (thread == NULL) {
6606 lStatus = BAD_VALUE;
6607 goto Exit;
6608 }
6609
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006610 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611
6612 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006613 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 lSessionId = *sessionId;
6615 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006616 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006617 if (sessionId != NULL) {
6618 *sessionId = lSessionId;
6619 }
6620 }
6621 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006622 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6623 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006625 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6627 // destructor is called by the TrackBase destructor with mLock held
6628 client.clear();
6629 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630 goto Exit;
6631 }
6632
6633 // return to handle to client
6634 recordHandle = new RecordHandle(recordTrack);
6635 lStatus = NO_ERROR;
6636
6637Exit:
6638 if (status) {
6639 *status = lStatus;
6640 }
6641 return recordHandle;
6642}
6643
6644// ----------------------------------------------------------------------------
6645
6646AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6647 : BnAudioRecord(),
6648 mRecordTrack(recordTrack)
6649{
6650}
6651
6652AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006653 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006654 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655}
6656
Glenn Kasten90716c52012-01-26 13:40:12 -08006657sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6658 return mRecordTrack->getCblk();
6659}
6660
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006661status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006662 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006663 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664}
6665
6666void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006667 stop_nonvirtual();
6668}
6669
6670void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006671 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672 mRecordTrack->stop();
6673}
6674
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675status_t AudioFlinger::RecordHandle::onTransact(
6676 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6677{
6678 return BnAudioRecord::onTransact(code, data, reply, flags);
6679}
6680
6681// ----------------------------------------------------------------------------
6682
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006683AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6684 AudioStreamIn *input,
6685 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006686 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006687 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006688 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006689 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006690 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006691 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006692 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006693 mReqSampleRate(sampleRate)
6694 // mBytesRead is only meaningful while active, and so is cleared in start()
6695 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696{
Glenn Kasten480b4682012-02-28 12:30:08 -08006697 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006698
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 readInputParameters();
6700}
6701
6702
6703AudioFlinger::RecordThread::~RecordThread()
6704{
6705 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006706 delete mResampler;
6707 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708}
6709
6710void AudioFlinger::RecordThread::onFirstRef()
6711{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006712 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713}
6714
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006715status_t AudioFlinger::RecordThread::readyToRun()
6716{
6717 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006718 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006719 return status;
6720}
6721
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722bool AudioFlinger::RecordThread::threadLoop()
6723{
6724 AudioBufferProvider::Buffer buffer;
6725 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006726 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727
Eric Laurent44d98482010-09-30 16:12:31 -07006728 nsecs_t lastWarning = 0;
6729
Glenn Kastene4e2a372012-07-23 12:55:09 -07006730 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006731 acquireWakeLock();
6732
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006733 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006734 bool readOnce = false;
6735
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 // start recording
6737 while (!exitPending()) {
6738
6739 processConfigEvents();
6740
6741 { // scope for mLock
6742 Mutex::Autolock _l(mLock);
6743 checkForNewParameters_l();
6744 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006745 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746
6747 if (exitPending()) break;
6748
Eric Laurentfeb0db62011-07-22 09:04:31 -07006749 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006750 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 // go to sleep
6752 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006753 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006754 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 continue;
6756 }
6757 if (mActiveTrack != 0) {
6758 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006759 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 mActiveTrack.clear();
6761 mStartStopCond.broadcast();
6762 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6763 if (mReqChannelCount != mActiveTrack->channelCount()) {
6764 mActiveTrack.clear();
6765 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006766 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 // record start succeeds only if first read from audio input
6768 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006769 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 mActiveTrack->mState = TrackBase::ACTIVE;
6771 } else {
6772 mActiveTrack.clear();
6773 }
6774 mStartStopCond.broadcast();
6775 }
6776 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006777 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6778 removeTrack_l(mActiveTrack);
6779 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 }
6781 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006782 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 }
6784
6785 if (mActiveTrack != 0) {
6786 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6787 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006788 unlockEffectChains(effectChains);
6789 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 continue;
6791 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006792 for (size_t i = 0; i < effectChains.size(); i ++) {
6793 effectChains[i]->process_l();
6794 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006795
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006797 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006798 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006800 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 // no resampling
6802 while (framesOut) {
6803 size_t framesIn = mFrameCount - mRsmpInIndex;
6804 if (framesIn) {
6805 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6806 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6807 if (framesIn > framesOut)
6808 framesIn = framesOut;
6809 mRsmpInIndex += framesIn;
6810 framesOut -= framesIn;
6811 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006812 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 memcpy(dst, src, framesIn * mFrameSize);
6814 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006816 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6817 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006819 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6820 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 }
6822 }
6823 }
6824 if (framesOut && mFrameCount == mRsmpInIndex) {
6825 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006826 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006827 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 framesOut = 0;
6829 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006830 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831 mRsmpInIndex = 0;
6832 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006833 if (mBytesRead <= 0) {
6834 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6835 {
6836 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 // Force input into standby so that it tries to
6838 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006839 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006840 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 }
6842 mRsmpInIndex = mFrameCount;
6843 framesOut = 0;
6844 buffer.frameCount = 0;
6845 }
6846 }
6847 }
6848 } else {
6849 // resampling
6850
6851 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6852 // alter output frame count as if we were expecting stereo samples
6853 if (mChannelCount == 1 && mReqChannelCount == 1) {
6854 framesOut >>= 1;
6855 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006856 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6858 // are 32 bit aligned which should be always true.
6859 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006860 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006862 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6863 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006865 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 }
6867
6868 }
Eric Laurenta011e352012-03-29 15:51:43 -07006869 if (mFramestoDrop == 0) {
6870 mActiveTrack->releaseBuffer(&buffer);
6871 } else {
6872 if (mFramestoDrop > 0) {
6873 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006874 if (mFramestoDrop <= 0) {
6875 clearSyncStartEvent();
6876 }
6877 } else {
6878 mFramestoDrop += buffer.frameCount;
6879 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6880 mSyncStartEvent->isCancelled()) {
6881 ALOGW("Synced record %s, session %d, trigger session %d",
6882 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6883 mActiveTrack->sessionId(),
6884 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6885 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006886 }
6887 }
6888 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006889 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 }
6891 // client isn't retrieving buffers fast enough
6892 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006893 if (!mActiveTrack->setOverflow()) {
6894 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006895 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006896 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006897 lastWarning = now;
6898 }
6899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 // Release the processor for a while before asking for a new buffer.
6901 // This will give the application more chance to read from the buffer and
6902 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006903 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 }
6905 }
Eric Laurentec437d82011-07-26 20:54:46 -07006906 // enable changes in effect chain
6907 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006908 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 }
6910
Glenn Kastene4e2a372012-07-23 12:55:09 -07006911 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912
Glenn Kasten33e6e352012-07-16 15:56:57 -07006913 {
6914 Mutex::Autolock _l(mLock);
6915 mActiveTrack.clear();
6916 mStartStopCond.broadcast();
6917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918
Eric Laurentfeb0db62011-07-22 09:04:31 -07006919 releaseWakeLock();
6920
Steve Block3856b092011-10-20 11:56:00 +01006921 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 return false;
6923}
6924
Glenn Kastene4e2a372012-07-23 12:55:09 -07006925void AudioFlinger::RecordThread::standby()
6926{
6927 if (!mStandby) {
6928 inputStandBy();
6929 mStandby = true;
6930 }
6931}
6932
6933void AudioFlinger::RecordThread::inputStandBy()
6934{
6935 mInput->stream->common.standby(&mInput->stream->common);
6936}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006937
6938sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6939 const sp<AudioFlinger::Client>& client,
6940 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006941 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006942 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006943 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006944 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006945 IAudioFlinger::track_flags_t flags,
6946 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006947 status_t *status)
6948{
6949 sp<RecordTrack> track;
6950 status_t lStatus;
6951
6952 lStatus = initCheck();
6953 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006954 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006955 goto Exit;
6956 }
6957
Glenn Kasten1879fff2012-07-11 15:36:59 -07006958 // FIXME use flags and tid similar to createTrack_l()
6959
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006960 { // scope for mLock
6961 Mutex::Autolock _l(mLock);
6962
6963 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006964 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006965
Glenn Kasten7378ca52012-01-20 13:44:40 -08006966 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006967 lStatus = NO_MEMORY;
6968 goto Exit;
6969 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006970 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006971
Eric Laurent59bd0da2011-08-01 09:52:20 -07006972 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006973 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006974 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006975 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6976 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006977 }
6978 lStatus = NO_ERROR;
6979
6980Exit:
6981 if (status) {
6982 *status = lStatus;
6983 }
6984 return track;
6985}
6986
Eric Laurenta011e352012-03-29 15:51:43 -07006987status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006988 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006989 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990{
Glenn Kasten58912562012-04-03 10:45:00 -07006991 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006992 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006994
6995 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006996 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006997 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6998 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6999 triggerSession,
7000 recordTrack->sessionId(),
7001 syncStartEventCallback,
7002 this);
Eric Laurent29864602012-05-08 18:57:51 -07007003 // Sync event can be cancelled by the trigger session if the track is not in a
7004 // compatible state in which case we start record immediately
7005 if (mSyncStartEvent->isCancelled()) {
7006 clearSyncStartEvent();
7007 } else {
7008 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
7009 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
7010 }
Eric Laurenta011e352012-03-29 15:51:43 -07007011 }
7012
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08007014 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 if (mActiveTrack != 0) {
7016 if (recordTrack != mActiveTrack.get()) {
7017 status = -EBUSY;
7018 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
7019 mActiveTrack->mState = TrackBase::ACTIVE;
7020 }
7021 return status;
7022 }
7023
7024 recordTrack->mState = TrackBase::IDLE;
7025 mActiveTrack = recordTrack;
7026 mLock.unlock();
7027 status_t status = AudioSystem::startInput(mId);
7028 mLock.lock();
7029 if (status != NO_ERROR) {
7030 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07007031 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 return status;
7033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034 mRsmpInIndex = mFrameCount;
7035 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08007036 if (mResampler != NULL) {
7037 mResampler->reset();
7038 }
7039 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01007041 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07007042 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08007044 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 mActiveTrack.clear();
7046 status = INVALID_OPERATION;
7047 goto startError;
7048 }
7049 mStartStopCond.wait(mLock);
7050 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007051 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 status = BAD_VALUE;
7053 goto startError;
7054 }
Steve Block3856b092011-10-20 11:56:00 +01007055 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 return status;
7057 }
7058startError:
7059 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07007060 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 return status;
7062}
7063
Eric Laurenta011e352012-03-29 15:51:43 -07007064void AudioFlinger::RecordThread::clearSyncStartEvent()
7065{
7066 if (mSyncStartEvent != 0) {
7067 mSyncStartEvent->cancel();
7068 }
7069 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007070 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007071}
7072
7073void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7074{
7075 sp<SyncEvent> strongEvent = event.promote();
7076
7077 if (strongEvent != 0) {
7078 RecordThread *me = (RecordThread *)strongEvent->cookie();
7079 me->handleSyncStartEvent(strongEvent);
7080 }
7081}
7082
7083void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7084{
Eric Laurent29864602012-05-08 18:57:51 -07007085 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007086 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7087 // from audio HAL
7088 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007089 }
7090}
7091
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007092bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007093 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007094 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7095 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007096 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007097 recordTrack->mState = TrackBase::PAUSING;
7098 // do not wait for mStartStopCond if exiting
7099 if (exitPending()) {
7100 return true;
7101 }
7102 mStartStopCond.wait(mLock);
7103 // if we have been restarted, recordTrack == mActiveTrack.get() here
7104 if (exitPending() || recordTrack != mActiveTrack.get()) {
7105 ALOGV("Record stopped OK");
7106 return true;
7107 }
7108 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109}
7110
Glenn Kasten106e8a42012-08-02 13:37:12 -07007111bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007112{
7113 return false;
7114}
7115
7116status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7117{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007118#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 -07007119 if (!isValidSyncEvent(event)) {
7120 return BAD_VALUE;
7121 }
7122
Glenn Kasten510a3d62012-07-16 14:24:34 -07007123 int eventSession = event->triggerSession();
7124 status_t ret = NAME_NOT_FOUND;
7125
Eric Laurenta011e352012-03-29 15:51:43 -07007126 Mutex::Autolock _l(mLock);
7127
Glenn Kasten510a3d62012-07-16 14:24:34 -07007128 for (size_t i = 0; i < mTracks.size(); i++) {
7129 sp<RecordTrack> track = mTracks[i];
7130 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007131 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007132 ret = NO_ERROR;
7133 }
Eric Laurenta011e352012-03-29 15:51:43 -07007134 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007135 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007136#else
7137 return BAD_VALUE;
7138#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007139}
7140
7141void AudioFlinger::RecordThread::RecordTrack::destroy()
7142{
7143 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7144 sp<RecordTrack> keep(this);
7145 {
7146 sp<ThreadBase> thread = mThread.promote();
7147 if (thread != 0) {
7148 if (mState == ACTIVE || mState == RESUMING) {
7149 AudioSystem::stopInput(thread->id());
7150 }
7151 AudioSystem::releaseInput(thread->id());
7152 Mutex::Autolock _l(thread->mLock);
7153 RecordThread *recordThread = (RecordThread *) thread.get();
7154 recordThread->destroyTrack_l(this);
7155 }
7156 }
7157}
7158
7159// destroyTrack_l() must be called with ThreadBase::mLock held
7160void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7161{
7162 track->mState = TrackBase::TERMINATED;
7163 // active tracks are removed by threadLoop()
7164 if (mActiveTrack != track) {
7165 removeTrack_l(track);
7166 }
7167}
7168
7169void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7170{
7171 mTracks.remove(track);
7172 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007173}
7174
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007175void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007177 dumpInternals(fd, args);
7178 dumpTracks(fd, args);
7179 dumpEffectChains(fd, args);
7180}
7181
7182void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7183{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184 const size_t SIZE = 256;
7185 char buffer[SIZE];
7186 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187
7188 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7189 result.append(buffer);
7190
7191 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7193 result.append(buffer);
7194 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7195 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007196 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197 result.append(buffer);
7198 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7199 result.append(buffer);
7200 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7201 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007203 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007205
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206 write(fd, result.string(), result.size());
7207
7208 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007209}
7210
7211void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7212{
7213 const size_t SIZE = 256;
7214 char buffer[SIZE];
7215 String8 result;
7216
7217 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7218 result.append(buffer);
7219 RecordTrack::appendDumpHeader(result);
7220 for (size_t i = 0; i < mTracks.size(); ++i) {
7221 sp<RecordTrack> track = mTracks[i];
7222 if (track != 0) {
7223 track->dump(buffer, SIZE);
7224 result.append(buffer);
7225 }
7226 }
7227
7228 if (mActiveTrack != 0) {
7229 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7230 result.append(buffer);
7231 RecordTrack::appendDumpHeader(result);
7232 mActiveTrack->dump(buffer, SIZE);
7233 result.append(buffer);
7234
7235 }
7236 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237}
7238
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007239// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007240status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241{
7242 size_t framesReq = buffer->frameCount;
7243 size_t framesReady = mFrameCount - mRsmpInIndex;
7244 int channelCount;
7245
7246 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007247 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007248 if (mBytesRead <= 0) {
7249 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7250 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 // Force input into standby so that it tries to
7252 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007253 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007254 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007256 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257 buffer->frameCount = 0;
7258 return NOT_ENOUGH_DATA;
7259 }
7260 mRsmpInIndex = 0;
7261 framesReady = mFrameCount;
7262 }
7263
7264 if (framesReq > framesReady) {
7265 framesReq = framesReady;
7266 }
7267
7268 if (mChannelCount == 1 && mReqChannelCount == 2) {
7269 channelCount = 1;
7270 } else {
7271 channelCount = 2;
7272 }
7273 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7274 buffer->frameCount = framesReq;
7275 return NO_ERROR;
7276}
7277
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007278// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7280{
7281 mRsmpInIndex += buffer->frameCount;
7282 buffer->frameCount = 0;
7283}
7284
7285bool AudioFlinger::RecordThread::checkForNewParameters_l()
7286{
7287 bool reconfig = false;
7288
7289 while (!mNewParameters.isEmpty()) {
7290 status_t status = NO_ERROR;
7291 String8 keyValuePair = mNewParameters[0];
7292 AudioParameter param = AudioParameter(keyValuePair);
7293 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007294 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 int reqSamplingRate = mReqSampleRate;
7296 int reqChannelCount = mReqChannelCount;
7297
7298 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7299 reqSamplingRate = value;
7300 reconfig = true;
7301 }
7302 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007303 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304 reconfig = true;
7305 }
7306 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007307 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 reconfig = true;
7309 }
7310 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7311 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007312 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313 // if frame count is changed after track creation
7314 if (mActiveTrack != 0) {
7315 status = INVALID_OPERATION;
7316 } else {
7317 reconfig = true;
7318 }
7319 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007320 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7321 // forward device change to effects that have requested to be
7322 // aware of attached audio device.
7323 for (size_t i = 0; i < mEffectChains.size(); i++) {
7324 mEffectChains[i]->setDevice_l(value);
7325 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007326
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007327 // store input device and output device but do not forward output device to audio HAL.
7328 // Note that status is ignored by the caller for output device
7329 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007330 if (audio_is_output_devices(value)) {
7331 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007332 status = BAD_VALUE;
7333 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007334 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007335 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007336 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007337 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7338 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007339 for (size_t i = 0; i < mTracks.size(); i++) {
7340 sp<RecordTrack> track = mTracks[i];
7341 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7342 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7343 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007344 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007345 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007346 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007347 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7348 mAudioSource != (audio_source_t)value) {
7349 // forward device change to effects that have requested to be
7350 // aware of attached audio device.
7351 for (size_t i = 0; i < mEffectChains.size(); i++) {
7352 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7353 }
7354 mAudioSource = (audio_source_t)value;
7355 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007357 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007359 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007360 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7361 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 }
7363 if (reconfig) {
7364 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007365 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007366 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007367 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007368 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007369 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 status = NO_ERROR;
7371 }
7372 if (status == NO_ERROR) {
7373 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007374 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375 }
7376 }
7377 }
7378
7379 mNewParameters.removeAt(0);
7380
7381 mParamStatus = status;
7382 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007383 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7384 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007385 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 }
7387 return reconfig;
7388}
7389
7390String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7391{
Dima Zavinfce7a472011-04-19 22:30:36 -07007392 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007393 String8 out_s8 = String8();
7394
7395 Mutex::Autolock _l(mLock);
7396 if (initCheck() != NO_ERROR) {
7397 return out_s8;
7398 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007399
Dima Zavin799a70e2011-04-18 16:57:27 -07007400 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007401 out_s8 = String8(s);
7402 free(s);
7403 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404}
7405
7406void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7407 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007408 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409
7410 switch (event) {
7411 case AudioSystem::INPUT_OPENED:
7412 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007413 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 desc.samplingRate = mSampleRate;
7415 desc.format = mFormat;
7416 desc.frameCount = mFrameCount;
7417 desc.latency = 0;
7418 param2 = &desc;
7419 break;
7420
7421 case AudioSystem::INPUT_CLOSED:
7422 default:
7423 break;
7424 }
7425 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7426}
7427
7428void AudioFlinger::RecordThread::readInputParameters()
7429{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007430 delete mRsmpInBuffer;
7431 // mRsmpInBuffer is always assigned a new[] below
7432 delete mRsmpOutBuffer;
7433 mRsmpOutBuffer = NULL;
7434 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007435 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436
Dima Zavin799a70e2011-04-18 16:57:27 -07007437 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007438 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007439 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007440 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007441 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007442 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007444 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007445 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7446
Glenn Kasten53d76db2012-03-08 12:32:47 -08007447 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 {
7449 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007450 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7451 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 if (mChannelCount == 1 && mReqChannelCount == 2) {
7453 channelCount = 1;
7454 } else {
7455 channelCount = 2;
7456 }
7457 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7458 mResampler->setSampleRate(mSampleRate);
7459 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7460 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7461
7462 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7463 if (mChannelCount == 1 && mReqChannelCount == 1) {
7464 mFrameCount >>= 1;
7465 }
7466
7467 }
7468 mRsmpInIndex = mFrameCount;
7469}
7470
7471unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7472{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007473 Mutex::Autolock _l(mLock);
7474 if (initCheck() != NO_ERROR) {
7475 return 0;
7476 }
7477
Dima Zavin799a70e2011-04-18 16:57:27 -07007478 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479}
7480
Glenn Kasten106e8a42012-08-02 13:37:12 -07007481uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007482{
7483 Mutex::Autolock _l(mLock);
7484 uint32_t result = 0;
7485 if (getEffectChain_l(sessionId) != 0) {
7486 result = EFFECT_SESSION;
7487 }
7488
Glenn Kasten510a3d62012-07-16 14:24:34 -07007489 for (size_t i = 0; i < mTracks.size(); ++i) {
7490 if (sessionId == mTracks[i]->sessionId()) {
7491 result |= TRACK_SESSION;
7492 break;
7493 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007494 }
7495
7496 return result;
7497}
7498
Glenn Kasten106e8a42012-08-02 13:37:12 -07007499KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007500{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007501 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007502 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007503 for (size_t j = 0; j < mTracks.size(); ++j) {
7504 sp<RecordThread::RecordTrack> track = mTracks[j];
7505 int sessionId = track->sessionId();
7506 if (ids.indexOfKey(sessionId) < 0) {
7507 ids.add(sessionId, true);
7508 }
7509 }
7510 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007511}
7512
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007513AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7514{
7515 Mutex::Autolock _l(mLock);
7516 AudioStreamIn *input = mInput;
7517 mInput = NULL;
7518 return input;
7519}
7520
7521// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007522audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007523{
7524 if (mInput == NULL) {
7525 return NULL;
7526 }
7527 return &mInput->stream->common;
7528}
7529
7530
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531// ----------------------------------------------------------------------------
7532
Eric Laurenta4c5a552012-03-29 10:12:40 -07007533audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7534{
7535 if (!settingsAllowed()) {
7536 return 0;
7537 }
7538 Mutex::Autolock _l(mLock);
7539 return loadHwModule_l(name);
7540}
7541
7542// loadHwModule_l() must be called with AudioFlinger::mLock held
7543audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7544{
7545 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7546 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7547 ALOGW("loadHwModule() module %s already loaded", name);
7548 return mAudioHwDevs.keyAt(i);
7549 }
7550 }
7551
Eric Laurenta4c5a552012-03-29 10:12:40 -07007552 audio_hw_device_t *dev;
7553
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007554 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007555 if (rc) {
7556 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7557 return 0;
7558 }
7559
7560 mHardwareStatus = AUDIO_HW_INIT;
7561 rc = dev->init_check(dev);
7562 mHardwareStatus = AUDIO_HW_IDLE;
7563 if (rc) {
7564 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7565 return 0;
7566 }
7567
John Grossmanee578c02012-07-23 17:05:46 -07007568 // Check and cache this HAL's level of support for master mute and master
7569 // volume. If this is the first HAL opened, and it supports the get
7570 // methods, use the initial values provided by the HAL as the current
7571 // master mute and volume settings.
7572
7573 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7574 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007575 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007576
madmack2f8d3672013-01-14 21:19:20 -05007577#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007578 if (0 == mAudioHwDevs.size()) {
7579 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7580 if (NULL != dev->get_master_volume) {
7581 float mv;
7582 if (OK == dev->get_master_volume(dev, &mv)) {
7583 mMasterVolume = mv;
7584 }
7585 }
7586
7587 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7588 if (NULL != dev->get_master_mute) {
7589 bool mm;
7590 if (OK == dev->get_master_mute(dev, &mm)) {
7591 mMasterMute = mm;
7592 }
7593 }
7594 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007595#endif
John Grossmanee578c02012-07-23 17:05:46 -07007596
Eric Laurenta4c5a552012-03-29 10:12:40 -07007597 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007598 if ((NULL != dev->set_master_volume) &&
7599 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7600 flags = static_cast<AudioHwDevice::Flags>(flags |
7601 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7602 }
7603
madmack2f8d3672013-01-14 21:19:20 -05007604#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007605 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7606 if ((NULL != dev->set_master_mute) &&
7607 (OK == dev->set_master_mute(dev, mMasterMute))) {
7608 flags = static_cast<AudioHwDevice::Flags>(flags |
7609 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7610 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007611#endif
John Grossmanee578c02012-07-23 17:05:46 -07007612
Eric Laurenta4c5a552012-03-29 10:12:40 -07007613 mHardwareStatus = AUDIO_HW_IDLE;
7614 }
7615
7616 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007617 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007618
7619 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007620 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007621
7622 return handle;
7623
7624}
7625
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007626// ----------------------------------------------------------------------------
7627
7628int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7629{
7630 Mutex::Autolock _l(mLock);
7631 PlaybackThread *thread = primaryPlaybackThread_l();
7632 return thread != NULL ? thread->sampleRate() : 0;
7633}
7634
7635int32_t AudioFlinger::getPrimaryOutputFrameCount()
7636{
7637 Mutex::Autolock _l(mLock);
7638 PlaybackThread *thread = primaryPlaybackThread_l();
7639 return thread != NULL ? thread->frameCountHAL() : 0;
7640}
7641
7642// ----------------------------------------------------------------------------
7643
Eric Laurenta4c5a552012-03-29 10:12:40 -07007644audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7645 audio_devices_t *pDevices,
7646 uint32_t *pSamplingRate,
7647 audio_format_t *pFormat,
7648 audio_channel_mask_t *pChannelMask,
7649 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007650 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651{
7652 status_t status;
7653 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007654 struct audio_config config = {
7655 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7656 channel_mask: pChannelMask ? *pChannelMask : 0,
7657 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7658 };
7659 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007660 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661
Eric Laurenta4c5a552012-03-29 10:12:40 -07007662 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7663 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007664 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007665 config.sample_rate,
7666 config.format,
7667 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007668 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669
7670 if (pDevices == NULL || *pDevices == 0) {
7671 return 0;
7672 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007673
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674 Mutex::Autolock _l(mLock);
7675
Eric Laurenta4c5a552012-03-29 10:12:40 -07007676 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007677 if (outHwDev == NULL)
7678 return 0;
7679
John Grossmanee578c02012-07-23 17:05:46 -07007680 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007681 audio_io_handle_t id = nextUniqueId();
7682
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007683 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007684
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007685#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007686 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007687 id,
7688 *pDevices,
7689 (audio_output_flags_t)flags,
7690 &config,
7691 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007692#else
7693 status = hwDevHal->open_output_stream(hwDevHal,
7694 *pDevices,
7695 (int *)&config.format,
7696 &config.channel_mask,
7697 &config.sample_rate,
7698 &outStream);
7699 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7700 flags = (audio_output_flags_t)newflags;
7701#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007702
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007703 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007704 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007705 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007706 config.sample_rate,
7707 config.format,
7708 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007709 status);
7710
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007711 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007712 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007713#ifdef QCOM_HARDWARE
7714 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7715 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7716 desc->mActive = true;
7717 //TODO: no stream type
7718 //desc->mStreamType = streamType;
7719 desc->mVolumeLeft = 1.0;
7720 desc->mVolumeRight = 1.0;
7721 desc->device = *pDevices;
7722 mDirectAudioTracks.add(id, desc);
7723 } else
7724#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007725 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007726 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7727 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007729 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 } else {
7731 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007732 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 }
vivek mehta2192bc92012-12-04 11:46:08 -08007734#ifdef QCOM_HARDWARE
7735 if (thread != NULL)
7736#endif
7737 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738
Dorian Snyderf32d5702013-03-01 14:25:46 -08007739#ifdef QCOM_HARDWARE
7740 // if the device is a A2DP, then this is an A2DP Output
7741 if ( true == audio_is_a2dp_device((audio_devices_t) *pDevices) )
7742 {
7743 mA2DPHandle = id;
7744 ALOGV("A2DP device activated. The handle is set to %d", mA2DPHandle);
7745 }
7746#endif
7747
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007748 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7749 if (pFormat != NULL) *pFormat = config.format;
7750 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007751#ifdef QCOM_HARDWARE
7752 if (thread != NULL) {
7753#endif
7754 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7755 // notify client processes of the new output creation
7756 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7757#ifdef QCOM_HARDWARE
7758 }
7759 else {
7760 *pLatencyMs = 0;
7761 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7762 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7763 *pLatencyMs = desc->stream->get_latency(desc->stream);
7764 }
7765 }
7766#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007767 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007768 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007769 ALOGI("Using module %d has the primary audio interface", module);
7770 mPrimaryHardwareDev = outHwDev;
7771
7772 AutoMutex lock(mHardwareLock);
7773 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007774 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007775 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007777 return id;
7778 }
7779
7780 return 0;
7781}
7782
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007783audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7784 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785{
7786 Mutex::Autolock _l(mLock);
7787 MixerThread *thread1 = checkMixerThread_l(output1);
7788 MixerThread *thread2 = checkMixerThread_l(output2);
7789
7790 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007791 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 return 0;
7793 }
7794
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007795 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7797 thread->addOutputTrack(thread2);
7798 mPlaybackThreads.add(id, thread);
7799 // notify client processes of the new output creation
7800 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7801 return id;
7802}
7803
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007804status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007805{
Glenn Kastend96c5722012-04-25 13:44:49 -07007806 return closeOutput_nonvirtual(output);
7807}
7808
7809status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7810{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 // keep strong reference on the playback thread so that
7812 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007813#ifdef QCOM_HARDWARE
7814 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7815 if (desc) {
7816 ALOGV("Closing DirectTrack output %d", output);
7817 desc->mActive = false;
7818 desc->stream->common.standby(&desc->stream->common);
7819 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7820 desc->trackRefPtr = NULL;
7821 mDirectAudioTracks.removeItem(output);
7822 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7823 delete desc;
7824 return NO_ERROR;
7825 }
7826#endif
7827
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007828 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 {
7830 Mutex::Autolock _l(mLock);
7831 thread = checkPlaybackThread_l(output);
7832 if (thread == NULL) {
7833 return BAD_VALUE;
7834 }
7835
Steve Block3856b092011-10-20 11:56:00 +01007836 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007838 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007840 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7842 dupThread->removeOutputTrack((MixerThread *)thread.get());
7843 }
7844 }
7845 }
Glenn Kastena1117922012-01-26 10:53:32 -08007846 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847 mPlaybackThreads.removeItem(output);
Dorian Snyderf32d5702013-03-01 14:25:46 -08007848#ifdef QCOM_HARDWARE
7849 if (mA2DPHandle == output)
7850 {
7851 mA2DPHandle = -1;
7852 ALOGV("A2DP OutputClosed Notifying Client");
7853 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
7854 }
7855#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 }
7857 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007858 // The thread entity (active unit of execution) is no longer running here,
7859 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007861 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007862 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007863 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007864 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007865 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007866 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007867 }
7868 return NO_ERROR;
7869}
7870
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007871status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872{
7873 Mutex::Autolock _l(mLock);
7874 PlaybackThread *thread = checkPlaybackThread_l(output);
7875
7876 if (thread == NULL) {
7877 return BAD_VALUE;
7878 }
7879
Steve Block3856b092011-10-20 11:56:00 +01007880 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 thread->suspend();
7882
7883 return NO_ERROR;
7884}
7885
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007886status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887{
7888 Mutex::Autolock _l(mLock);
7889 PlaybackThread *thread = checkPlaybackThread_l(output);
7890
7891 if (thread == NULL) {
7892 return BAD_VALUE;
7893 }
7894
Steve Block3856b092011-10-20 11:56:00 +01007895 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896
7897 thread->restore();
7898
7899 return NO_ERROR;
7900}
7901
Eric Laurenta4c5a552012-03-29 10:12:40 -07007902audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7903 audio_devices_t *pDevices,
7904 uint32_t *pSamplingRate,
7905 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007906 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907{
7908 status_t status;
7909 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007910 struct audio_config config = {
7911 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7912 channel_mask: pChannelMask ? *pChannelMask : 0,
7913 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7914 };
7915 uint32_t reqSamplingRate = config.sample_rate;
7916 audio_format_t reqFormat = config.format;
7917 audio_channel_mask_t reqChannels = config.channel_mask;
7918 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007919 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007920
7921 if (pDevices == NULL || *pDevices == 0) {
7922 return 0;
7923 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007924
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925 Mutex::Autolock _l(mLock);
7926
Eric Laurenta4c5a552012-03-29 10:12:40 -07007927 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007928 if (inHwDev == NULL)
7929 return 0;
7930
John Grossmanee578c02012-07-23 17:05:46 -07007931 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007932 audio_io_handle_t id = nextUniqueId();
7933
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007934#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007935 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007936 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007937#else
7938 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7939 (int *)&config.format,
7940 &config.channel_mask,
7941 &config.sample_rate, (audio_in_acoustics_t)0,
7942 &inStream);
7943#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007944 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007945 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007946 config.sample_rate,
7947 config.format,
7948 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 status);
7950
7951 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7952 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7953 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007954 if (status == BAD_VALUE &&
7955 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7956 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007957 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007958 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007959 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007960#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007961 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007962#else
7963 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7964 (int *)&config.format,
7965 &config.channel_mask,
7966 &config.sample_rate, (audio_in_acoustics_t)0,
7967 &inStream);
7968#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 }
7970
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007971 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007972 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7973
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007974 // Start record thread
7975 // RecorThread require both input and output device indication to forward to audio
7976 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007977 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007978 thread = new RecordThread(this,
7979 input,
7980 reqSamplingRate,
7981 reqChannels,
7982 id,
7983 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007985 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007986 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007987 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007988 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007989
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 // notify client processes of the new input creation
7991 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7992 return id;
7993 }
7994
7995 return 0;
7996}
7997
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007998status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999{
Glenn Kastend96c5722012-04-25 13:44:49 -07008000 return closeInput_nonvirtual(input);
8001}
8002
8003status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
8004{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 // keep strong reference on the record thread so that
8006 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008007 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008008 {
8009 Mutex::Autolock _l(mLock);
8010 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07008011 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012 return BAD_VALUE;
8013 }
8014
Steve Block3856b092011-10-20 11:56:00 +01008015 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08008016 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017 mRecordThreads.removeItem(input);
8018 }
8019 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08008020 // The thread entity (active unit of execution) is no longer running here,
8021 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008023 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08008024 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008025 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07008026 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07008027 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008028
8029 return NO_ERROR;
8030}
8031
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008032status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008033{
8034 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008035 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036
8037 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8038 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07008039 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07008040 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08008041#ifdef QCOM_HARDWARE
8042 if ( mA2DPHandle == output ) {
8043 ALOGV("A2DP Activated and hence notifying the client");
8044 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &output);
8045 }
8046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047
8048 return NO_ERROR;
8049}
8050
8051
8052int AudioFlinger::newAudioSessionId()
8053{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008054 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055}
8056
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008057void AudioFlinger::acquireAudioSessionId(int audioSession)
8058{
8059 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008060 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008061 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008062 size_t num = mAudioSessionRefs.size();
8063 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008064 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008065 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8066 ref->mCnt++;
8067 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008068 return;
8069 }
8070 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08008071 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
8072 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008073}
8074
8075void AudioFlinger::releaseAudioSessionId(int audioSession)
8076{
8077 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008078 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008079 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008080 size_t num = mAudioSessionRefs.size();
8081 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008082 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008083 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8084 ref->mCnt--;
8085 ALOGV(" decremented refcount to %d", ref->mCnt);
8086 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008087 mAudioSessionRefs.removeAt(i);
8088 delete ref;
8089 purgeStaleEffects_l();
8090 }
8091 return;
8092 }
8093 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008094 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008095}
8096
8097void AudioFlinger::purgeStaleEffects_l() {
8098
Steve Block3856b092011-10-20 11:56:00 +01008099 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008100
8101 Vector< sp<EffectChain> > chains;
8102
8103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8104 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8105 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8106 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008107 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8108 chains.push(ec);
8109 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008110 }
8111 }
8112 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8113 sp<RecordThread> t = mRecordThreads.valueAt(i);
8114 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8115 sp<EffectChain> ec = t->mEffectChains[j];
8116 chains.push(ec);
8117 }
8118 }
8119
8120 for (size_t i = 0; i < chains.size(); i++) {
8121 sp<EffectChain> ec = chains[i];
8122 int sessionid = ec->sessionId();
8123 sp<ThreadBase> t = ec->mThread.promote();
8124 if (t == 0) {
8125 continue;
8126 }
8127 size_t numsessionrefs = mAudioSessionRefs.size();
8128 bool found = false;
8129 for (size_t k = 0; k < numsessionrefs; k++) {
8130 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008131 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008132 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008133 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008134 found = true;
8135 break;
8136 }
8137 }
8138 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008139 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008140 // remove all effects from the chain
8141 while (ec->mEffects.size()) {
8142 sp<EffectModule> effect = ec->mEffects[0];
8143 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008144 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008145 if (effect->purgeHandles()) {
8146 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008147 }
8148 AudioSystem::unregisterEffect(effect->id());
8149 }
8150 }
8151 }
8152 return;
8153}
8154
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008156AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157{
Glenn Kastena1117922012-01-26 10:53:32 -08008158 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159}
8160
8161// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008162AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163{
8164 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008165 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008166}
8167
8168// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008169AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008170{
Glenn Kastena1117922012-01-26 10:53:32 -08008171 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172}
8173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008174uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008175{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008176 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177}
8178
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008179AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008180{
8181 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8182 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008183 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008184 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008185 return thread;
8186 }
8187 }
8188 return NULL;
8189}
8190
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008191audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008192{
8193 PlaybackThread *thread = primaryPlaybackThread_l();
8194
8195 if (thread == NULL) {
8196 return 0;
8197 }
8198
Eric Laurentf1c04f92012-08-28 14:26:53 -07008199 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008200}
8201
Eric Laurenta011e352012-03-29 15:51:43 -07008202sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8203 int triggerSession,
8204 int listenerSession,
8205 sync_event_callback_t callBack,
8206 void *cookie)
8207{
8208 Mutex::Autolock _l(mLock);
8209
8210 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8211 status_t playStatus = NAME_NOT_FOUND;
8212 status_t recStatus = NAME_NOT_FOUND;
8213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8214 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8215 if (playStatus == NO_ERROR) {
8216 return event;
8217 }
8218 }
8219 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8220 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8221 if (recStatus == NO_ERROR) {
8222 return event;
8223 }
8224 }
8225 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8226 mPendingSyncEvents.add(event);
8227 } else {
8228 ALOGV("createSyncEvent() invalid event %d", event->type());
8229 event.clear();
8230 }
8231 return event;
8232}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008233
Mathias Agopian65ab4712010-07-14 17:59:35 -07008234// ----------------------------------------------------------------------------
8235// Effect management
8236// ----------------------------------------------------------------------------
8237
8238
Glenn Kastenf587ba52012-01-26 16:25:10 -08008239status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008240{
8241 Mutex::Autolock _l(mLock);
8242 return EffectQueryNumberEffects(numEffects);
8243}
8244
Glenn Kastenf587ba52012-01-26 16:25:10 -08008245status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008246{
8247 Mutex::Autolock _l(mLock);
8248 return EffectQueryEffect(index, descriptor);
8249}
8250
Glenn Kasten5e92a782012-01-30 07:40:52 -08008251status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008252 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253{
8254 Mutex::Autolock _l(mLock);
8255 return EffectGetDescriptor(pUuid, descriptor);
8256}
8257
8258
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8260 effect_descriptor_t *pDesc,
8261 const sp<IEffectClient>& effectClient,
8262 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008263 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 int sessionId,
8265 status_t *status,
8266 int *id,
8267 int *enabled)
8268{
8269 status_t lStatus = NO_ERROR;
8270 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008273 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008274 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008275
8276 if (pDesc == NULL) {
8277 lStatus = BAD_VALUE;
8278 goto Exit;
8279 }
8280
Eric Laurent84e9a102010-09-23 16:10:16 -07008281 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008282 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008283 lStatus = PERMISSION_DENIED;
8284 goto Exit;
8285 }
8286
Dima Zavinfce7a472011-04-19 22:30:36 -07008287 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008288 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008289 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008290 lStatus = PERMISSION_DENIED;
8291 goto Exit;
8292 }
8293
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008294 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008295 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008296 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008297 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008298 lStatus = BAD_VALUE;
8299 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008300 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008301 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008302 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008303 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008304 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008305 }
8306 }
8307
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 {
8309 Mutex::Autolock _l(mLock);
8310
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311
8312 if (!EffectIsNullUuid(&pDesc->uuid)) {
8313 // if uuid is specified, request effect descriptor
8314 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8315 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008316 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008317 goto Exit;
8318 }
8319 } else {
8320 // if uuid is not specified, look for an available implementation
8321 // of the required type in effect factory
8322 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008323 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008324 lStatus = BAD_VALUE;
8325 goto Exit;
8326 }
8327 uint32_t numEffects = 0;
8328 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008329 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 bool found = false;
8331
8332 lStatus = EffectQueryNumberEffects(&numEffects);
8333 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008334 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335 goto Exit;
8336 }
8337 for (uint32_t i = 0; i < numEffects; i++) {
8338 lStatus = EffectQueryEffect(i, &desc);
8339 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008340 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341 continue;
8342 }
8343 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8344 // If matching type found save effect descriptor. If the session is
8345 // 0 and the effect is not auxiliary, continue enumeration in case
8346 // an auxiliary version of this effect type is available
8347 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008348 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008349 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8351 break;
8352 }
8353 }
8354 }
8355 if (!found) {
8356 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008357 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008358 goto Exit;
8359 }
8360 // For same effect type, chose auxiliary version over insert version if
8361 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008362 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008363 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008364 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 }
8366 }
8367
8368 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008369 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008370 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8371 lStatus = INVALID_OPERATION;
8372 goto Exit;
8373 }
8374
Eric Laurent59255e42011-07-27 19:49:51 -07008375 // check recording permission for visualizer
8376 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8377 !recordingAllowed()) {
8378 lStatus = PERMISSION_DENIED;
8379 goto Exit;
8380 }
8381
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008383 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384
8385 // If output is not specified try to find a matching audio session ID in one of the
8386 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008387 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8388 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008389 // Note: io is never 0 when creating an effect on an input
8390 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008391 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8393 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008394 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008395 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008397 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008398 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008399 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8400 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8401 io = mRecordThreads.keyAt(i);
8402 break;
8403 }
8404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008405 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008406 // If no output thread contains the requested session ID, default to
8407 // first output. The effect chain will be moved to the correct output
8408 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008409 if (io == 0 && mPlaybackThreads.size()) {
8410 io = mPlaybackThreads.keyAt(0);
8411 }
Steve Block3856b092011-10-20 11:56:00 +01008412 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008413 }
8414 ThreadBase *thread = checkRecordThread_l(io);
8415 if (thread == NULL) {
8416 thread = checkPlaybackThread_l(io);
8417 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008418 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008419 lStatus = BAD_VALUE;
8420 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008422 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008423
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008424 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008426 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008427 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8428 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429 if (handle != 0 && id != NULL) {
8430 *id = handle->id();
8431 }
8432 }
8433
8434Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008435 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 *status = lStatus;
8437 }
8438 return handle;
8439}
8440
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008441status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8442 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008443{
Steve Block3856b092011-10-20 11:56:00 +01008444 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008445 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008446 Mutex::Autolock _l(mLock);
8447 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008448 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008449 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008450 }
Eric Laurentde070132010-07-13 04:45:46 -07008451 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8452 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008453 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008454 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 }
Eric Laurentde070132010-07-13 04:45:46 -07008456 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8457 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008458 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008459 return BAD_VALUE;
8460 }
8461
8462 Mutex::Autolock _dl(dstThread->mLock);
8463 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008464 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008465
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466 return NO_ERROR;
8467}
8468
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008469// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008470status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008471 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008472 AudioFlinger::PlaybackThread *dstThread,
8473 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008474{
Steve Block3856b092011-10-20 11:56:00 +01008475 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008476 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008477
Eric Laurent59255e42011-07-27 19:49:51 -07008478 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008479 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008480 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008481 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008482 return INVALID_OPERATION;
8483 }
8484
Eric Laurent39e94f82010-07-28 01:32:47 -07008485 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008486 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008487 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008488 // removed.
8489 srcThread->removeEffectChain_l(chain);
8490
8491 // transfer all effects one by one so that new effect chain is created on new thread with
8492 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008493 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008494 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008495 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008496 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8497 while (effect != 0) {
8498 srcThread->removeEffect_l(effect);
8499 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008500 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8501 if (effect->state() == EffectModule::ACTIVE ||
8502 effect->state() == EffectModule::STOPPING) {
8503 effect->start();
8504 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008505 // if the move request is not received from audio policy manager, the effect must be
8506 // re-registered with the new strategy and output
8507 if (dstChain == 0) {
8508 dstChain = effect->chain().promote();
8509 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008510 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008511 srcThread->addEffect_l(effect);
8512 return NO_INIT;
8513 }
8514 strategy = dstChain->strategy();
8515 }
8516 if (reRegister) {
8517 AudioSystem::unregisterEffect(effect->id());
8518 AudioSystem::registerEffect(&effect->desc(),
8519 dstOutput,
8520 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008521 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008522 effect->id());
8523 }
Eric Laurentde070132010-07-13 04:45:46 -07008524 effect = chain->getEffectFromId_l(0);
8525 }
8526
8527 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528}
8529
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008530
Mathias Agopian65ab4712010-07-14 17:59:35 -07008531// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008532sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533 const sp<AudioFlinger::Client>& client,
8534 const sp<IEffectClient>& effectClient,
8535 int32_t priority,
8536 int sessionId,
8537 effect_descriptor_t *desc,
8538 int *enabled,
8539 status_t *status
8540 )
8541{
8542 sp<EffectModule> effect;
8543 sp<EffectHandle> handle;
8544 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008545 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008546 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008547 bool effectCreated = false;
8548 bool effectRegistered = false;
8549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008550 lStatus = initCheck();
8551 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008552 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008553 goto Exit;
8554 }
8555
8556 // Do not allow effects with session ID 0 on direct output or duplicating threads
8557 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008558 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008559 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008560 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008561 lStatus = BAD_VALUE;
8562 goto Exit;
8563 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008564 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008565 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008566 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008567 desc->name, desc->flags, mType);
8568 lStatus = BAD_VALUE;
8569 goto Exit;
8570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571
Steve Block3856b092011-10-20 11:56:00 +01008572 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573
8574 { // scope for mLock
8575 Mutex::Autolock _l(mLock);
8576
8577 // check for existing effect chain with the requested audio session
8578 chain = getEffectChain_l(sessionId);
8579 if (chain == 0) {
8580 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008581 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582 chain = new EffectChain(this, sessionId);
8583 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008584 chain->setStrategy(getStrategyForSession_l(sessionId));
8585 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008586#ifdef QCOM_HARDWARE
8587 if(sessionId == mAudioFlinger->mLPASessionId) {
8588 // Clear reference to previous effect chain if any
8589 if(mAudioFlinger->mLPAEffectChain.get()) {
8590 mAudioFlinger->mLPAEffectChain.clear();
8591 }
8592 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8593 mAudioFlinger->mLPAEffectChain = chain;
8594 chain->setLPAFlag(true);
8595 // For LPA, the volume will be applied in DSP. No need for volume
8596 // control in the Effect chain, so setting it to unity.
8597 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8598 chain->setVolume_l(&volume,&volume);
8599 }
8600#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008602 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 }
8604
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008605 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606
8607 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008608 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008609 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008610 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008611 if (lStatus != NO_ERROR) {
8612 goto Exit;
8613 }
8614 effectRegistered = true;
8615 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008616 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008617 lStatus = effect->status();
8618 if (lStatus != NO_ERROR) {
8619 goto Exit;
8620 }
Eric Laurentcab11242010-07-15 12:50:15 -07008621 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008622 if (lStatus != NO_ERROR) {
8623 goto Exit;
8624 }
8625 effectCreated = true;
8626
Eric Laurentf1c04f92012-08-28 14:26:53 -07008627 effect->setDevice(mOutDevice);
8628 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008629 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008630 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008631#ifdef QCOM_HARDWARE
8632 if(chain == mAudioFlinger->mLPAEffectChain) {
8633 effect->setLPAFlag(true);
8634 }
8635#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008636 }
8637 // create effect handle and connect it to effect module
8638 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008639 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008640 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008641 *enabled = (int)effect->isEnabled();
8642 }
8643 }
8644
8645Exit:
8646 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008647 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008648 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008649 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008650 }
8651 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008652 AudioSystem::unregisterEffect(effect->id());
8653 }
8654 if (chainCreated) {
8655 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008656 }
8657 handle.clear();
8658 }
8659
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008660 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008661 *status = lStatus;
8662 }
8663 return handle;
8664}
8665
Eric Laurent717e1282012-06-29 16:36:52 -07008666sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8667{
8668 Mutex::Autolock _l(mLock);
8669 return getEffect_l(sessionId, effectId);
8670}
8671
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008672sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8673{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008674 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008675 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008676}
8677
Eric Laurentde070132010-07-13 04:45:46 -07008678// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8679// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008680status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008681{
8682 // check for existing effect chain with the requested audio session
8683 int sessionId = effect->sessionId();
8684 sp<EffectChain> chain = getEffectChain_l(sessionId);
8685 bool chainCreated = false;
8686
8687 if (chain == 0) {
8688 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008689 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008690 chain = new EffectChain(this, sessionId);
8691 addEffectChain_l(chain);
8692 chain->setStrategy(getStrategyForSession_l(sessionId));
8693 chainCreated = true;
8694 }
Steve Block3856b092011-10-20 11:56:00 +01008695 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008696
8697 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008698 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008699 this, effect->desc().name, chain.get());
8700 return BAD_VALUE;
8701 }
8702
8703 status_t status = chain->addEffect_l(effect);
8704 if (status != NO_ERROR) {
8705 if (chainCreated) {
8706 removeEffectChain_l(chain);
8707 }
8708 return status;
8709 }
8710
Eric Laurentf1c04f92012-08-28 14:26:53 -07008711 effect->setDevice(mOutDevice);
8712 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008713 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008714 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008715 return NO_ERROR;
8716}
8717
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008718void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008719
Steve Block3856b092011-10-20 11:56:00 +01008720 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008722 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8723 detachAuxEffect_l(effect->id());
8724 }
8725
8726 sp<EffectChain> chain = effect->chain().promote();
8727 if (chain != 0) {
8728 // remove effect chain if removing last effect
8729 if (chain->removeEffect_l(effect) == 0) {
8730 removeEffectChain_l(chain);
8731 }
8732 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008733 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008734 }
8735}
8736
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008737void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008738 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008739{
8740 effectChains = mEffectChains;
8741 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008742#ifdef QCOM_HARDWARE
8743 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8744#endif
8745 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008746 }
8747}
8748
8749void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008750 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008751{
8752 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008753#ifdef QCOM_HARDWARE
8754 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8755#endif
8756 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008757 }
8758}
8759
8760sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8761{
8762 Mutex::Autolock _l(mLock);
8763 return getEffectChain_l(sessionId);
8764}
8765
Glenn Kasten106e8a42012-08-02 13:37:12 -07008766sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008767{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008768 size_t size = mEffectChains.size();
8769 for (size_t i = 0; i < size; i++) {
8770 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008771 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008772 }
8773 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008774 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008775}
8776
Glenn Kastenf78aee72012-01-04 11:00:47 -08008777void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008778{
8779 Mutex::Autolock _l(mLock);
8780 size_t size = mEffectChains.size();
8781 for (size_t i = 0; i < size; i++) {
8782 mEffectChains[i]->setMode_l(mode);
8783 }
8784}
8785
8786void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008787 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008788 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008789
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008791 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008792 // delete the effect module if removing last handle on it
8793 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008794 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008795 removeEffect_l(effect);
8796 AudioSystem::unregisterEffect(effect->id());
8797 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798 }
8799}
8800
8801status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8802{
8803 int session = chain->sessionId();
8804 int16_t *buffer = mMixBuffer;
8805 bool ownsBuffer = false;
8806
Steve Block3856b092011-10-20 11:56:00 +01008807 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808 if (session > 0) {
8809 // Only one effect chain can be present in direct output thread and it uses
8810 // the mix buffer as input
8811 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008812 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 buffer = new int16_t[numSamples];
8814 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008815 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816 ownsBuffer = true;
8817 }
8818
8819 // Attach all tracks with same session ID to this chain.
8820 for (size_t i = 0; i < mTracks.size(); ++i) {
8821 sp<Track> track = mTracks[i];
8822 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008823 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008825 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 }
8827 }
8828
8829 // indicate all active tracks in the chain
8830 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8831 sp<Track> track = mActiveTracks[i].promote();
8832 if (track == 0) continue;
8833 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008834 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008835 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836 }
8837 }
8838 }
8839
8840 chain->setInBuffer(buffer, ownsBuffer);
8841 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008842 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008843 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008844 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8845 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008847 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8848 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008849 // Effect chain for other sessions are inserted at beginning of effect
8850 // chains list to be processed before output mix effects. Relative order between other
8851 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852 size_t size = mEffectChains.size();
8853 size_t i = 0;
8854 for (i = 0; i < size; i++) {
8855 if (mEffectChains[i]->sessionId() < session) break;
8856 }
8857 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008858 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859
8860 return NO_ERROR;
8861}
8862
8863size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8864{
8865 int session = chain->sessionId();
8866
Steve Block3856b092011-10-20 11:56:00 +01008867 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868
8869 for (size_t i = 0; i < mEffectChains.size(); i++) {
8870 if (chain == mEffectChains[i]) {
8871 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008872 // detach all active tracks from the chain
8873 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8874 sp<Track> track = mActiveTracks[i].promote();
8875 if (track == 0) continue;
8876 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008877 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008878 chain.get(), session);
8879 chain->decActiveTrackCnt();
8880 }
8881 }
8882
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 // detach all tracks with same session ID from this chain
8884 for (size_t i = 0; i < mTracks.size(); ++i) {
8885 sp<Track> track = mTracks[i];
8886 if (session == track->sessionId()) {
8887 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008888 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008889 }
8890 }
Eric Laurentde070132010-07-13 04:45:46 -07008891 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 }
8893 }
8894 return mEffectChains.size();
8895}
8896
Eric Laurentde070132010-07-13 04:45:46 -07008897status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8898 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899{
8900 Mutex::Autolock _l(mLock);
8901 return attachAuxEffect_l(track, EffectId);
8902}
8903
Eric Laurentde070132010-07-13 04:45:46 -07008904status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8905 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008906{
8907 status_t status = NO_ERROR;
8908
8909 if (EffectId == 0) {
8910 track->setAuxBuffer(0, NULL);
8911 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008912 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8913 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 if (effect != 0) {
8915 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8916 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8917 } else {
8918 status = INVALID_OPERATION;
8919 }
8920 } else {
8921 status = BAD_VALUE;
8922 }
8923 }
8924 return status;
8925}
8926
8927void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8928{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008929 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930 sp<Track> track = mTracks[i];
8931 if (track->auxEffectId() == effectId) {
8932 attachAuxEffect_l(track, 0);
8933 }
8934 }
8935}
8936
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008937status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8938{
8939 // only one chain per input thread
8940 if (mEffectChains.size() != 0) {
8941 return INVALID_OPERATION;
8942 }
Steve Block3856b092011-10-20 11:56:00 +01008943 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008944
8945 chain->setInBuffer(NULL);
8946 chain->setOutBuffer(NULL);
8947
Eric Laurent59255e42011-07-27 19:49:51 -07008948 checkSuspendOnAddEffectChain_l(chain);
8949
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008950 mEffectChains.add(chain);
8951
8952 return NO_ERROR;
8953}
8954
8955size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8956{
Steve Block3856b092011-10-20 11:56:00 +01008957 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008958 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008959 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8960 chain.get(), mEffectChains.size(), this);
8961 if (mEffectChains.size() == 1) {
8962 mEffectChains.removeAt(0);
8963 }
8964 return 0;
8965}
8966
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967// ----------------------------------------------------------------------------
8968// EffectModule implementation
8969// ----------------------------------------------------------------------------
8970
8971#undef LOG_TAG
8972#define LOG_TAG "AudioFlinger::EffectModule"
8973
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008974AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 const wp<AudioFlinger::EffectChain>& chain,
8976 effect_descriptor_t *desc,
8977 int id,
8978 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008979 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8980 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008981 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008982 // mConfig is set by configure() and not used before then
8983 mEffectInterface(NULL),
8984 mStatus(NO_INIT), mState(IDLE),
8985 // mMaxDisableWaitCnt is set by configure() and not used before then
8986 // mDisableWaitCnt is set by process() and updateState() and not used before then
8987 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08008988#ifdef QCOM_HARDWARE
8989 ,mIsForLPA(false)
8990#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991{
Steve Block3856b092011-10-20 11:56:00 +01008992 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994
8995 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008996 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997
8998 if (mStatus != NO_ERROR) {
8999 return;
9000 }
9001 lStatus = init();
9002 if (lStatus < 0) {
9003 mStatus = lStatus;
9004 goto Error;
9005 }
9006
Steve Block3856b092011-10-20 11:56:00 +01009007 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 return;
9009Error:
9010 EffectRelease(mEffectInterface);
9011 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01009012 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013}
9014
9015AudioFlinger::EffectModule::~EffectModule()
9016{
Steve Block3856b092011-10-20 11:56:00 +01009017 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009019 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9020 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
9021 sp<ThreadBase> thread = mThread.promote();
9022 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009023 audio_stream_t *stream = thread->stream();
9024 if (stream != NULL) {
9025 stream->remove_audio_effect(stream, mEffectInterface);
9026 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009027 }
9028 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029 // release effect engine
9030 EffectRelease(mEffectInterface);
9031 }
9032}
9033
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009034status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035{
9036 status_t status;
9037
9038 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009039 int priority = handle->priority();
9040 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009041 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042 size_t i;
9043 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009044 EffectHandle *h = mHandles[i];
9045 if (h == NULL || h->destroyed_l()) continue;
9046 // first non destroyed handle is considered in control
9047 if (controlHandle == NULL)
9048 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009049 if (h->priority() <= priority) break;
9050 }
9051 // if inserted in first place, move effect control from previous owner to this handle
9052 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07009053 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009054 if (controlHandle != NULL) {
9055 enabled = controlHandle->enabled();
9056 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009057 }
Eric Laurent59255e42011-07-27 19:49:51 -07009058 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009059 status = NO_ERROR;
9060 } else {
9061 status = ALREADY_EXISTS;
9062 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009063 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009064 mHandles.insertAt(handle, i);
9065 return status;
9066}
9067
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009068size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009069{
9070 Mutex::Autolock _l(mLock);
9071 size_t size = mHandles.size();
9072 size_t i;
9073 for (i = 0; i < size; i++) {
9074 if (mHandles[i] == handle) break;
9075 }
9076 if (i == size) {
9077 return size;
9078 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009079 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07009080
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009082 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009083 if (i == 0) {
9084 EffectHandle *h = controlHandle_l();
9085 if (h != NULL) {
9086 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009087 }
9088 }
9089
Eric Laurentec437d82011-07-26 20:54:46 -07009090 // Prevent calls to process() and other functions on effect interface from now on.
9091 // The effect engine will be released by the destructor when the last strong reference on
9092 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009093 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009094 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009095 }
9096
Eric Laurente65c8912012-07-20 15:57:23 -07009097 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009098}
9099
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009100// must be called with EffectModule::mLock held
9101AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009102{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009103 // the first valid handle in the list has control over the module
9104 for (size_t i = 0; i < mHandles.size(); i++) {
9105 EffectHandle *h = mHandles[i];
9106 if (h != NULL && !h->destroyed_l()) {
9107 return h;
9108 }
9109 }
9110
9111 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009112}
9113
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009114size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115{
vivek mehta2192bc92012-12-04 11:46:08 -08009116#ifdef QCOM_HARDWARE
9117 setEnabled(false);
9118#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009119 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120 // keep a strong reference on this EffectModule to avoid calling the
9121 // destructor before we exit
9122 sp<EffectModule> keep(this);
9123 {
9124 sp<ThreadBase> thread = mThread.promote();
9125 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009126 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127 }
9128 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009129 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009130}
9131
9132void AudioFlinger::EffectModule::updateState() {
9133 Mutex::Autolock _l(mLock);
9134
9135 switch (mState) {
9136 case RESTART:
9137 reset_l();
9138 // FALL THROUGH
9139
9140 case STARTING:
9141 // clear auxiliary effect input buffer for next accumulation
9142 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9143 memset(mConfig.inputCfg.buffer.raw,
9144 0,
9145 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9146 }
9147 start_l();
9148 mState = ACTIVE;
9149 break;
9150 case STOPPING:
9151 stop_l();
9152 mDisableWaitCnt = mMaxDisableWaitCnt;
9153 mState = STOPPED;
9154 break;
9155 case STOPPED:
9156 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9157 // turn off sequence.
9158 if (--mDisableWaitCnt == 0) {
9159 reset_l();
9160 mState = IDLE;
9161 }
9162 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009163 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164 break;
9165 }
9166}
9167
9168void AudioFlinger::EffectModule::process()
9169{
9170 Mutex::Autolock _l(mLock);
9171
Eric Laurentec437d82011-07-26 20:54:46 -07009172 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009173 mConfig.inputCfg.buffer.raw == NULL ||
9174 mConfig.outputCfg.buffer.raw == NULL) {
9175 return;
9176 }
9177
Eric Laurent8f45bd72010-08-31 13:50:07 -07009178 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9180 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009181 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009182 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009183 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009184 }
9185
9186 // do the actual processing in the effect engine
9187 int ret = (*mEffectInterface)->process(mEffectInterface,
9188 &mConfig.inputCfg.buffer,
9189 &mConfig.outputCfg.buffer);
9190
9191 // force transition to IDLE state when engine is ready
9192 if (mState == STOPPED && ret == -ENODATA) {
9193 mDisableWaitCnt = 1;
9194 }
9195
9196 // clear auxiliary effect input buffer for next accumulation
9197 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009198 memset(mConfig.inputCfg.buffer.raw, 0,
9199 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009200 }
9201 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009202 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9203 // If an insert effect is idle and input buffer is different from output buffer,
9204 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009205 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009206 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009207 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9208 int16_t *in = mConfig.inputCfg.buffer.s16;
9209 int16_t *out = mConfig.outputCfg.buffer.s16;
9210 for (size_t i = 0; i < frameCnt; i++) {
9211 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213 }
9214 }
9215}
9216
9217void AudioFlinger::EffectModule::reset_l()
9218{
9219 if (mEffectInterface == NULL) {
9220 return;
9221 }
9222 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9223}
9224
vivek mehta2192bc92012-12-04 11:46:08 -08009225#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226status_t AudioFlinger::EffectModule::configure()
9227{
vivek mehta2192bc92012-12-04 11:46:08 -08009228#else
9229status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9230{
9231 uint32_t channels;
9232
9233 // Acquire lock here to make sure that any other thread does not delete
9234 // the effect handle and release the effect module.
9235 Mutex::Autolock _l(mLock);
9236#endif
9237
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238 if (mEffectInterface == NULL) {
9239 return NO_INIT;
9240 }
9241
9242 sp<ThreadBase> thread = mThread.promote();
9243 if (thread == 0) {
9244 return DEAD_OBJECT;
9245 }
9246
9247 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009248 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009249#ifdef QCOM_HARDWARE
9250 mIsForLPA = isForLPA;
9251 if(isForLPA) {
9252 if (channelCount == 1) {
9253 channels = AUDIO_CHANNEL_OUT_MONO;
9254 } else {
9255 channels = AUDIO_CHANNEL_OUT_STEREO;
9256 }
9257 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9258 } else {
9259 if (thread->channelCount() == 1) {
9260 channels = AUDIO_CHANNEL_OUT_MONO;
9261 } else {
9262 channels = AUDIO_CHANNEL_OUT_STEREO;
9263 }
9264 }
9265#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009266
9267 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009268 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009269 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009270 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009271 }
Glenn Kasten254af182012-07-03 14:59:05 -07009272 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009273 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9274 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009275#ifdef QCOM_HARDWARE
9276 if(isForLPA){
9277 mConfig.inputCfg.samplingRate = sampleRate;
9278 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9279 } else
9280#endif
9281 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9283 mConfig.inputCfg.bufferProvider.cookie = NULL;
9284 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9285 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9286 mConfig.outputCfg.bufferProvider.cookie = NULL;
9287 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9288 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9289 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9290 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009291 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009292 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009293 // - in other sessions:
9294 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9295 // other effect: overwrites output buffer: input buffer == output buffer
9296 // Auxiliary effect:
9297 // accumulates in output buffer: input buffer != output buffer
9298 // Therefore: accumulate <=> input buffer != output buffer
9299 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9300 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9301 } else {
9302 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9303 }
9304 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9305 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009306#ifdef QCOM_HARDWARE
9307 if(isForLPA) {
9308 mConfig.inputCfg.buffer.frameCount = frameCount;
9309 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9310 } else
9311#endif
9312 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009313 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9314
Steve Block3856b092011-10-20 11:56:00 +01009315 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009316 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9317
Mathias Agopian65ab4712010-07-14 17:59:35 -07009318 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009319 uint32_t size = sizeof(int);
9320 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009321 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009322 sizeof(effect_config_t),
9323 &mConfig,
9324 &size,
9325 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009326 if (status == 0) {
9327 status = cmdStatus;
9328 }
9329
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009330 if (status == 0 &&
9331 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9332 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9333 effect_param_t *p = (effect_param_t *)buf32;
9334
9335 p->psize = sizeof(uint32_t);
9336 p->vsize = sizeof(uint32_t);
9337 size = sizeof(int);
9338 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9339
9340 uint32_t latency = 0;
9341 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9342 if (pbt != NULL) {
9343 latency = pbt->latency_l();
9344 }
9345
9346 *((int32_t *)p->data + 1)= latency;
9347 (*mEffectInterface)->command(mEffectInterface,
9348 EFFECT_CMD_SET_PARAM,
9349 sizeof(effect_param_t) + 8,
9350 &buf32,
9351 &size,
9352 &cmdStatus);
9353 }
9354
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9356 (1000 * mConfig.outputCfg.buffer.frameCount);
9357
9358 return status;
9359}
9360
9361status_t AudioFlinger::EffectModule::init()
9362{
9363 Mutex::Autolock _l(mLock);
9364 if (mEffectInterface == NULL) {
9365 return NO_INIT;
9366 }
9367 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009368 uint32_t size = sizeof(status_t);
9369 status_t status = (*mEffectInterface)->command(mEffectInterface,
9370 EFFECT_CMD_INIT,
9371 0,
9372 NULL,
9373 &size,
9374 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009375 if (status == 0) {
9376 status = cmdStatus;
9377 }
9378 return status;
9379}
9380
Eric Laurentec35a142011-10-05 17:42:25 -07009381status_t AudioFlinger::EffectModule::start()
9382{
9383 Mutex::Autolock _l(mLock);
9384 return start_l();
9385}
9386
Mathias Agopian65ab4712010-07-14 17:59:35 -07009387status_t AudioFlinger::EffectModule::start_l()
9388{
9389 if (mEffectInterface == NULL) {
9390 return NO_INIT;
9391 }
9392 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009393 uint32_t size = sizeof(status_t);
9394 status_t status = (*mEffectInterface)->command(mEffectInterface,
9395 EFFECT_CMD_ENABLE,
9396 0,
9397 NULL,
9398 &size,
9399 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009400 if (status == 0) {
9401 status = cmdStatus;
9402 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009403 if (status == 0 &&
9404 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9405 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9406 sp<ThreadBase> thread = mThread.promote();
9407 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009408 audio_stream_t *stream = thread->stream();
9409 if (stream != NULL) {
9410 stream->add_audio_effect(stream, mEffectInterface);
9411 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009412 }
9413 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009414 return status;
9415}
9416
Eric Laurentec437d82011-07-26 20:54:46 -07009417status_t AudioFlinger::EffectModule::stop()
9418{
9419 Mutex::Autolock _l(mLock);
9420 return stop_l();
9421}
9422
Mathias Agopian65ab4712010-07-14 17:59:35 -07009423status_t AudioFlinger::EffectModule::stop_l()
9424{
9425 if (mEffectInterface == NULL) {
9426 return NO_INIT;
9427 }
9428 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009429 uint32_t size = sizeof(status_t);
9430 status_t status = (*mEffectInterface)->command(mEffectInterface,
9431 EFFECT_CMD_DISABLE,
9432 0,
9433 NULL,
9434 &size,
9435 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009436 if (status == 0) {
9437 status = cmdStatus;
9438 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009439 if (status == 0 &&
9440 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9441 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9442 sp<ThreadBase> thread = mThread.promote();
9443 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009444 audio_stream_t *stream = thread->stream();
9445 if (stream != NULL) {
9446 stream->remove_audio_effect(stream, mEffectInterface);
9447 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009448 }
9449 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009450 return status;
9451}
9452
Eric Laurent25f43952010-07-28 05:40:18 -07009453status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9454 uint32_t cmdSize,
9455 void *pCmdData,
9456 uint32_t *replySize,
9457 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009458{
9459 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009460// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009461
Eric Laurentec437d82011-07-26 20:54:46 -07009462 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009463 return NO_INIT;
9464 }
Eric Laurent25f43952010-07-28 05:40:18 -07009465 status_t status = (*mEffectInterface)->command(mEffectInterface,
9466 cmdCode,
9467 cmdSize,
9468 pCmdData,
9469 replySize,
9470 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009471 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009472 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009473 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009474 EffectHandle *h = mHandles[i];
9475 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009476 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9477 }
9478 }
9479 }
9480 return status;
9481}
9482
9483status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9484{
9485 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009486 return setEnabled_l(enabled);
9487}
9488
9489// must be called with EffectModule::mLock held
9490status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9491{
vivek mehta2192bc92012-12-04 11:46:08 -08009492#ifdef QCOM_HARDWARE
9493 bool effectStateChanged = false;
9494#endif
Steve Block3856b092011-10-20 11:56:00 +01009495 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009496
9497 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009498#ifdef QCOM_HARDWARE
9499 effectStateChanged = true;
9500#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009501 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9502 if (enabled && status != NO_ERROR) {
9503 return status;
9504 }
9505
Mathias Agopian65ab4712010-07-14 17:59:35 -07009506 switch (mState) {
9507 // going from disabled to enabled
9508 case IDLE:
9509 mState = STARTING;
9510 break;
9511 case STOPPED:
9512 mState = RESTART;
9513 break;
9514 case STOPPING:
9515 mState = ACTIVE;
9516 break;
9517
9518 // going from enabled to disabled
9519 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009520 mState = STOPPED;
9521 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009522 case STARTING:
9523 mState = IDLE;
9524 break;
9525 case ACTIVE:
9526 mState = STOPPING;
9527 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009528 case DESTROYED:
9529 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009530 }
9531 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009532 EffectHandle *h = mHandles[i];
9533 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009534 h->setEnabled(enabled);
9535 }
9536 }
9537 }
vivek mehta2192bc92012-12-04 11:46:08 -08009538#ifdef QCOM_HARDWARE
9539 /*
9540 Send notification event to LPA Player when an effect for
9541 LPA output is enabled or disabled.
9542 */
9543 if (effectStateChanged && mIsForLPA) {
9544 sp<ThreadBase> thread = mThread.promote();
9545 thread->effectConfigChanged();
9546 }
9547#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009548 return NO_ERROR;
9549}
9550
Glenn Kastenc59c0042012-02-02 14:06:11 -08009551bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009552{
9553 switch (mState) {
9554 case RESTART:
9555 case STARTING:
9556 case ACTIVE:
9557 return true;
9558 case IDLE:
9559 case STOPPING:
9560 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009561 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009562 default:
9563 return false;
9564 }
9565}
9566
Glenn Kastenc59c0042012-02-02 14:06:11 -08009567bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009568{
9569 switch (mState) {
9570 case RESTART:
9571 case ACTIVE:
9572 case STOPPING:
9573 case STOPPED:
9574 return true;
9575 case IDLE:
9576 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009577 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009578 default:
9579 return false;
9580 }
9581}
9582
Mathias Agopian65ab4712010-07-14 17:59:35 -07009583status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9584{
9585 Mutex::Autolock _l(mLock);
9586 status_t status = NO_ERROR;
9587
9588 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9589 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009590 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009591 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9592 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009593 status_t cmdStatus;
9594 uint32_t volume[2];
9595 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009596 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009597 volume[0] = *left;
9598 volume[1] = *right;
9599 if (controller) {
9600 pVolume = volume;
9601 }
Eric Laurent25f43952010-07-28 05:40:18 -07009602 status = (*mEffectInterface)->command(mEffectInterface,
9603 EFFECT_CMD_SET_VOLUME,
9604 size,
9605 volume,
9606 &size,
9607 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009608 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9609 *left = volume[0];
9610 *right = volume[1];
9611 }
9612 }
9613 return status;
9614}
9615
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009616status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009617{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009618 if (device == AUDIO_DEVICE_NONE) {
9619 return NO_ERROR;
9620 }
9621
Mathias Agopian65ab4712010-07-14 17:59:35 -07009622 Mutex::Autolock _l(mLock);
9623 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009624 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009625 status_t cmdStatus;
9626 uint32_t size = sizeof(status_t);
9627 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9628 EFFECT_CMD_SET_INPUT_DEVICE;
9629 status = (*mEffectInterface)->command(mEffectInterface,
9630 cmd,
9631 sizeof(uint32_t),
9632 &device,
9633 &size,
9634 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009635 }
9636 return status;
9637}
9638
Glenn Kastenf78aee72012-01-04 11:00:47 -08009639status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009640{
9641 Mutex::Autolock _l(mLock);
9642 status_t status = NO_ERROR;
9643 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009644 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009645 uint32_t size = sizeof(status_t);
9646 status = (*mEffectInterface)->command(mEffectInterface,
9647 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009648 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009649 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009650 &size,
9651 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009652 if (status == NO_ERROR) {
9653 status = cmdStatus;
9654 }
9655 }
9656 return status;
9657}
9658
Eric Laurent57b2dd12012-08-31 17:44:06 -07009659status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9660{
9661 Mutex::Autolock _l(mLock);
9662 status_t status = NO_ERROR;
9663 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9664 uint32_t size = 0;
9665 status = (*mEffectInterface)->command(mEffectInterface,
9666 EFFECT_CMD_SET_AUDIO_SOURCE,
9667 sizeof(audio_source_t),
9668 &source,
9669 &size,
9670 NULL);
9671 }
9672 return status;
9673}
9674
Eric Laurent59255e42011-07-27 19:49:51 -07009675void AudioFlinger::EffectModule::setSuspended(bool suspended)
9676{
9677 Mutex::Autolock _l(mLock);
9678 mSuspended = suspended;
9679}
Glenn Kastena3a85482012-01-04 11:01:11 -08009680
9681bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009682{
9683 Mutex::Autolock _l(mLock);
9684 return mSuspended;
9685}
9686
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009687bool AudioFlinger::EffectModule::purgeHandles()
9688{
9689 bool enabled = false;
9690 Mutex::Autolock _l(mLock);
9691 for (size_t i = 0; i < mHandles.size(); i++) {
9692 EffectHandle *handle = mHandles[i];
9693 if (handle != NULL && !handle->destroyed_l()) {
9694 handle->effect().clear();
9695 if (handle->hasControl()) {
9696 enabled = handle->enabled();
9697 }
9698 }
9699 }
9700 return enabled;
9701}
9702
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009703void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009704{
9705 const size_t SIZE = 256;
9706 char buffer[SIZE];
9707 String8 result;
9708
9709 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9710 result.append(buffer);
9711
9712 bool locked = tryLock(mLock);
9713 // failed to lock - AudioFlinger is probably deadlocked
9714 if (!locked) {
9715 result.append("\t\tCould not lock Fx mutex:\n");
9716 }
9717
9718 result.append("\t\tSession Status State Engine:\n");
9719 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9720 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9721 result.append(buffer);
9722
9723 result.append("\t\tDescriptor:\n");
9724 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9725 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9726 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9727 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9728 result.append(buffer);
9729 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9730 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9731 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9732 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9733 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009734 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009735 mDescriptor.apiVersion,
9736 mDescriptor.flags);
9737 result.append(buffer);
9738 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9739 mDescriptor.name);
9740 result.append(buffer);
9741 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9742 mDescriptor.implementor);
9743 result.append(buffer);
9744
9745 result.append("\t\t- Input configuration:\n");
9746 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9747 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9748 (uint32_t)mConfig.inputCfg.buffer.raw,
9749 mConfig.inputCfg.buffer.frameCount,
9750 mConfig.inputCfg.samplingRate,
9751 mConfig.inputCfg.channels,
9752 mConfig.inputCfg.format);
9753 result.append(buffer);
9754
9755 result.append("\t\t- Output configuration:\n");
9756 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9757 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9758 (uint32_t)mConfig.outputCfg.buffer.raw,
9759 mConfig.outputCfg.buffer.frameCount,
9760 mConfig.outputCfg.samplingRate,
9761 mConfig.outputCfg.channels,
9762 mConfig.outputCfg.format);
9763 result.append(buffer);
9764
9765 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9766 result.append(buffer);
9767 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9768 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009769 EffectHandle *handle = mHandles[i];
9770 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009771 handle->dump(buffer, SIZE);
9772 result.append(buffer);
9773 }
9774 }
9775
9776 result.append("\n");
9777
9778 write(fd, result.string(), result.length());
9779
9780 if (locked) {
9781 mLock.unlock();
9782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009783}
9784
9785// ----------------------------------------------------------------------------
9786// EffectHandle implementation
9787// ----------------------------------------------------------------------------
9788
9789#undef LOG_TAG
9790#define LOG_TAG "AudioFlinger::EffectHandle"
9791
9792AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9793 const sp<AudioFlinger::Client>& client,
9794 const sp<IEffectClient>& effectClient,
9795 int32_t priority)
9796 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009797 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009798 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009799{
Steve Block3856b092011-10-20 11:56:00 +01009800 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009801
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009802 if (client == 0) {
9803 return;
9804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009805 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9806 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9807 if (mCblkMemory != 0) {
9808 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9809
Glenn Kastena0d68332012-01-27 16:47:15 -08009810 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009811 new(mCblk) effect_param_cblk_t();
9812 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009814 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009815 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009816 return;
9817 }
9818}
9819
9820AudioFlinger::EffectHandle::~EffectHandle()
9821{
Steve Block3856b092011-10-20 11:56:00 +01009822 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009823
9824 if (mEffect == 0) {
9825 mDestroyed = true;
9826 return;
9827 }
9828 mEffect->lock();
9829 mDestroyed = true;
9830 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009831 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009832}
9833
9834status_t AudioFlinger::EffectHandle::enable()
9835{
Steve Block3856b092011-10-20 11:56:00 +01009836 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009837 if (!mHasControl) return INVALID_OPERATION;
9838 if (mEffect == 0) return DEAD_OBJECT;
9839
Eric Laurentdb7c0792011-08-10 10:37:50 -07009840 if (mEnabled) {
9841 return NO_ERROR;
9842 }
9843
Eric Laurent59255e42011-07-27 19:49:51 -07009844 mEnabled = true;
9845
9846 sp<ThreadBase> thread = mEffect->thread().promote();
9847 if (thread != 0) {
9848 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9849 }
9850
9851 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9852 if (mEffect->suspended()) {
9853 return NO_ERROR;
9854 }
9855
Eric Laurentdb7c0792011-08-10 10:37:50 -07009856 status_t status = mEffect->setEnabled(true);
9857 if (status != NO_ERROR) {
9858 if (thread != 0) {
9859 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9860 }
9861 mEnabled = false;
9862 }
9863 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009864}
9865
9866status_t AudioFlinger::EffectHandle::disable()
9867{
Steve Block3856b092011-10-20 11:56:00 +01009868 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009869 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009870 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009871
Eric Laurentdb7c0792011-08-10 10:37:50 -07009872 if (!mEnabled) {
9873 return NO_ERROR;
9874 }
Eric Laurent59255e42011-07-27 19:49:51 -07009875 mEnabled = false;
9876
9877 if (mEffect->suspended()) {
9878 return NO_ERROR;
9879 }
9880
9881 status_t status = mEffect->setEnabled(false);
9882
9883 sp<ThreadBase> thread = mEffect->thread().promote();
9884 if (thread != 0) {
9885 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9886 }
9887
9888 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009889}
9890
9891void AudioFlinger::EffectHandle::disconnect()
9892{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009893 disconnect(true);
9894}
9895
Glenn Kasten58123c32012-02-03 10:32:24 -08009896void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009897{
Glenn Kasten58123c32012-02-03 10:32:24 -08009898 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009899 if (mEffect == 0) {
9900 return;
9901 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009902 // restore suspended effects if the disconnected handle was enabled and the last one.
9903 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009904 sp<ThreadBase> thread = mEffect->thread().promote();
9905 if (thread != 0) {
9906 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9907 }
Eric Laurent59255e42011-07-27 19:49:51 -07009908 }
9909
Mathias Agopian65ab4712010-07-14 17:59:35 -07009910 // release sp on module => module destructor can be called now
9911 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009912 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009913 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009914 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009915 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9916 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009917 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009918 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009919 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9920 mClient.clear();
9921 }
9922}
9923
Eric Laurent25f43952010-07-28 05:40:18 -07009924status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9925 uint32_t cmdSize,
9926 void *pCmdData,
9927 uint32_t *replySize,
9928 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009929{
Steve Block3856b092011-10-20 11:56:00 +01009930// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009931// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009932
9933 // only get parameter command is permitted for applications not controlling the effect
9934 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9935 return INVALID_OPERATION;
9936 }
9937 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009938 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009939
9940 // handle commands that are not forwarded transparently to effect engine
9941 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9942 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9943 // no risk to block the whole media server process or mixer threads is we are stuck here
9944 Mutex::Autolock _l(mCblk->lock);
9945 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9946 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9947 mCblk->serverIndex = 0;
9948 mCblk->clientIndex = 0;
9949 return BAD_VALUE;
9950 }
9951 status_t status = NO_ERROR;
9952 while (mCblk->serverIndex < mCblk->clientIndex) {
9953 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009954 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009955 int *p = (int *)(mBuffer + mCblk->serverIndex);
9956 int size = *p++;
9957 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009958 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009959 break;
9960 }
9961 effect_param_t *param = (effect_param_t *)p;
9962 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009963 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009964 mCblk->serverIndex += size;
9965 continue;
9966 }
Eric Laurent25f43952010-07-28 05:40:18 -07009967 uint32_t psize = sizeof(effect_param_t) +
9968 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9969 param->vsize;
9970 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9971 psize,
9972 p,
9973 &rsize,
9974 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009975 // stop at first error encountered
9976 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009977 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009978 *(int *)pReplyData = reply;
9979 break;
9980 } else if (reply != NO_ERROR) {
9981 *(int *)pReplyData = reply;
9982 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009983 }
9984 mCblk->serverIndex += size;
9985 }
9986 mCblk->serverIndex = 0;
9987 mCblk->clientIndex = 0;
9988 return status;
9989 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009990 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009991 return enable();
9992 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009993 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009994 return disable();
9995 }
9996
vivek mehta2192bc92012-12-04 11:46:08 -08009997#ifdef QCOM_HARDWARE
9998 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
9999 if(mEffect->isOnLPA() &&
10000 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
10001 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
10002 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
10003 // Notify Direct track for the change in Effect module
10004 // TODO: check if it is required to send mLPAHandle
10005 ALOGV("Notifying Direct Track for the change in effect config");
10006 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
10007 }
10008#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010009 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10010}
10011
Eric Laurent59255e42011-07-27 19:49:51 -070010012void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010013{
Steve Block3856b092011-10-20 11:56:00 +010010014 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010015
10016 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -070010017 mEnabled = enabled;
10018
Mathias Agopian65ab4712010-07-14 17:59:35 -070010019 if (signal && mEffectClient != 0) {
10020 mEffectClient->controlStatusChanged(hasControl);
10021 }
10022}
10023
Eric Laurent25f43952010-07-28 05:40:18 -070010024void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
10025 uint32_t cmdSize,
10026 void *pCmdData,
10027 uint32_t replySize,
10028 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010029{
10030 if (mEffectClient != 0) {
10031 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10032 }
10033}
10034
10035
10036
10037void AudioFlinger::EffectHandle::setEnabled(bool enabled)
10038{
10039 if (mEffectClient != 0) {
10040 mEffectClient->enableStatusChanged(enabled);
10041 }
10042}
10043
10044status_t AudioFlinger::EffectHandle::onTransact(
10045 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10046{
10047 return BnEffect::onTransact(code, data, reply, flags);
10048}
10049
10050
10051void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
10052{
Glenn Kastena0d68332012-01-27 16:47:15 -080010053 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010054
10055 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -080010056 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -070010057 mPriority,
10058 mHasControl,
10059 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -070010060 mCblk ? mCblk->clientIndex : 0,
10061 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070010062 );
10063
10064 if (locked) {
10065 mCblk->lock.unlock();
10066 }
10067}
10068
10069#undef LOG_TAG
10070#define LOG_TAG "AudioFlinger::EffectChain"
10071
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010072AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010073 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010074 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -070010075 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
10076 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -080010077#ifdef QCOM_HARDWARE
10078 ,mIsForLPATrack(false)
10079#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010080{
Dima Zavinfce7a472011-04-19 22:30:36 -070010081 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010082 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010083 return;
10084 }
10085 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
10086 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010087}
10088
10089AudioFlinger::EffectChain::~EffectChain()
10090{
10091 if (mOwnInBuffer) {
10092 delete mInBuffer;
10093 }
10094
10095}
10096
Eric Laurent59255e42011-07-27 19:49:51 -070010097// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010098sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010099{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010100 size_t size = mEffects.size();
10101
10102 for (size_t i = 0; i < size; i++) {
10103 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010104 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010105 }
10106 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010107 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010108}
10109
Eric Laurent59255e42011-07-27 19:49:51 -070010110// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010111sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010112{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010113 size_t size = mEffects.size();
10114
10115 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010116 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10117 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010118 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010119 }
10120 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010121 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010122}
10123
vivek mehta2192bc92012-12-04 11:46:08 -080010124#ifdef QCOM_HARDWARE
10125sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10126{
10127 sp<EffectModule> effect = NULL;
10128 if(idx < 0 || idx >= mEffects.size()) {
10129 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10130 }
10131 if(mEffects.size() > 0){
10132 effect = mEffects[idx];
10133 }
10134 return effect;
10135}
10136#endif
10137
Eric Laurent59255e42011-07-27 19:49:51 -070010138// getEffectFromType_l() must be called with ThreadBase::mLock held
10139sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10140 const effect_uuid_t *type)
10141{
Eric Laurent59255e42011-07-27 19:49:51 -070010142 size_t size = mEffects.size();
10143
10144 for (size_t i = 0; i < size; i++) {
10145 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010146 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010147 }
10148 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010149 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010150}
10151
Eric Laurent91b14c42012-05-30 12:30:29 -070010152void AudioFlinger::EffectChain::clearInputBuffer()
10153{
10154 Mutex::Autolock _l(mLock);
10155 sp<ThreadBase> thread = mThread.promote();
10156 if (thread == 0) {
10157 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10158 return;
10159 }
10160 clearInputBuffer_l(thread);
10161}
10162
10163// Must be called with EffectChain::mLock locked
10164void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10165{
10166 size_t numSamples = thread->frameCount() * thread->channelCount();
10167 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10168
10169}
10170
Mathias Agopian65ab4712010-07-14 17:59:35 -070010171// Must be called with EffectChain::mLock locked
10172void AudioFlinger::EffectChain::process_l()
10173{
Eric Laurentdac69112010-09-28 14:09:57 -070010174 sp<ThreadBase> thread = mThread.promote();
10175 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010176 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010177 return;
10178 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010179 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10180 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010181 // always process effects unless no more tracks are on the session and the effect tail
10182 // has been rendered
10183 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010184 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010185 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010186
Eric Laurent544fe9b2011-11-11 15:42:52 -080010187 if (!tracksOnSession && mTailBufferCount == 0) {
10188 doProcess = false;
10189 }
10190
10191 if (activeTrackCnt() == 0) {
10192 // if no track is active and the effect tail has not been rendered,
10193 // the input buffer must be cleared here as the mixer process will not do it
10194 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010195 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010196 if (mTailBufferCount > 0) {
10197 mTailBufferCount--;
10198 }
10199 }
10200 }
Eric Laurentdac69112010-09-28 14:09:57 -070010201 }
10202
Mathias Agopian65ab4712010-07-14 17:59:35 -070010203 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010204#ifdef QCOM_HARDWARE
10205 if (doProcess || isForLPATrack()) {
10206#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010207 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010208#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010209 for (size_t i = 0; i < size; i++) {
10210 mEffects[i]->process();
10211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010212 }
10213 for (size_t i = 0; i < size; i++) {
10214 mEffects[i]->updateState();
10215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010216}
10217
Eric Laurentcab11242010-07-15 12:50:15 -070010218// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010219status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010220{
10221 effect_descriptor_t desc = effect->desc();
10222 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10223
10224 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010225 effect->setChain(this);
10226 sp<ThreadBase> thread = mThread.promote();
10227 if (thread == 0) {
10228 return NO_INIT;
10229 }
10230 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010231
10232 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10233 // Auxiliary effects are inserted at the beginning of mEffects vector as
10234 // they are processed first and accumulated in chain input buffer
10235 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010236
Mathias Agopian65ab4712010-07-14 17:59:35 -070010237 // the input buffer for auxiliary effect contains mono samples in
10238 // 32 bit format. This is to avoid saturation in AudoMixer
10239 // accumulation stage. Saturation is done in EffectModule::process() before
10240 // calling the process in effect engine
10241 size_t numSamples = thread->frameCount();
10242 int32_t *buffer = new int32_t[numSamples];
10243 memset(buffer, 0, numSamples * sizeof(int32_t));
10244 effect->setInBuffer((int16_t *)buffer);
10245 // auxiliary effects output samples to chain input buffer for further processing
10246 // by insert effects
10247 effect->setOutBuffer(mInBuffer);
10248 } else {
10249 // Insert effects are inserted at the end of mEffects vector as they are processed
10250 // after track and auxiliary effects.
10251 // Insert effect order as a function of indicated preference:
10252 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10253 // another effect is present
10254 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10255 // last effect claiming first position
10256 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10257 // first effect claiming last position
10258 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10259 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10260 // already present
10261
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010262 size_t size = mEffects.size();
10263 size_t idx_insert = size;
10264 ssize_t idx_insert_first = -1;
10265 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010266
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010267 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010268 effect_descriptor_t d = mEffects[i]->desc();
10269 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10270 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10271 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10272 // check invalid effect chaining combinations
10273 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10274 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010275 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010276 return INVALID_OPERATION;
10277 }
10278 // remember position of first insert effect and by default
10279 // select this as insert position for new effect
10280 if (idx_insert == size) {
10281 idx_insert = i;
10282 }
10283 // remember position of last insert effect claiming
10284 // first position
10285 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10286 idx_insert_first = i;
10287 }
10288 // remember position of first insert effect claiming
10289 // last position
10290 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10291 idx_insert_last == -1) {
10292 idx_insert_last = i;
10293 }
10294 }
10295 }
10296
10297 // modify idx_insert from first position if needed
10298 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10299 if (idx_insert_last != -1) {
10300 idx_insert = idx_insert_last;
10301 } else {
10302 idx_insert = size;
10303 }
10304 } else {
10305 if (idx_insert_first != -1) {
10306 idx_insert = idx_insert_first + 1;
10307 }
10308 }
10309
10310 // always read samples from chain input buffer
10311 effect->setInBuffer(mInBuffer);
10312
10313 // if last effect in the chain, output samples to chain
10314 // output buffer, otherwise to chain input buffer
10315 if (idx_insert == size) {
10316 if (idx_insert != 0) {
10317 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10318 mEffects[idx_insert-1]->configure();
10319 }
10320 effect->setOutBuffer(mOutBuffer);
10321 } else {
10322 effect->setOutBuffer(mInBuffer);
10323 }
10324 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010325
Steve Block3856b092011-10-20 11:56:00 +010010326 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010327 }
10328 effect->configure();
10329 return NO_ERROR;
10330}
10331
Eric Laurentcab11242010-07-15 12:50:15 -070010332// removeEffect_l() must be called with PlaybackThread::mLock held
10333size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010334{
10335 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010336 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010337 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10338
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010339 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010340 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010341 // calling stop here will remove pre-processing effect from the audio HAL.
10342 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10343 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010344 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10345 mEffects[i]->state() == EffectModule::STOPPING) {
10346 mEffects[i]->stop();
10347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010348 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10349 delete[] effect->inBuffer();
10350 } else {
10351 if (i == size - 1 && i != 0) {
10352 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10353 mEffects[i - 1]->configure();
10354 }
10355 }
10356 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010357 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010358 break;
10359 }
10360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010361
10362 return mEffects.size();
10363}
10364
Eric Laurentcab11242010-07-15 12:50:15 -070010365// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010366void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010367{
10368 size_t size = mEffects.size();
10369 for (size_t i = 0; i < size; i++) {
10370 mEffects[i]->setDevice(device);
10371 }
10372}
10373
Eric Laurentcab11242010-07-15 12:50:15 -070010374// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010375void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010376{
10377 size_t size = mEffects.size();
10378 for (size_t i = 0; i < size; i++) {
10379 mEffects[i]->setMode(mode);
10380 }
10381}
10382
Eric Laurent57b2dd12012-08-31 17:44:06 -070010383// setAudioSource_l() must be called with PlaybackThread::mLock held
10384void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10385{
10386 size_t size = mEffects.size();
10387 for (size_t i = 0; i < size; i++) {
10388 mEffects[i]->setAudioSource(source);
10389 }
10390}
10391
Eric Laurentcab11242010-07-15 12:50:15 -070010392// setVolume_l() must be called with PlaybackThread::mLock held
10393bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010394{
10395 uint32_t newLeft = *left;
10396 uint32_t newRight = *right;
10397 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010398 int ctrlIdx = -1;
10399 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010400
Eric Laurentcab11242010-07-15 12:50:15 -070010401 // first update volume controller
10402 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010403 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010404 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10405 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010406 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010407 break;
10408 }
10409 }
10410
10411 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010412 if (hasControl) {
10413 *left = mNewLeftVolume;
10414 *right = mNewRightVolume;
10415 }
10416 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010417 }
10418
10419 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010420 mLeftVolume = newLeft;
10421 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010422
10423 // second get volume update from volume controller
10424 if (ctrlIdx >= 0) {
10425 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010426 mNewLeftVolume = newLeft;
10427 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010428 }
10429 // then indicate volume to all other effects in chain.
10430 // Pass altered volume to effects before volume controller
10431 // and requested volume to effects after controller
10432 uint32_t lVol = newLeft;
10433 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010434
Mathias Agopian65ab4712010-07-14 17:59:35 -070010435 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010436 if ((int)i == ctrlIdx) continue;
10437 // this also works for ctrlIdx == -1 when there is no volume controller
10438 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010439 lVol = *left;
10440 rVol = *right;
10441 }
10442 mEffects[i]->setVolume(&lVol, &rVol, false);
10443 }
10444 *left = newLeft;
10445 *right = newRight;
10446
10447 return hasControl;
10448}
10449
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010450void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010451{
10452 const size_t SIZE = 256;
10453 char buffer[SIZE];
10454 String8 result;
10455
10456 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10457 result.append(buffer);
10458
10459 bool locked = tryLock(mLock);
10460 // failed to lock - AudioFlinger is probably deadlocked
10461 if (!locked) {
10462 result.append("\tCould not lock mutex:\n");
10463 }
10464
Eric Laurentcab11242010-07-15 12:50:15 -070010465 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10466 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010467 mEffects.size(),
10468 (uint32_t)mInBuffer,
10469 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010470 mActiveTrackCnt);
10471 result.append(buffer);
10472 write(fd, result.string(), result.size());
10473
10474 for (size_t i = 0; i < mEffects.size(); ++i) {
10475 sp<EffectModule> effect = mEffects[i];
10476 if (effect != 0) {
10477 effect->dump(fd, args);
10478 }
10479 }
10480
10481 if (locked) {
10482 mLock.unlock();
10483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010484}
10485
Eric Laurent59255e42011-07-27 19:49:51 -070010486// must be called with ThreadBase::mLock held
10487void AudioFlinger::EffectChain::setEffectSuspended_l(
10488 const effect_uuid_t *type, bool suspend)
10489{
10490 sp<SuspendedEffectDesc> desc;
10491 // use effect type UUID timelow as key as there is no real risk of identical
10492 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010493 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010494 if (suspend) {
10495 if (index >= 0) {
10496 desc = mSuspendedEffects.valueAt(index);
10497 } else {
10498 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010499 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010500 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010501 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010502 }
10503 if (desc->mRefCount++ == 0) {
10504 sp<EffectModule> effect = getEffectIfEnabled(type);
10505 if (effect != 0) {
10506 desc->mEffect = effect;
10507 effect->setSuspended(true);
10508 effect->setEnabled(false);
10509 }
10510 }
10511 } else {
10512 if (index < 0) {
10513 return;
10514 }
10515 desc = mSuspendedEffects.valueAt(index);
10516 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010517 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010518 desc->mRefCount = 1;
10519 }
10520 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010521 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010522 if (desc->mEffect != 0) {
10523 sp<EffectModule> effect = desc->mEffect.promote();
10524 if (effect != 0) {
10525 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010526 effect->lock();
10527 EffectHandle *handle = effect->controlHandle_l();
10528 if (handle != NULL && !handle->destroyed_l()) {
10529 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010530 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010531 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010532 }
10533 desc->mEffect.clear();
10534 }
10535 mSuspendedEffects.removeItemsAt(index);
10536 }
10537 }
10538}
10539
10540// must be called with ThreadBase::mLock held
10541void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10542{
10543 sp<SuspendedEffectDesc> desc;
10544
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010545 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010546 if (suspend) {
10547 if (index >= 0) {
10548 desc = mSuspendedEffects.valueAt(index);
10549 } else {
10550 desc = new SuspendedEffectDesc();
10551 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010552 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010553 }
10554 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010555 Vector< sp<EffectModule> > effects;
10556 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010557 for (size_t i = 0; i < effects.size(); i++) {
10558 setEffectSuspended_l(&effects[i]->desc().type, true);
10559 }
10560 }
10561 } else {
10562 if (index < 0) {
10563 return;
10564 }
10565 desc = mSuspendedEffects.valueAt(index);
10566 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010567 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010568 desc->mRefCount = 1;
10569 }
10570 if (--desc->mRefCount == 0) {
10571 Vector<const effect_uuid_t *> types;
10572 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10573 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10574 continue;
10575 }
10576 types.add(&mSuspendedEffects.valueAt(i)->mType);
10577 }
10578 for (size_t i = 0; i < types.size(); i++) {
10579 setEffectSuspended_l(types[i], false);
10580 }
Steve Block3856b092011-10-20 11:56:00 +010010581 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010582 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10583 }
10584 }
10585}
10586
Eric Laurent6bffdb82011-09-23 08:40:41 -070010587
10588// The volume effect is used for automated tests only
10589#ifndef OPENSL_ES_H_
10590static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10591 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10592const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10593#endif //OPENSL_ES_H_
10594
Eric Laurentdb7c0792011-08-10 10:37:50 -070010595bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10596{
10597 // auxiliary effects and visualizer are never suspended on output mix
10598 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10599 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010600 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10601 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010602 return false;
10603 }
10604 return true;
10605}
10606
Glenn Kastend0539712012-01-30 12:56:03 -080010607void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010608{
Glenn Kastend0539712012-01-30 12:56:03 -080010609 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010610 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010611 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10612 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010613 }
Eric Laurent59255e42011-07-27 19:49:51 -070010614 }
Eric Laurent59255e42011-07-27 19:49:51 -070010615}
10616
10617sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10618 const effect_uuid_t *type)
10619{
Glenn Kasten090f0192012-01-30 13:00:02 -080010620 sp<EffectModule> effect = getEffectFromType_l(type);
10621 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010622}
10623
10624void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10625 bool enabled)
10626{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010627 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010628 if (enabled) {
10629 if (index < 0) {
10630 // if the effect is not suspend check if all effects are suspended
10631 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10632 if (index < 0) {
10633 return;
10634 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010635 if (!isEffectEligibleForSuspend(effect->desc())) {
10636 return;
10637 }
Eric Laurent59255e42011-07-27 19:49:51 -070010638 setEffectSuspended_l(&effect->desc().type, enabled);
10639 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010640 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010641 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010642 return;
10643 }
Eric Laurent59255e42011-07-27 19:49:51 -070010644 }
Steve Block3856b092011-10-20 11:56:00 +010010645 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010646 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010647 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10648 // if effect is requested to suspended but was not yet enabled, supend it now.
10649 if (desc->mEffect == 0) {
10650 desc->mEffect = effect;
10651 effect->setEnabled(false);
10652 effect->setSuspended(true);
10653 }
10654 } else {
10655 if (index < 0) {
10656 return;
10657 }
Steve Block3856b092011-10-20 11:56:00 +010010658 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010659 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010660 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10661 desc->mEffect.clear();
10662 effect->setSuspended(false);
10663 }
10664}
10665
Mathias Agopian65ab4712010-07-14 17:59:35 -070010666#undef LOG_TAG
10667#define LOG_TAG "AudioFlinger"
10668
10669// ----------------------------------------------------------------------------
10670
10671status_t AudioFlinger::onTransact(
10672 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10673{
10674 return BnAudioFlinger::onTransact(code, data, reply, flags);
10675}
10676
Mathias Agopian65ab4712010-07-14 17:59:35 -070010677}; // namespace android