blob: e4c055ac9208306e1d181e8c9626a7424a1d92a3 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
vivek mehta2192bc92012-12-04 11:46:08 -08004** Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
5**
6** Copyright (c) 2012, The Linux Foundation. All rights reserved.
7** Not a Contribution, Apache license notifications and license are retained
8** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07009**
10** Licensed under the Apache License, Version 2.0 (the "License");
11** you may not use this file except in compliance with the License.
12** You may obtain a copy of the License at
13**
14** http://www.apache.org/licenses/LICENSE-2.0
15**
16** Unless required by applicable law or agreed to in writing, software
17** distributed under the License is distributed on an "AS IS" BASIS,
18** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19** See the License for the specific language governing permissions and
20** limitations under the License.
21*/
22
23
24#define LOG_TAG "AudioFlinger"
25//#define LOG_NDEBUG 0
26
27#include <math.h>
28#include <signal.h>
29#include <sys/time.h>
30#include <sys/resource.h>
31
Gloria Wang9ee159b2011-02-24 14:51:45 -080032#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/IServiceManager.h>
34#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070035#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/Parcel.h>
37#include <binder/IPCThreadState.h>
38#include <utils/String16.h>
39#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070040#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041
Dima Zavinfce7a472011-04-19 22:30:36 -070042#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080044#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#undef ADD_BATTERY_DATA
47
48#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080049#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080050#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070051#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include <private/media/AudioTrackShared.h>
54#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070057#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
59#include "AudioMixer.h"
60#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080061#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070064#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070065#include <audio_effects/effect_ns.h>
66#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
Glenn Kasten3b21c502011-12-15 09:52:39 -080068#include <audio_utils/primitives.h>
69
Eric Laurentfeb0db62011-07-22 09:04:31 -070070#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080071
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070077
John Grossman4ff14ba2012-02-08 16:37:41 -080078#include <common_time/cc_helper.h>
79#include <common_time/local_clock.h>
80
Glenn Kasten58912562012-04-03 10:45:00 -070081#include "FastMixer.h"
82
83// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070084#include <media/nbaio/AudioStreamOutSink.h>
85#include <media/nbaio/MonoPipe.h>
86#include <media/nbaio/MonoPipeReader.h>
87#include <media/nbaio/Pipe.h>
88#include <media/nbaio/PipeReader.h>
89#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070090
Glenn Kasten1dc28b72012-04-24 10:01:03 -070091#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070092
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
John Grossman1c345192012-03-27 14:00:17 -070095// Note: the following macro is used for extremely verbose logging message. In
96// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
97// 0; but one side effect of this is to turn all LOGV's as well. Some messages
98// are so verbose that we want to suppress them even when we have ALOG_ASSERT
99// turned on. Do not uncomment the #def below unless you really know what you
100// are doing and want to see all of the extremely verbose messages.
101//#define VERY_VERY_VERBOSE_LOGGING
102#ifdef VERY_VERY_VERBOSE_LOGGING
103#define ALOGVV ALOGV
104#else
105#define ALOGVV(a...) do { } while(0)
106#endif
Eric Laurentde070132010-07-13 04:45:46 -0700107
vivek mehta2192bc92012-12-04 11:46:08 -0800108#ifdef QCOM_HARDWARE
109#define DIRECT_TRACK_EOS 1
110static const char lockName[] = "DirectTrack";
111#endif
112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113namespace android {
114
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800115static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
116static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800119static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121// retry counts for buffer fill timeout
122// 50 * ~20msecs = 1 second
123static const int8_t kMaxTrackRetries = 50;
124static const int8_t kMaxTrackStartupRetries = 50;
125// allow less retry attempts on direct output thread.
126// direct outputs can be a scarce resource in audio hardware and should
127// be released as quickly as possible.
128static const int8_t kMaxTrackRetriesDirect = 2;
129
130static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800131static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700132
Glenn Kasten7dede872011-12-13 11:04:14 -0800133// don't warn about blocked writes or record buffer overflows more often than this
134static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700136// RecordThread loop sleep time upon application overrun or audio HAL read error
137static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138
Glenn Kasten7dede872011-12-13 11:04:14 -0800139// maximum time to wait for setParameters to complete
140static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700141
Eric Laurent7cafbb32011-11-22 18:50:29 -0800142// minimum sleep time for the mixer thread loop when tracks are active but in underrun
143static const uint32_t kMinThreadSleepTimeUs = 5000;
144// maximum divider applied to the active sleep time in the mixer thread loop
145static const uint32_t kMaxThreadSleepTimeShift = 2;
146
Glenn Kasten58912562012-04-03 10:45:00 -0700147// minimum normal mix buffer size, expressed in milliseconds rather than frames
148static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700149// maximum normal mix buffer size
150static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700151
John Grossman4ff14ba2012-02-08 16:37:41 -0800152nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800153
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700160 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700162 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700171static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
172 // AudioFlinger::setParameters() updates, other threads read w/o lock
173
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700174// Priorities for requestPriority
175static const int kPriorityAudioApp = 2;
176static const int kPriorityFastMixer = 3;
177
Glenn Kasten3ed29202012-08-07 15:24:44 -0700178// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
179// for the track. The client then sub-divides this into smaller buffers for its use.
180// Currently the client uses double-buffering by default, but doesn't tell us about that.
181// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700182// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
183// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700184// See the client's minBufCount and mNotificationFramesAct calculations for details.
185static const int kFastTrackMultiplier = 2;
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700189#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800190// To collect the amplifier usage
191static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800192 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
193 if (service == NULL) {
194 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800195 return;
196 }
197
198 service->addBatteryData(params);
199}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700200#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800201
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700203{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700204 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 int rc;
206
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700207 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
208 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
209 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
210 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700212 }
213 rc = audio_hw_device_open(mod, dev);
214 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
215 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
216 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700218 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000219#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700220 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
221 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
222 rc = BAD_VALUE;
223 goto out;
224 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100225#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 return 0;
227
228out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 *dev = NULL;
230 return rc;
231}
232
vivek mehta2192bc92012-12-04 11:46:08 -0800233static uint32_t getInputChannelCount(uint32_t channels) {
234#ifdef QCOM_HARDWARE
235 // only mono or stereo and 5.1 are supported for input sources
236 return popcount((channels) & (AUDIO_CHANNEL_IN_STEREO | AUDIO_CHANNEL_IN_MONO | AUDIO_CHANNEL_IN_5POINT1));
237#else
238 return popcount(channels);
239#endif
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241// ----------------------------------------------------------------------------
242
243AudioFlinger::AudioFlinger()
244 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800245 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700246 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800248 mMasterMute(false),
249 mNextUniqueId(1),
250 mMode(AUDIO_MODE_INVALID),
251 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700252{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700253}
254
255void AudioFlinger::onFirstRef()
256{
Dima Zavin799a70e2011-04-18 16:57:27 -0700257 int rc = 0;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800258#ifdef QCOM_HARDWARE
259 mA2DPHandle = -1;
260#endif
Dima Zavinfce7a472011-04-19 22:30:36 -0700261
Eric Laurent93575202011-01-18 18:39:02 -0800262 Mutex::Autolock _l(mLock);
263
Dima Zavin799a70e2011-04-18 16:57:27 -0700264 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800265#ifdef QCOM_HARDWARE
266 mLPASessionId = -2; // -2 is invalid session ID
267 mIsEffectConfigChanged = false;
268 mLPAEffectChain = NULL;
269#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800270 char val_str[PROPERTY_VALUE_MAX] = { 0 };
271 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
272 uint32_t int_val;
273 if (1 == sscanf(val_str, "%u", &int_val)) {
274 mStandbyTimeInNsecs = milliseconds(int_val);
275 ALOGI("Using %u mSec as standby time.", int_val);
276 } else {
277 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
278 ALOGI("Using default %u mSec as standby time.",
279 (uint32_t)(mStandbyTimeInNsecs / 1000000));
280 }
281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700282
Eric Laurenta4c5a552012-03-29 10:12:40 -0700283 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700284}
285
286AudioFlinger::~AudioFlinger()
287{
288 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700289 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700290 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700291 }
292 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700293 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700294 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700295 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700296
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800297 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
298 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
300 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301 }
302}
303
Eric Laurenta4c5a552012-03-29 10:12:40 -0700304static const char * const audio_interfaces[] = {
305 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
306 AUDIO_HARDWARE_MODULE_ID_A2DP,
307 AUDIO_HARDWARE_MODULE_ID_USB,
308};
309#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
310
John Grossmanee578c02012-07-23 17:05:46 -0700311AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
312 audio_module_handle_t module,
313 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700314{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700315 // if module is 0, the request comes from an old policy manager and we should load
316 // well known modules
317 if (module == 0) {
318 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
319 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
320 loadHwModule_l(audio_interfaces[i]);
321 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700322 // then try to find a module supporting the requested device.
323 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
324 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
325 audio_hw_device_t *dev = audioHwDevice->hwDevice();
326 if ((dev->get_supported_devices != NULL) &&
327 (dev->get_supported_devices(dev) & devices) == devices)
328 return audioHwDevice;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800329#ifdef ICS_AUDIO_BLOB
330 else if (dev->get_supported_devices == NULL && i != 0 &&
331 devices == 0x80)
332 // Reasonably safe assumption: A non-primary HAL without
333 // get_supported_devices is a locally-built A2DP binary
334 return audioHwDevice;
335#endif
Eric Laurentf1c04f92012-08-28 14:26:53 -0700336 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700337 } else {
338 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700339 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
340 if (audioHwDevice != NULL) {
341 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700342 }
343 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700344
Dima Zavin799a70e2011-04-18 16:57:27 -0700345 return NULL;
346}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700348void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349{
350 const size_t SIZE = 256;
351 char buffer[SIZE];
352 String8 result;
353
354 result.append("Clients:\n");
355 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800356 sp<Client> client = mClients.valueAt(i).promote();
357 if (client != 0) {
358 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
359 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360 }
361 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700362
363 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800364 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700365 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
366 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800367 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700368 result.append(buffer);
369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371}
372
373
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700374void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375{
376 const size_t SIZE = 256;
377 char buffer[SIZE];
378 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800379 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380
John Grossman4ff14ba2012-02-08 16:37:41 -0800381 snprintf(buffer, SIZE, "Hardware status: %d\n"
382 "Standby Time mSec: %u\n",
383 hardwareStatus,
384 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 result.append(buffer);
386 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387}
388
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700389void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390{
391 const size_t SIZE = 256;
392 char buffer[SIZE];
393 String8 result;
394 snprintf(buffer, SIZE, "Permission Denial: "
395 "can't dump AudioFlinger from pid=%d, uid=%d\n",
396 IPCThreadState::self()->getCallingPid(),
397 IPCThreadState::self()->getCallingUid());
398 result.append(buffer);
399 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400}
401
402static bool tryLock(Mutex& mutex)
403{
404 bool locked = false;
405 for (int i = 0; i < kDumpLockRetries; ++i) {
406 if (mutex.tryLock() == NO_ERROR) {
407 locked = true;
408 break;
409 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800410 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 return locked;
413}
414
415status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
416{
Glenn Kasten44deb052012-02-05 18:09:08 -0800417 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418 dumpPermissionDenial(fd, args);
419 } else {
420 // get state of hardware lock
421 bool hardwareLocked = tryLock(mHardwareLock);
422 if (!hardwareLocked) {
423 String8 result(kHardwareLockedString);
424 write(fd, result.string(), result.size());
425 } else {
426 mHardwareLock.unlock();
427 }
428
429 bool locked = tryLock(mLock);
430
431 // failed to lock - AudioFlinger is probably deadlocked
432 if (!locked) {
433 String8 result(kDeadlockedString);
434 write(fd, result.string(), result.size());
435 }
436
437 dumpClients(fd, args);
438 dumpInternals(fd, args);
439
440 // dump playback threads
441 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
442 mPlaybackThreads.valueAt(i)->dump(fd, args);
443 }
444
445 // dump record threads
446 for (size_t i = 0; i < mRecordThreads.size(); i++) {
447 mRecordThreads.valueAt(i)->dump(fd, args);
448 }
449
Dima Zavin799a70e2011-04-18 16:57:27 -0700450 // dump all hardware devs
451 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700452 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700453 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 }
455 if (locked) mLock.unlock();
456 }
457 return NO_ERROR;
458}
459
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800460sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
461{
462 // If pid is already in the mClients wp<> map, then use that entry
463 // (for which promote() is always != 0), otherwise create a new entry and Client.
464 sp<Client> client = mClients.valueFor(pid).promote();
465 if (client == 0) {
466 client = new Client(this, pid);
467 mClients.add(pid, client);
468 }
469
470 return client;
471}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
473// IAudioFlinger interface
474
475
476sp<IAudioTrack> AudioFlinger::createTrack(
477 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800478 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800480 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700481 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800483 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800485 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800486 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 int *sessionId,
488 status_t *status)
489{
490 sp<PlaybackThread::Track> track;
491 sp<TrackHandle> trackHandle;
492 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 status_t lStatus;
494 int lSessionId;
495
Glenn Kasten263709e2012-01-06 08:40:01 -0800496 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
497 // but if someone uses binder directly they could bypass that and cause us to crash
498 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000499 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 lStatus = BAD_VALUE;
501 goto Exit;
502 }
503
504 {
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700507 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000509 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 lStatus = BAD_VALUE;
511 goto Exit;
512 }
513
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800514 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515
Steve Block3856b092011-10-20 11:56:00 +0100516 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700517 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700518 // check if an effect chain with the same session ID is present on another
519 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700520 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700521 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
522 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700523 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700524 if (sessions & PlaybackThread::EFFECT_SESSION) {
525 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700526 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700527 }
Eric Laurentde070132010-07-13 04:45:46 -0700528 }
529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 lSessionId = *sessionId;
531 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700532 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700533 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 if (sessionId != NULL) {
535 *sessionId = lSessionId;
536 }
537 }
Steve Block3856b092011-10-20 11:56:00 +0100538 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539
540 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800541 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700542
543 // move effect chain to this output thread if an effect on same session was waiting
544 // for a track to be created
545 if (lStatus == NO_ERROR && effectThread != NULL) {
546 Mutex::Autolock _dl(thread->mLock);
547 Mutex::Autolock _sl(effectThread->mLock);
548 moveEffectChain_l(lSessionId, effectThread, thread, true);
549 }
Eric Laurenta011e352012-03-29 15:51:43 -0700550
551 // Look for sync events awaiting for a session to be used.
552 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
553 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
554 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700555 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700556 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700557 } else {
558 mPendingSyncEvents[i]->cancel();
559 }
Eric Laurenta011e352012-03-29 15:51:43 -0700560 mPendingSyncEvents.removeAt(i);
561 i--;
562 }
563 }
564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 if (lStatus == NO_ERROR) {
567 trackHandle = new TrackHandle(track);
568 } else {
569 // remove local strong reference to Client before deleting the Track so that the Client
570 // destructor is called by the TrackBase destructor with mLock held
571 client.clear();
572 track.clear();
573 }
574
575Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700576 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 *status = lStatus;
578 }
579 return trackHandle;
580}
581
vivek mehta2192bc92012-12-04 11:46:08 -0800582#ifdef QCOM_HARDWARE
583sp<IDirectTrack> AudioFlinger::createDirectTrack(
584 pid_t pid,
585 uint32_t sampleRate,
586 audio_channel_mask_t channelMask,
587 audio_io_handle_t output,
588 int *sessionId,
589 IDirectTrackClient *client,
590 audio_stream_type_t streamType,
591 status_t *status)
592{
593 *status = NO_ERROR;
594 status_t lStatus = NO_ERROR;
595 sp<IDirectTrack> track = NULL;
596 DirectAudioTrack* directTrack = NULL;
597 Mutex::Autolock _l(mLock);
598
599 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
600 *sessionId, sampleRate, channelMask);
601 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
602 if(desc == NULL) {
603 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
604 lStatus = BAD_VALUE;
605 goto Exit;
606 }
607 desc->mStreamType = streamType;
608 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
609 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
610 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
611 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
612 // Check if the session ID is already associated with a track
613 uint32_t sessions = t->hasAudioSession(*sessionId);
614
615 // check if an effect with same session ID is waiting for a ssession to be created
616 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
617 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
618 // Clear reference to previous effect chain if any
619 t->mLock.lock();
620 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
621 mLPAEffectChain = t->getEffectChain_l(*sessionId);
622 t->mLock.unlock();
623 }
624 }
625 mLPASessionId = *sessionId;
626 if (mLPAEffectChain != NULL) {
627 mLPAEffectChain->setLPAFlag(true);
628 // For LPA, the volume will be applied in DSP. No need for volume
629 // control in the Effect chain, so setting it to unity.
630 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
631 mLPAEffectChain->setVolume_l(&volume,&volume);
632 } else {
633 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
634 }
635 mLPASampleRate = sampleRate;
636 mLPANumChannels = popcount(channelMask);
637 } else {
638 if(sessionId != NULL) {
639 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
640 }
641 }
642 }
643 mLock.unlock();
644 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
645 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
646 mLock.lock();
647 if (directTrack != 0) {
648 track = dynamic_cast<IDirectTrack *>(directTrack);
649 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
650 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
651 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
652 } else {
653 lStatus = BAD_VALUE;
654 }
655Exit:
656 if(lStatus) {
657 if (track != NULL) {
658 track.clear();
659 }
660 *status = lStatus;
661 }
662 return track;
663}
664
665void AudioFlinger::deleteEffectSession()
666{
667 Mutex::Autolock _l(mLock);
668 ALOGV("deleteSession");
669 // -2 is invalid session ID
670 mLPASessionId = -2;
671 if (mLPAEffectChain != NULL) {
672 mLPAEffectChain->setLPAFlag(false);
673 size_t i, numEffects = mLPAEffectChain->getNumEffects();
674 for(i = 0; i < numEffects; i++) {
675 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
676 effect->setInBuffer(mLPAEffectChain->inBuffer());
677 if (i == numEffects-1) {
678 effect->setOutBuffer(mLPAEffectChain->outBuffer());
679 } else {
680 effect->setOutBuffer(mLPAEffectChain->inBuffer());
681 }
682 effect->configure();
683 }
684 mLPAEffectChain.clear();
685 mLPAEffectChain = NULL;
686 }
687}
688
689// ToDo: Should we go ahead with this frameCount?
690#define DEAFULT_FRAME_COUNT 1200
691void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
692{
693 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
694 // This might be the first buffer to apply effects after effect config change
695 // should not skip effects processing
696 mIsEffectConfigChanged = false;
697
698 volatile size_t numEffects = 0;
699 if(mLPAEffectChain != NULL) {
700 numEffects = mLPAEffectChain->getNumEffects();
701 }
702
703 if( numEffects > 0) {
704 size_t i = 0;
705 int16_t *pIn = inBuffer;
706 int16_t *pOut = outBuffer;
707
708 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
709
710 while(frameCount > 0) {
711 if(mLPAEffectChain == NULL) {
712 ALOGV("LPA Effect Chain is removed - No effects processing !!");
713 numEffects = 0;
714 break;
715 }
716 mLPAEffectChain->lock();
717
718 numEffects = mLPAEffectChain->getNumEffects();
719 if(!numEffects) {
720 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
721 mLPAEffectChain->unlock();
722 break;
723 }
724
725 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
726 bool isEffectEnabled = false;
727 for(i = 0; i < numEffects; i++) {
728 // If effect configuration is changed while applying effects do not process further
729 if(mIsEffectConfigChanged) {
730 mLPAEffectChain->unlock();
731 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
732 return;
733 }
734 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
735 if(effect == NULL) {
736 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
737 mLPAEffectChain->unlock();
738 return;
739 }
740 if(i == 0) {
741 // For the first set input and output buffers different
742 isEffectEnabled = effect->isProcessEnabled();
743 effect->setInBuffer(pIn);
744 effect->setOutBuffer(pOut);
745 } else {
746 // For the remaining use previous effect's output buffer as input buffer
747 effect->setInBuffer(pOut);
748 effect->setOutBuffer(pOut);
749 }
750 // true indicates that it is being applied on LPA output
751 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
752 }
753
754 if(isEffectEnabled) {
755 // Clear the output buffer
756 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
757 } else {
758 // Copy input buffer content to the output buffer
759 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
760 }
761
762 mLPAEffectChain->process_l();
763
764 mLPAEffectChain->unlock();
765
766 // Update input and output buffer pointers
767 pIn += (outFrameCount * mLPANumChannels);
768 pOut += (outFrameCount * mLPANumChannels);
769 frameCount -= outFrameCount;
770 }
771 }
772
773 if (!numEffects) {
774 ALOGV("applyEffectsOn: There are no effects to be applied");
775 if(inBuffer != outBuffer) {
776 // No effect applied so just copy input buffer to output buffer
777 memcpy(outBuffer, inBuffer, size);
778 }
779 }
780}
781#endif
782
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800783uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784{
785 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800786#ifdef QCOM_HARDWARE
787 if (!mDirectAudioTracks.isEmpty()) {
788 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
789 if(desc != NULL) {
790 return desc->stream->common.get_sample_rate(&desc->stream->common);
791 }
792 }
793#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 PlaybackThread *thread = checkPlaybackThread_l(output);
795 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000796 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 return 0;
798 }
799 return thread->sampleRate();
800}
801
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800802int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803{
804 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800805#ifdef QCOM_HARDWARE
806 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
807 if(desc != NULL) {
808 return desc->stream->common.get_channels(&desc->stream->common);
809 }
810#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 PlaybackThread *thread = checkPlaybackThread_l(output);
812 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000813 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return 0;
815 }
816 return thread->channelCount();
817}
818
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800819audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
821 Mutex::Autolock _l(mLock);
822 PlaybackThread *thread = checkPlaybackThread_l(output);
823 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000824 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800825 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 }
827 return thread->format();
828}
829
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800830size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
832 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800833#ifdef QCOM_HARDWARE
834 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
835 if(desc != NULL) {
836 return desc->stream->common.get_buffer_size(&desc->stream->common);
837 }
838#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 PlaybackThread *thread = checkPlaybackThread_l(output);
840 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000841 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return 0;
843 }
Glenn Kasten58912562012-04-03 10:45:00 -0700844 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
845 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 return thread->frameCount();
847}
848
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800849uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
851 Mutex::Autolock _l(mLock);
852 PlaybackThread *thread = checkPlaybackThread_l(output);
853 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000854 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855 return 0;
856 }
857 return thread->latency();
858}
859
860status_t AudioFlinger::setMasterVolume(float value)
861{
Eric Laurenta1884f92011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
Dorian Snyderf32d5702013-03-01 14:25:46 -0800872#ifdef QCOM_HARDWARE
873 mA2DPHandle = -1;
874#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -0700875 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700876 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700877
John Grossmanee578c02012-07-23 17:05:46 -0700878 // Set master volume in the HALs which support it.
879 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
880 AutoMutex lock(mHardwareLock);
881 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800882
John Grossmanee578c02012-07-23 17:05:46 -0700883 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
884 if (dev->canSetMasterVolume()) {
885 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800886 }
John Grossmanee578c02012-07-23 17:05:46 -0700887 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889
John Grossmanee578c02012-07-23 17:05:46 -0700890 // Now set the master volume in each playback thread. Playback threads
891 // assigned to HALs which do not have master volume support will apply
892 // master volume during the mix operation. Threads with HALs which do
893 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800894 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700895 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896
897 return NO_ERROR;
898}
899
Glenn Kastenf78aee72012-01-04 11:00:47 -0800900status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901{
Eric Laurenta1884f92011-08-23 08:25:03 -0700902 status_t ret = initCheck();
903 if (ret != NO_ERROR) {
904 return ret;
905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906
907 // check calling permissions
908 if (!settingsAllowed()) {
909 return PERMISSION_DENIED;
910 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800911 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000912 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 return BAD_VALUE;
914 }
915
916 { // scope for the lock
917 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700918 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700920 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 mHardwareStatus = AUDIO_HW_IDLE;
922 }
923
924 if (NO_ERROR == ret) {
925 Mutex::Autolock _l(mLock);
926 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800927 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700928 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 }
930
931 return ret;
932}
933
934status_t AudioFlinger::setMicMute(bool state)
935{
Eric Laurenta1884f92011-08-23 08:25:03 -0700936 status_t ret = initCheck();
937 if (ret != NO_ERROR) {
938 return ret;
939 }
940
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 // check calling permissions
942 if (!settingsAllowed()) {
943 return PERMISSION_DENIED;
944 }
945
946 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700947 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700949 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 mHardwareStatus = AUDIO_HW_IDLE;
951 return ret;
952}
953
954bool AudioFlinger::getMicMute() const
955{
Eric Laurenta1884f92011-08-23 08:25:03 -0700956 status_t ret = initCheck();
957 if (ret != NO_ERROR) {
958 return false;
959 }
960
Dima Zavinfce7a472011-04-19 22:30:36 -0700961 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800962 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700963 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700965 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 mHardwareStatus = AUDIO_HW_IDLE;
967 return state;
968}
969
970status_t AudioFlinger::setMasterMute(bool muted)
971{
John Grossmand8f178d2012-07-20 14:51:35 -0700972 status_t ret = initCheck();
973 if (ret != NO_ERROR) {
974 return ret;
975 }
976
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 // check calling permissions
978 if (!settingsAllowed()) {
979 return PERMISSION_DENIED;
980 }
981
John Grossmanee578c02012-07-23 17:05:46 -0700982 Mutex::Autolock _l(mLock);
983 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700984
John Grossmanee578c02012-07-23 17:05:46 -0700985 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100986#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700987 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
988 AutoMutex lock(mHardwareLock);
989 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700990
John Grossmanee578c02012-07-23 17:05:46 -0700991 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
992 if (dev->canSetMasterMute()) {
993 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700994 }
John Grossmanee578c02012-07-23 17:05:46 -0700995 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700996 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100997#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700998
John Grossmanee578c02012-07-23 17:05:46 -0700999 // Now set the master mute in each playback thread. Playback threads
1000 // assigned to HALs which do not have master mute support will apply master
1001 // mute during the mix operation. Threads with HALs which do support master
1002 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001003 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -07001004 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005
1006 return NO_ERROR;
1007}
1008
1009float AudioFlinger::masterVolume() const
1010{
Glenn Kasten98067102011-12-13 11:47:54 -08001011 Mutex::Autolock _l(mLock);
1012 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
1015bool AudioFlinger::masterMute() const
1016{
Glenn Kasten98067102011-12-13 11:47:54 -08001017 Mutex::Autolock _l(mLock);
1018 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019}
1020
John Grossman4ff14ba2012-02-08 16:37:41 -08001021float AudioFlinger::masterVolume_l() const
1022{
John Grossman4ff14ba2012-02-08 16:37:41 -08001023 return mMasterVolume;
1024}
1025
John Grossmand8f178d2012-07-20 14:51:35 -07001026bool AudioFlinger::masterMute_l() const
1027{
John Grossmanee578c02012-07-23 17:05:46 -07001028 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001029}
1030
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001031status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1032 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033{
1034 // check calling permissions
1035 if (!settingsAllowed()) {
1036 return PERMISSION_DENIED;
1037 }
1038
Glenn Kasten263709e2012-01-06 08:40:01 -08001039 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001040 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 return BAD_VALUE;
1042 }
1043
1044 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001045#ifdef QCOM_HARDWARE
1046 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1047 AudioSessionDescriptor *desc = NULL;
1048 if (!mDirectAudioTracks.isEmpty()) {
1049 desc = mDirectAudioTracks.valueFor(output);
1050 if (desc != NULL) {
1051 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1052 if (desc->mStreamType == stream) {
1053 mStreamTypes[stream].volume = value;
Dorian Snyderf32d5702013-03-01 14:25:46 -08001054 desc->mVolumeScale = value;
vivek mehta2192bc92012-12-04 11:46:08 -08001055 desc->stream->set_volume(desc->stream,
1056 desc->mVolumeLeft * mStreamTypes[stream].volume,
1057 desc->mVolumeRight* mStreamTypes[stream].volume);
1058 return NO_ERROR;
1059 }
1060 }
1061 }
1062#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 PlaybackThread *thread = NULL;
1064 if (output) {
1065 thread = checkPlaybackThread_l(output);
1066 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001067#ifdef QCOM_HARDWARE
1068 if (desc != NULL) {
1069 return NO_ERROR;
1070 }
1071#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 return BAD_VALUE;
1073 }
vivek mehta2192bc92012-12-04 11:46:08 -08001074
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
1076
1077 mStreamTypes[stream].volume = value;
1078
1079 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001080 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001081 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 }
1083 } else {
1084 thread->setStreamVolume(stream, value);
1085 }
1086
1087 return NO_ERROR;
1088}
1089
Glenn Kastenfff6d712012-01-12 16:38:12 -08001090status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 // check calling permissions
1093 if (!settingsAllowed()) {
1094 return PERMISSION_DENIED;
1095 }
1096
Glenn Kasten263709e2012-01-06 08:40:01 -08001097 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001098 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001099 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 return BAD_VALUE;
1101 }
1102
Eric Laurent93575202011-01-18 18:39:02 -08001103 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 mStreamTypes[stream].mute = muted;
1105 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001106 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107
1108 return NO_ERROR;
1109}
1110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001111float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
Glenn Kasten263709e2012-01-06 08:40:01 -08001113 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 return 0.0f;
1115 }
1116
1117 AutoMutex lock(mLock);
1118 float volume;
1119 if (output) {
1120 PlaybackThread *thread = checkPlaybackThread_l(output);
1121 if (thread == NULL) {
1122 return 0.0f;
1123 }
1124 volume = thread->streamVolume(stream);
1125 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001126 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
1128
1129 return volume;
1130}
1131
Glenn Kastenfff6d712012-01-12 16:38:12 -08001132bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133{
Glenn Kasten263709e2012-01-06 08:40:01 -08001134 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 return true;
1136 }
1137
Glenn Kasten6637baa2012-01-09 09:40:36 -08001138 AutoMutex lock(mLock);
1139 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140}
1141
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001142status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001144 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1146 // check calling permissions
1147 if (!settingsAllowed()) {
1148 return PERMISSION_DENIED;
1149 }
1150
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 // ioHandle == 0 means the parameters are global to the audio hardware interface
1152 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001153 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001154 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001155 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001156 AutoMutex lock(mHardwareLock);
1157 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1158 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1159 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1160 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1161 final_result = result ?: final_result;
1162 }
1163 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001164 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001165 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1166 AudioParameter param = AudioParameter(keyValuePairs);
1167 String8 value;
1168 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001169 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1170 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001171 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1172 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001173 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001174 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1175 // collect all of the thread's session IDs
1176 KeyedVector<int, bool> ids = thread->sessionIds();
1177 // suspend effects associated with those session IDs
1178 for (size_t j = 0; j < ids.size(); ++j) {
1179 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001180 thread->setEffectSuspended(FX_IID_AEC,
1181 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001182 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001183 thread->setEffectSuspended(FX_IID_NS,
1184 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001185 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001186 }
1187 }
Eric Laurentbee53372011-08-29 12:42:48 -07001188 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001189 }
1190 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001191 String8 screenState;
1192 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1193 bool isOff = screenState == "off";
1194 if (isOff != (gScreenState & 1)) {
1195 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1196 }
1197 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001198 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 }
1200
vivek mehta2192bc92012-12-04 11:46:08 -08001201#ifdef QCOM_HARDWARE
1202 AudioSessionDescriptor *desc = NULL;
1203 if (!mDirectAudioTracks.isEmpty()) {
1204 desc = mDirectAudioTracks.valueFor(ioHandle);
1205 if (desc != NULL) {
1206 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1207 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
Mingming Yin9b3dd172013-01-10 18:42:38 -08001208 AudioParameter param = AudioParameter(keyValuePairs);
1209 String8 key = String8(AudioParameter::keyRouting);
1210 int device;
1211 if (param.getInt(key, device) == NO_ERROR) {
1212 if(mLPAEffectChain != NULL){
1213 mLPAEffectChain->setDevice_l(device);
1214 audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1215 }
1216 }
vivek mehta2192bc92012-12-04 11:46:08 -08001217 }
1218 }
1219#endif
1220
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1222 // and the thread is exited once the lock is released
1223 sp<ThreadBase> thread;
1224 {
1225 Mutex::Autolock _l(mLock);
1226 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001227 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001229 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001230 // indicate output device change to all input threads for pre processing
1231 AudioParameter param = AudioParameter(keyValuePairs);
1232 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001233 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1234 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001235 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1236 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001237 for (size_t i = 0; i < recordThreads.size(); i++) {
1238 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001239 }
1240 }
vivek mehta2192bc92012-12-04 11:46:08 -08001241 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 }
vivek mehta2192bc92012-12-04 11:46:08 -08001243 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001245 if (thread != 0) {
1246 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 }
1248 return BAD_VALUE;
1249}
1250
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001251String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001253// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1255
Eric Laurenta4c5a552012-03-29 10:12:40 -07001256 Mutex::Autolock _l(mLock);
1257
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001259 String8 out_s8;
1260
Dima Zavin799a70e2011-04-18 16:57:27 -07001261 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001262 char *s;
1263 {
1264 AutoMutex lock(mHardwareLock);
1265 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001266 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001267 s = dev->get_parameters(dev, keys.string());
1268 mHardwareStatus = AUDIO_HW_IDLE;
1269 }
John Grossmanef7740b2012-02-09 11:28:36 -08001270 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001271 free(s);
1272 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001273 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 }
1275
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1277 if (playbackThread != NULL) {
1278 return playbackThread->getParameters(keys);
1279 }
1280 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1281 if (recordThread != NULL) {
1282 return recordThread->getParameters(keys);
1283 }
1284 return String8("");
1285}
1286
Glenn Kastendd8104c2012-07-02 12:42:44 -07001287size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1288 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289{
Eric Laurenta1884f92011-08-23 08:25:03 -07001290 status_t ret = initCheck();
1291 if (ret != NO_ERROR) {
1292 return 0;
1293 }
1294
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001295 AutoMutex lock(mHardwareLock);
1296 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001297 struct audio_config config = {
1298 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001299 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001300 format: format,
1301 };
John Grossmanee578c02012-07-23 17:05:46 -07001302 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001303#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001304 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001305#else
1306 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1307#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001308 mHardwareStatus = AUDIO_HW_IDLE;
1309 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310}
1311
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001312unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314 Mutex::Autolock _l(mLock);
1315
1316 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1317 if (recordThread != NULL) {
1318 return recordThread->getInputFramesLost();
1319 }
1320 return 0;
1321}
1322
1323status_t AudioFlinger::setVoiceVolume(float value)
1324{
Eric Laurenta1884f92011-08-23 08:25:03 -07001325 status_t ret = initCheck();
1326 if (ret != NO_ERROR) {
1327 return ret;
1328 }
1329
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330 // check calling permissions
1331 if (!settingsAllowed()) {
1332 return PERMISSION_DENIED;
1333 }
1334
1335 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001336 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001337 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001338 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 mHardwareStatus = AUDIO_HW_IDLE;
1340
1341 return ret;
1342}
1343
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001344status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1345 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001346{
1347 status_t status;
1348
1349 Mutex::Autolock _l(mLock);
1350
1351 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1352 if (playbackThread != NULL) {
1353 return playbackThread->getRenderPosition(halFrames, dspFrames);
1354 }
1355
1356 return BAD_VALUE;
1357}
1358
1359void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1360{
1361
1362 Mutex::Autolock _l(mLock);
1363
vivek mehta2192bc92012-12-04 11:46:08 -08001364 sp<IBinder> binder = client->asBinder();
1365 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366 sp<NotificationClient> notificationClient = new NotificationClient(this,
1367 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001368 binder);
Dorian Snyderf32d5702013-03-01 14:25:46 -08001369 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370
vivek mehta2192bc92012-12-04 11:46:08 -08001371 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372
1373 sp<IBinder> binder = client->asBinder();
1374 binder->linkToDeath(notificationClient);
1375
1376 // the config change is always sent from playback or record threads to avoid deadlock
1377 // with AudioSystem::gLock
1378 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001379 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 }
1381
1382 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001383 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 }
1385 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08001386#ifdef QCOM_HARDWARE
1387 // Send the notification to the client only once.
1388 if (mA2DPHandle != -1) {
1389 ALOGV("A2DP active. Notifying the registered client");
1390 client->ioConfigChanged(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
1391 }
1392#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393}
1394
vivek mehta2192bc92012-12-04 11:46:08 -08001395#ifdef QCOM_HARDWARE
1396status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1397{
1398 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1399 Mutex::Autolock _l(mLock);
1400
1401 sp<IBinder> binder = client->asBinder();
1402 int index = mNotificationClients.indexOfKey(binder);
1403 if (index >= 0) {
1404 mNotificationClients.removeItemsAt(index);
1405 return true;
1406 }
1407
1408 return false;
1409}
1410#endif
1411
1412void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413{
1414 Mutex::Autolock _l(mLock);
1415
vivek mehta2192bc92012-12-04 11:46:08 -08001416 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001417
vivek mehta2192bc92012-12-04 11:46:08 -08001418 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001419 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001420 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001421 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001422 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001423 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001424 ALOGV(" pid %d @ %d", ref->mPid, i);
1425 if (ref->mPid == pid) {
1426 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001427 mAudioSessionRefs.removeAt(i);
1428 delete ref;
1429 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001430 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001431 } else {
1432 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001433 }
1434 }
1435 if (removed) {
1436 purgeStaleEffects_l();
1437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438}
1439
1440// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001441void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442{
vivek mehta2192bc92012-12-04 11:46:08 -08001443#ifdef QCOM_HARDWARE
1444 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1445 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1446 mIsEffectConfigChanged = true;
1447 }
1448#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449 size_t size = mNotificationClients.size();
1450 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001451 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1452 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 }
1454}
1455
1456// removeClient_l() must be called with AudioFlinger::mLock held
1457void AudioFlinger::removeClient_l(pid_t pid)
1458{
Steve Block3856b092011-10-20 11:56:00 +01001459 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 mClients.removeItem(pid);
1461}
1462
Eric Laurent717e1282012-06-29 16:36:52 -07001463// getEffectThread_l() must be called with AudioFlinger::mLock held
1464sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1465{
1466 sp<PlaybackThread> thread;
1467
1468 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1469 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1470 ALOG_ASSERT(thread == 0);
1471 thread = mPlaybackThreads.valueAt(i);
1472 }
1473 }
1474
1475 return thread;
1476}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477
1478// ----------------------------------------------------------------------------
1479
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001480AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001481 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001482 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001483 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001484 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001485 // mChannelMask
1486 mChannelCount(0),
1487 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1488 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001489 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1490 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001491 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001492 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493{
1494}
1495
1496AudioFlinger::ThreadBase::~ThreadBase()
1497{
1498 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001499 // do not lock the mutex in destructor
1500 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001501 if (mPowerManager != 0) {
1502 sp<IBinder> binder = mPowerManager->asBinder();
1503 binder->unlinkToDeath(mDeathRecipient);
1504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505}
1506
1507void AudioFlinger::ThreadBase::exit()
1508{
Steve Block3856b092011-10-20 11:56:00 +01001509 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001510 // do any cleanup required for exit to succeed
1511 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001513 // This lock prevents the following race in thread (uniprocessor for illustration):
1514 // if (!exitPending()) {
1515 // // context switch from here to exit()
1516 // // exit() calls requestExit(), what exitPending() observes
1517 // // exit() calls signal(), which is dropped since no waiters
1518 // // context switch back from exit() to here
1519 // mWaitWorkCV.wait(...);
1520 // // now thread is hung
1521 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001522 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001524 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001526 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1527 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 requestExitAndWait();
1529}
1530
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1532{
1533 status_t status;
1534
Steve Block3856b092011-10-20 11:56:00 +01001535 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 Mutex::Autolock _l(mLock);
1537
1538 mNewParameters.add(keyValuePairs);
1539 mWaitWorkCV.signal();
1540 // wait condition with timeout in case the thread loop has exited
1541 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001542 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 status = mParamStatus;
1544 mWaitWorkCV.signal();
1545 } else {
1546 status = TIMED_OUT;
1547 }
1548 return status;
1549}
1550
vivek mehta2192bc92012-12-04 11:46:08 -08001551#ifdef QCOM_HARDWARE
1552void AudioFlinger::ThreadBase::effectConfigChanged() {
1553 mAudioFlinger->mLock.lock();
1554 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1555 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1556 mAudioFlinger->mLock.unlock();
1557}
1558#endif
1559
Eric Laurent896adcd2012-09-13 11:18:23 -07001560void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561{
1562 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001563 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564}
1565
Eric Laurent896adcd2012-09-13 11:18:23 -07001566// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1567void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568{
Eric Laurent896adcd2012-09-13 11:18:23 -07001569 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1570 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1571 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1572 mWaitWorkCV.signal();
1573}
1574
1575// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1576void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1577{
1578 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1579 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1580 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1581 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 mWaitWorkCV.signal();
1583}
1584
1585void AudioFlinger::ThreadBase::processConfigEvents()
1586{
1587 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001588 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001589 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001590 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 mConfigEvents.removeAt(0);
1592 // release mLock before locking AudioFlinger mLock: lock order is always
1593 // AudioFlinger then ThreadBase to avoid cross deadlock
1594 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001595 switch(event->type()) {
1596 case CFG_EVENT_PRIO: {
1597 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1598 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1599 if (err != 0) {
1600 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1601 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1602 }
1603 } break;
1604 case CFG_EVENT_IO: {
1605 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1606 mAudioFlinger->mLock.lock();
1607 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1608 mAudioFlinger->mLock.unlock();
1609 } break;
1610 default:
1611 ALOGE("processConfigEvents() unknown event type %d", event->type());
1612 break;
1613 }
1614 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 mLock.lock();
1616 }
1617 mLock.unlock();
1618}
1619
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001620void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621{
1622 const size_t SIZE = 256;
1623 char buffer[SIZE];
1624 String8 result;
1625
1626 bool locked = tryLock(mLock);
1627 if (!locked) {
1628 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1629 write(fd, buffer, strlen(buffer));
1630 }
1631
Eric Laurent612bbb52012-03-14 15:03:26 -07001632 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1633 result.append(buffer);
1634 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1635 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1637 result.append(buffer);
1638 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1639 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001640 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1641 result.append(buffer);
1642 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 result.append(buffer);
1644 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1645 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001646 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1647 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1649 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001650 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 result.append(buffer);
1652
1653 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1654 result.append(buffer);
1655 result.append(" Index Command");
1656 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1657 snprintf(buffer, SIZE, "\n %02d ", i);
1658 result.append(buffer);
1659 result.append(mNewParameters[i]);
1660 }
1661
1662 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1663 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001665 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 result.append(buffer);
1667 }
1668 result.append("\n");
1669
1670 write(fd, result.string(), result.size());
1671
1672 if (locked) {
1673 mLock.unlock();
1674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675}
1676
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001677void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001678{
1679 const size_t SIZE = 256;
1680 char buffer[SIZE];
1681 String8 result;
1682
1683 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1684 write(fd, buffer, strlen(buffer));
1685
1686 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1687 sp<EffectChain> chain = mEffectChains[i];
1688 if (chain != 0) {
1689 chain->dump(fd, args);
1690 }
1691 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001692}
1693
Eric Laurentfeb0db62011-07-22 09:04:31 -07001694void AudioFlinger::ThreadBase::acquireWakeLock()
1695{
1696 Mutex::Autolock _l(mLock);
1697 acquireWakeLock_l();
1698}
1699
1700void AudioFlinger::ThreadBase::acquireWakeLock_l()
1701{
1702 if (mPowerManager == 0) {
1703 // use checkService() to avoid blocking if power service is not up yet
1704 sp<IBinder> binder =
1705 defaultServiceManager()->checkService(String16("power"));
1706 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001707 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001708 } else {
1709 mPowerManager = interface_cast<IPowerManager>(binder);
1710 binder->linkToDeath(mDeathRecipient);
1711 }
1712 }
1713 if (mPowerManager != 0) {
1714 sp<IBinder> binder = new BBinder();
1715 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1716 binder,
1717 String16(mName));
1718 if (status == NO_ERROR) {
1719 mWakeLockToken = binder;
1720 }
Steve Block3856b092011-10-20 11:56:00 +01001721 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001722 }
1723}
1724
1725void AudioFlinger::ThreadBase::releaseWakeLock()
1726{
1727 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001728 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001729}
1730
1731void AudioFlinger::ThreadBase::releaseWakeLock_l()
1732{
1733 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001734 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001735 if (mPowerManager != 0) {
1736 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1737 }
1738 mWakeLockToken.clear();
1739 }
1740}
1741
1742void AudioFlinger::ThreadBase::clearPowerManager()
1743{
1744 Mutex::Autolock _l(mLock);
1745 releaseWakeLock_l();
1746 mPowerManager.clear();
1747}
1748
1749void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1750{
1751 sp<ThreadBase> thread = mThread.promote();
1752 if (thread != 0) {
1753 thread->clearPowerManager();
1754 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001755 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001756}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001757
Eric Laurent59255e42011-07-27 19:49:51 -07001758void AudioFlinger::ThreadBase::setEffectSuspended(
1759 const effect_uuid_t *type, bool suspend, int sessionId)
1760{
1761 Mutex::Autolock _l(mLock);
1762 setEffectSuspended_l(type, suspend, sessionId);
1763}
1764
1765void AudioFlinger::ThreadBase::setEffectSuspended_l(
1766 const effect_uuid_t *type, bool suspend, int sessionId)
1767{
Glenn Kasten090f0192012-01-30 13:00:02 -08001768 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001769 if (chain != 0) {
1770 if (type != NULL) {
1771 chain->setEffectSuspended_l(type, suspend);
1772 } else {
1773 chain->setEffectSuspendedAll_l(suspend);
1774 }
1775 }
1776
1777 updateSuspendedSessions_l(type, suspend, sessionId);
1778}
1779
1780void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1781{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001782 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001783 if (index < 0) {
1784 return;
1785 }
1786
Glenn Kasten0a7af182012-07-09 16:09:19 -07001787 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1788 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001789
1790 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001791 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001792 for (int j = 0; j < desc->mRefCount; j++) {
1793 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1794 chain->setEffectSuspendedAll_l(true);
1795 } else {
Steve Block3856b092011-10-20 11:56:00 +01001796 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001797 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001798 chain->setEffectSuspended_l(&desc->mType, true);
1799 }
1800 }
1801 }
1802}
1803
Eric Laurent59255e42011-07-27 19:49:51 -07001804void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1805 bool suspend,
1806 int sessionId)
1807{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001808 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001809
1810 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1811
1812 if (suspend) {
1813 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001814 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001815 } else {
1816 mSuspendedSessions.add(sessionId, sessionEffects);
1817 }
1818 } else {
1819 if (index < 0) {
1820 return;
1821 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001822 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001823 }
1824
1825
1826 int key = EffectChain::kKeyForSuspendAll;
1827 if (type != NULL) {
1828 key = type->timeLow;
1829 }
1830 index = sessionEffects.indexOfKey(key);
1831
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001832 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001833 if (suspend) {
1834 if (index >= 0) {
1835 desc = sessionEffects.valueAt(index);
1836 } else {
1837 desc = new SuspendedSessionDesc();
1838 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001839 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001840 }
1841 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001842 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001843 }
1844 desc->mRefCount++;
1845 } else {
1846 if (index < 0) {
1847 return;
1848 }
1849 desc = sessionEffects.valueAt(index);
1850 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001851 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001852 sessionEffects.removeItemsAt(index);
1853 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001854 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001855 sessionId);
1856 mSuspendedSessions.removeItem(sessionId);
1857 }
1858 }
1859 }
1860 if (!sessionEffects.isEmpty()) {
1861 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1862 }
1863}
1864
1865void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1866 bool enabled,
1867 int sessionId)
1868{
1869 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001870 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1871}
Eric Laurent59255e42011-07-27 19:49:51 -07001872
Eric Laurenta85a74a2011-10-19 11:44:54 -07001873void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1874 bool enabled,
1875 int sessionId)
1876{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001877 if (mType != RECORD) {
1878 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1879 // another session. This gives the priority to well behaved effect control panels
1880 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001881 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1882 // global effects
1883 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001884 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1885 }
1886 }
Eric Laurent59255e42011-07-27 19:49:51 -07001887
1888 sp<EffectChain> chain = getEffectChain_l(sessionId);
1889 if (chain != 0) {
1890 chain->checkSuspendOnEffectEnabled(effect, enabled);
1891 }
1892}
1893
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894// ----------------------------------------------------------------------------
1895
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001896AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1897 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001898 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001899 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001900 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001901 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001902 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001903 // mStreamTypes[] initialized in constructor body
1904 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001905 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001906 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001907 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001908 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001909 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001910 // index 0 is reserved for normal mixer's submix
1911 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912{
Glenn Kasten480b4682012-02-28 12:30:08 -08001913 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001914
John Grossmanee578c02012-07-23 17:05:46 -07001915 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1916 // it would be safer to explicitly pass initial masterVolume/masterMute as
1917 // parameter.
1918 //
1919 // If the HAL we are using has support for master volume or master mute,
1920 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1921 // and the mute set to false).
1922 mMasterVolume = audioFlinger->masterVolume_l();
1923 mMasterMute = audioFlinger->masterMute_l();
1924 if (mOutput && mOutput->audioHwDev) {
1925 if (mOutput->audioHwDev->canSetMasterVolume()) {
1926 mMasterVolume = 1.0;
1927 }
1928
1929 if (mOutput->audioHwDev->canSetMasterMute()) {
1930 mMasterMute = false;
1931 }
1932 }
1933
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 readOutputParameters();
1935
Glenn Kasten263709e2012-01-06 08:40:01 -08001936 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001937 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1938 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1939 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001940 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1941 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001943 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1944 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945}
1946
1947AudioFlinger::PlaybackThread::~PlaybackThread()
1948{
1949 delete [] mMixBuffer;
1950}
1951
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001952void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953{
1954 dumpInternals(fd, args);
1955 dumpTracks(fd, args);
1956 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957}
1958
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001959void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960{
1961 const size_t SIZE = 256;
1962 char buffer[SIZE];
1963 String8 result;
1964
Glenn Kasten58912562012-04-03 10:45:00 -07001965 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1966 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1967 const stream_type_t *st = &mStreamTypes[i];
1968 if (i > 0) {
1969 result.appendFormat(", ");
1970 }
1971 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1972 if (st->mute) {
1973 result.append("M");
1974 }
1975 }
1976 result.append("\n");
1977 write(fd, result.string(), result.length());
1978 result.clear();
1979
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1981 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001982 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 for (size_t i = 0; i < mTracks.size(); ++i) {
1984 sp<Track> track = mTracks[i];
1985 if (track != 0) {
1986 track->dump(buffer, SIZE);
1987 result.append(buffer);
1988 }
1989 }
1990
1991 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1992 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001993 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001995 sp<Track> track = mActiveTracks[i].promote();
1996 if (track != 0) {
1997 track->dump(buffer, SIZE);
1998 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 }
2000 }
2001 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07002002
2003 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2004 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
2005 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
2006 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007}
2008
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002009void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010{
2011 const size_t SIZE = 256;
2012 char buffer[SIZE];
2013 String8 result;
2014
2015 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
2016 result.append(buffer);
2017 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
2018 result.append(buffer);
2019 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
2020 result.append(buffer);
2021 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
2022 result.append(buffer);
2023 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
2024 result.append(buffer);
2025 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
2026 result.append(buffer);
2027 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
2028 result.append(buffer);
2029 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002030 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031
2032 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033}
2034
2035// Thread virtuals
2036status_t AudioFlinger::PlaybackThread::readyToRun()
2037{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002038 status_t status = initCheck();
2039 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002040 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002041 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002042 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002044 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045}
2046
2047void AudioFlinger::PlaybackThread::onFirstRef()
2048{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002049 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050}
2051
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002052// ThreadBase virtuals
2053void AudioFlinger::PlaybackThread::preExit()
2054{
2055 ALOGV(" preExit()");
2056 // FIXME this is using hard-coded strings but in the future, this functionality will be
2057 // converted to use audio HAL extensions required to support tunneling
2058 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2059}
2060
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002062sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002064 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002066 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002067 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 int frameCount,
2069 const sp<IMemory>& sharedBuffer,
2070 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002071 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002072 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 status_t *status)
2074{
2075 sp<Track> track;
2076 status_t lStatus;
2077
Glenn Kasten73d22752012-03-19 13:38:30 -07002078 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2079
2080 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002081 if (flags & IAudioFlinger::TRACK_FAST) {
2082 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002083 // not timed
2084 (!isTimed) &&
2085 // either of these use cases:
2086 (
2087 // use case 1: shared buffer with any frame count
2088 (
2089 (sharedBuffer != 0)
2090 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002091 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002092 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002093 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002094 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002095 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002096 )
2097 ) &&
2098 // PCM data
2099 audio_is_linear_pcm(format) &&
2100 // mono or stereo
2101 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2102 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002103#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002104 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002105 (sampleRate == mSampleRate) &&
2106#endif
2107 // normal mixer has an associated fast mixer
2108 hasFastMixer() &&
2109 // there are sufficient fast track slots available
2110 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002111 // FIXME test that MixerThread for this fast track has a capable output HAL
2112 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002113 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002114 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2115 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002116 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002117 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002118 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002119 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002120 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002121 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002122 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002123 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2124 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2125 audio_is_linear_pcm(format),
2126 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002127 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002128 // For compatibility with AudioTrack calculation, buffer depth is forced
2129 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2130 // This is probably too conservative, but legacy application code may depend on it.
2131 // If you change this calculation, also review the start threshold which is related.
2132 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2133 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2134 if (minBufCount < 2) {
2135 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002136 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002137 int minFrameCount = mNormalFrameCount * minBufCount;
2138 if (frameCount < minFrameCount) {
2139 frameCount = minFrameCount;
2140 }
2141 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002142 }
2143
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002145 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2146 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002147 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002148 "for output %p with format %d",
2149 sampleRate, format, channelMask, mOutput, mFormat);
2150 lStatus = BAD_VALUE;
2151 goto Exit;
2152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 }
2154 } else {
2155 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2156 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002157 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 lStatus = BAD_VALUE;
2159 goto Exit;
2160 }
2161 }
2162
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002163 lStatus = initCheck();
2164 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002165 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 goto Exit;
2167 }
2168
2169 { // scope for mLock
2170 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002171
2172 // all tracks in same audio session must share the same routing strategy otherwise
2173 // conflicts will happen when tracks are moved from one output to another by audio policy
2174 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002175 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002176 for (size_t i = 0; i < mTracks.size(); ++i) {
2177 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002178 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002179 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002180 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002181 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002182 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002183 lStatus = BAD_VALUE;
2184 goto Exit;
2185 }
2186 }
2187 }
2188
John Grossman4ff14ba2012-02-08 16:37:41 -08002189 if (!isTimed) {
2190 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002191 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002192 } else {
2193 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2194 channelMask, frameCount, sharedBuffer, sessionId);
2195 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002196 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 lStatus = NO_MEMORY;
2198 goto Exit;
2199 }
2200 mTracks.add(track);
2201
2202 sp<EffectChain> chain = getEffectChain_l(sessionId);
2203 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002204 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002206 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002207 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002208 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002209
Eric Laurent896adcd2012-09-13 11:18:23 -07002210 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2211 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2212 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2213 // so ask activity manager to do this on our behalf
2214 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002215 }
2216 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002217
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218 lStatus = NO_ERROR;
2219
2220Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002221 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 *status = lStatus;
2223 }
2224 return track;
2225}
2226
Eric Laurente737cda2012-05-22 18:55:44 -07002227uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2228{
2229 if (mFastMixer != NULL) {
2230 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2231 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2232 }
2233 return latency;
2234}
2235
2236uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2237{
2238 return latency;
2239}
2240
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241uint32_t AudioFlinger::PlaybackThread::latency() const
2242{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002243 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002244 return latency_l();
2245}
2246uint32_t AudioFlinger::PlaybackThread::latency_l() const
2247{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002248 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002249 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002250 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 return 0;
2252 }
2253}
2254
Glenn Kasten6637baa2012-01-09 09:40:36 -08002255void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002257 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002258 // Don't apply master volume in SW if our HAL can do it for us.
2259 if (mOutput && mOutput->audioHwDev &&
2260 mOutput->audioHwDev->canSetMasterVolume()) {
2261 mMasterVolume = 1.0;
2262 } else {
2263 mMasterVolume = value;
2264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265}
2266
Glenn Kasten6637baa2012-01-09 09:40:36 -08002267void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002269 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002270 // Don't apply master mute in SW if our HAL can do it for us.
2271 if (mOutput && mOutput->audioHwDev &&
2272 mOutput->audioHwDev->canSetMasterMute()) {
2273 mMasterMute = false;
2274 } else {
2275 mMasterMute = muted;
2276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277}
2278
Glenn Kasten6637baa2012-01-09 09:40:36 -08002279void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002281 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283}
2284
Glenn Kasten6637baa2012-01-09 09:40:36 -08002285void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002287 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289}
2290
Glenn Kastenfff6d712012-01-12 16:38:12 -08002291float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002293 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 return mStreamTypes[stream].volume;
2295}
2296
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297// addTrack_l() must be called with ThreadBase::mLock held
2298status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2299{
2300 status_t status = ALREADY_EXISTS;
2301
2302 // set retry count for buffer fill
2303 track->mRetryCount = kMaxTrackStartupRetries;
2304 if (mActiveTracks.indexOf(track) < 0) {
2305 // the track is newly added, make sure it fills up all its
2306 // buffers before playing. This is to ensure the client will
2307 // effectively get the latency it requested.
2308 track->mFillingUpStatus = Track::FS_FILLING;
2309 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002310 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 mActiveTracks.add(track);
2312 if (track->mainBuffer() != mMixBuffer) {
2313 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2314 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002315 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002316 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317 }
2318 }
2319
2320 status = NO_ERROR;
2321 }
2322
Steve Block3856b092011-10-20 11:56:00 +01002323 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 mWaitWorkCV.broadcast();
2325
2326 return status;
2327}
2328
2329// destroyTrack_l() must be called with ThreadBase::mLock held
2330void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2331{
2332 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002333 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002335 removeTrack_l(track);
2336 }
2337}
2338
2339void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2340{
Eric Laurent29864602012-05-08 18:57:51 -07002341 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002342 mTracks.remove(track);
2343 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002344 // redundant as track is about to be destroyed, for dumpsys only
2345 track->mName = -1;
2346 if (track->isFastTrack()) {
2347 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002348 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002349 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2350 mFastTrackAvailMask |= 1 << index;
2351 // redundant as track is about to be destroyed, for dumpsys only
2352 track->mFastIndex = -1;
2353 }
Eric Laurentb469b942011-05-09 12:09:06 -07002354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2355 if (chain != 0) {
2356 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358}
2359
2360String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2361{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002362 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002363 char *s;
2364
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002365 Mutex::Autolock _l(mLock);
2366 if (initCheck() != NO_ERROR) {
2367 return out_s8;
2368 }
2369
Dima Zavin799a70e2011-04-18 16:57:27 -07002370 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002371 out_s8 = String8(s);
2372 free(s);
2373 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374}
2375
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002376// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2378 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002379 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380
Steve Block3856b092011-10-20 11:56:00 +01002381 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382
2383 switch (event) {
2384 case AudioSystem::OUTPUT_OPENED:
2385 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002386 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 desc.samplingRate = mSampleRate;
2388 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002389 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 desc.latency = latency();
2391 param2 = &desc;
2392 break;
2393
2394 case AudioSystem::STREAM_CONFIG_CHANGED:
2395 param2 = &param;
2396 case AudioSystem::OUTPUT_CLOSED:
2397 default:
2398 break;
2399 }
2400 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2401}
2402
2403void AudioFlinger::PlaybackThread::readOutputParameters()
2404{
Dima Zavin799a70e2011-04-18 16:57:27 -07002405 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002406 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2407 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002408 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002409 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002410 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002411 if (mFrameCount & 15) {
2412 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2413 mFrameCount);
2414 }
2415
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002416 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002417 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002418 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002419 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002420 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2421 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2422 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2423 maxNormalFrameCount = maxNormalFrameCount & ~15;
2424 if (maxNormalFrameCount < minNormalFrameCount) {
2425 maxNormalFrameCount = minNormalFrameCount;
2426 }
2427 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2428 if (multiplier <= 1.0) {
2429 multiplier = 1.0;
2430 } else if (multiplier <= 2.0) {
2431 if (2 * mFrameCount <= maxNormalFrameCount) {
2432 multiplier = 2.0;
2433 } else {
2434 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2435 }
2436 } else {
2437 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2438 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2439 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2440 // FIXME this rounding up should not be done if no HAL SRC
2441 uint32_t truncMult = (uint32_t) multiplier;
2442 if ((truncMult & 1)) {
2443 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2444 ++truncMult;
2445 }
2446 }
2447 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002448 }
Glenn Kasten58912562012-04-03 10:45:00 -07002449 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002450 mNormalFrameCount = multiplier * mFrameCount;
2451 // round up to nearest 16 frames to satisfy AudioMixer
2452 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002453 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
Glenn Kastene9dd0172012-01-27 18:08:45 -08002455 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002456 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2457 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458
Eric Laurentde070132010-07-13 04:45:46 -07002459 // force reconfiguration of effect chains and engines to take new buffer size and audio
2460 // parameters into account
2461 // Note that mLock is not held when readOutputParameters() is called from the constructor
2462 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2463 // matter.
2464 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2465 Vector< sp<EffectChain> > effectChains = mEffectChains;
2466 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002467 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469}
2470
Eric Laurente737cda2012-05-22 18:55:44 -07002471
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2473{
Glenn Kastena0d68332012-01-27 16:47:15 -08002474 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 return BAD_VALUE;
2476 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002477 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002478 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 return INVALID_OPERATION;
2480 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002481 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482
Eric Laurent1afc26d2012-09-23 15:20:50 -07002483 if (isSuspended()) {
2484 // return an estimation of rendered frames when the output is suspended
2485 int32_t frames = mBytesWritten - latency_l();
2486 if (frames < 0) {
2487 frames = 0;
2488 }
2489 *dspFrames = (uint32_t)frames;
2490 return NO_ERROR;
2491 } else {
2492 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494}
2495
Glenn Kasten106e8a42012-08-02 13:37:12 -07002496uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497{
2498 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002499 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002501 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 }
2503
2504 for (size_t i = 0; i < mTracks.size(); ++i) {
2505 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002506 if (sessionId == track->sessionId() &&
2507 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002508 result |= TRACK_SESSION;
2509 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 }
2511 }
2512
Eric Laurent39e94f82010-07-28 01:32:47 -07002513 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514}
2515
Eric Laurentde070132010-07-13 04:45:46 -07002516uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2517{
Dima Zavinfce7a472011-04-19 22:30:36 -07002518 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002519 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002520 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2521 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002522 }
2523 for (size_t i = 0; i < mTracks.size(); i++) {
2524 sp<Track> track = mTracks[i];
2525 if (sessionId == track->sessionId() &&
2526 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002527 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002528 }
2529 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002530 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002531}
2532
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533
Glenn Kastenaed850d2012-01-26 09:46:34 -08002534AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002535{
2536 Mutex::Autolock _l(mLock);
2537 return mOutput;
2538}
2539
2540AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2541{
2542 Mutex::Autolock _l(mLock);
2543 AudioStreamOut *output = mOutput;
2544 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002545 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2546 // must push a NULL and wait for ack
2547 mOutputSink.clear();
2548 mPipeSink.clear();
2549 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002550 return output;
2551}
2552
2553// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002554audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002555{
2556 if (mOutput == NULL) {
2557 return NULL;
2558 }
2559 return &mOutput->stream->common;
2560}
2561
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002562uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002563{
Eric Laurentab9071b2012-06-04 13:45:29 -07002564 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002565}
2566
Eric Laurenta011e352012-03-29 15:51:43 -07002567status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2568{
2569 if (!isValidSyncEvent(event)) {
2570 return BAD_VALUE;
2571 }
2572
2573 Mutex::Autolock _l(mLock);
2574
2575 for (size_t i = 0; i < mTracks.size(); ++i) {
2576 sp<Track> track = mTracks[i];
2577 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002578 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002579 return NO_ERROR;
2580 }
2581 }
2582
2583 return NAME_NOT_FOUND;
2584}
2585
Glenn Kasten106e8a42012-08-02 13:37:12 -07002586bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002587{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002588 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002589}
2590
Eric Laurent44a957f2012-05-15 15:26:05 -07002591void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2592{
2593 size_t count = tracksToRemove.size();
2594 if (CC_UNLIKELY(count)) {
2595 for (size_t i = 0 ; i < count ; i++) {
2596 const sp<Track>& track = tracksToRemove.itemAt(i);
2597 if ((track->sharedBuffer() != 0) &&
2598 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2599 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2600 }
2601 }
2602 }
2603
2604}
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606// ----------------------------------------------------------------------------
2607
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002608AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002609 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002610 : PlaybackThread(audioFlinger, output, id, device, type),
2611 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002612 // mFastMixer below
2613 mFastMixerFutex(0)
2614 // mOutputSink below
2615 // mPipeSink below
2616 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002618 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002619 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002620 "mFrameCount=%d, mNormalFrameCount=%d",
2621 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2622 mNormalFrameCount);
2623 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2624
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002626 if (mChannelCount != FCC_2) {
2627 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
Glenn Kasten58912562012-04-03 10:45:00 -07002629
2630 // create an NBAIO sink for the HAL output stream, and negotiate
2631 mOutputSink = new AudioStreamOutSink(output->stream);
2632 size_t numCounterOffers = 0;
2633 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2634 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2635 ALOG_ASSERT(index == 0);
2636
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002637 // initialize fast mixer depending on configuration
2638 bool initFastMixer;
2639 switch (kUseFastMixer) {
2640 case FastMixer_Never:
2641 initFastMixer = false;
2642 break;
2643 case FastMixer_Always:
2644 initFastMixer = true;
2645 break;
2646 case FastMixer_Static:
2647 case FastMixer_Dynamic:
2648 initFastMixer = mFrameCount < mNormalFrameCount;
2649 break;
2650 }
2651 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002652
2653 // create a MonoPipe to connect our submix to FastMixer
2654 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002655 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2656 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2657 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2658 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002659 const NBAIO_Format offers[1] = {format};
2660 size_t numCounterOffers = 0;
2661 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2662 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002663 monoPipe->setAvgFrames((mScreenState & 1) ?
2664 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002665 mPipeSink = monoPipe;
2666
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002667#ifdef TEE_SINK_FRAMES
2668 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2669 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2670 numCounterOffers = 0;
2671 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2672 ALOG_ASSERT(index == 0);
2673 mTeeSink = teeSink;
2674 PipeReader *teeSource = new PipeReader(*teeSink);
2675 numCounterOffers = 0;
2676 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2677 ALOG_ASSERT(index == 0);
2678 mTeeSource = teeSource;
2679#endif
2680
Glenn Kasten58912562012-04-03 10:45:00 -07002681 // create fast mixer and configure it initially with just one fast track for our submix
2682 mFastMixer = new FastMixer();
2683 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002684#ifdef STATE_QUEUE_DUMP
2685 sq->setObserverDump(&mStateQueueObserverDump);
2686 sq->setMutatorDump(&mStateQueueMutatorDump);
2687#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002688 FastMixerState *state = sq->begin();
2689 FastTrack *fastTrack = &state->mFastTracks[0];
2690 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2691 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2692 fastTrack->mVolumeProvider = NULL;
2693 fastTrack->mGeneration++;
2694 state->mFastTracksGen++;
2695 state->mTrackMask = 1;
2696 // fast mixer will use the HAL output sink
2697 state->mOutputSink = mOutputSink.get();
2698 state->mOutputSinkGen++;
2699 state->mFrameCount = mFrameCount;
2700 state->mCommand = FastMixerState::COLD_IDLE;
2701 // already done in constructor initialization list
2702 //mFastMixerFutex = 0;
2703 state->mColdFutexAddr = &mFastMixerFutex;
2704 state->mColdGen++;
2705 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002706 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002707 sq->end();
2708 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2709
2710 // start the fast mixer
2711 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002712 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002713 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002714 if (err != 0) {
2715 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002716 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002717 }
Glenn Kasten58912562012-04-03 10:45:00 -07002718
Glenn Kastenc15d6652012-05-30 14:52:57 -07002719#ifdef AUDIO_WATCHDOG
2720 // create and start the watchdog
2721 mAudioWatchdog = new AudioWatchdog();
2722 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2723 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2724 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002725 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002726 if (err != 0) {
2727 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002728 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002729 }
2730#endif
2731
Glenn Kasten58912562012-04-03 10:45:00 -07002732 } else {
2733 mFastMixer = NULL;
2734 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002735
2736 switch (kUseFastMixer) {
2737 case FastMixer_Never:
2738 case FastMixer_Dynamic:
2739 mNormalSink = mOutputSink;
2740 break;
2741 case FastMixer_Always:
2742 mNormalSink = mPipeSink;
2743 break;
2744 case FastMixer_Static:
2745 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2746 break;
2747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748}
2749
2750AudioFlinger::MixerThread::~MixerThread()
2751{
Glenn Kasten58912562012-04-03 10:45:00 -07002752 if (mFastMixer != NULL) {
2753 FastMixerStateQueue *sq = mFastMixer->sq();
2754 FastMixerState *state = sq->begin();
2755 if (state->mCommand == FastMixerState::COLD_IDLE) {
2756 int32_t old = android_atomic_inc(&mFastMixerFutex);
2757 if (old == -1) {
2758 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2759 }
2760 }
2761 state->mCommand = FastMixerState::EXIT;
2762 sq->end();
2763 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2764 mFastMixer->join();
2765 // Though the fast mixer thread has exited, it's state queue is still valid.
2766 // We'll use that extract the final state which contains one remaining fast track
2767 // corresponding to our sub-mix.
2768 state = sq->begin();
2769 ALOG_ASSERT(state->mTrackMask == 1);
2770 FastTrack *fastTrack = &state->mFastTracks[0];
2771 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2772 delete fastTrack->mBufferProvider;
2773 sq->end(false /*didModify*/);
2774 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002775#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002776 if (mAudioWatchdog != 0) {
2777 mAudioWatchdog->requestExit();
2778 mAudioWatchdog->requestExitAndWait();
2779 mAudioWatchdog.clear();
2780 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002781#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 delete mAudioMixer;
2784}
2785
Glenn Kasten83efdd02012-02-24 07:21:32 -08002786class CpuStats {
2787public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002788 CpuStats();
2789 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002790#ifdef DEBUG_CPU_USAGE
2791private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002792 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2793 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2794
2795 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2796
2797 int mCpuNum; // thread's current CPU number
2798 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002799#endif
2800};
2801
Glenn Kasten190a46f2012-03-06 11:27:10 -08002802CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002803#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002804 : mCpuNum(-1), mCpukHz(-1)
2805#endif
2806{
2807}
2808
2809void CpuStats::sample(const String8 &title) {
2810#ifdef DEBUG_CPU_USAGE
2811 // get current thread's delta CPU time in wall clock ns
2812 double wcNs;
2813 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2814
2815 // record sample for wall clock statistics
2816 if (valid) {
2817 mWcStats.sample(wcNs);
2818 }
2819
2820 // get the current CPU number
2821 int cpuNum = sched_getcpu();
2822
2823 // get the current CPU frequency in kHz
2824 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2825
2826 // check if either CPU number or frequency changed
2827 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2828 mCpuNum = cpuNum;
2829 mCpukHz = cpukHz;
2830 // ignore sample for purposes of cycles
2831 valid = false;
2832 }
2833
2834 // if no change in CPU number or frequency, then record sample for cycle statistics
2835 if (valid && mCpukHz > 0) {
2836 double cycles = wcNs * cpukHz * 0.000001;
2837 mHzStats.sample(cycles);
2838 }
2839
2840 unsigned n = mWcStats.n();
2841 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002842 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002843 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002844 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2845 double perLoop = elapsed / (double) n;
2846 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002847 double perLoop1k = perLoop * 0.001;
2848 double mean = mWcStats.mean();
2849 double stddev = mWcStats.stddev();
2850 double minimum = mWcStats.minimum();
2851 double maximum = mWcStats.maximum();
2852 double meanCycles = mHzStats.mean();
2853 double stddevCycles = mHzStats.stddev();
2854 double minCycles = mHzStats.minimum();
2855 double maxCycles = mHzStats.maximum();
2856 mCpuUsage.resetElapsed();
2857 mWcStats.reset();
2858 mHzStats.reset();
2859 ALOGD("CPU usage for %s over past %.1f secs\n"
2860 " (%u mixer loops at %.1f mean ms per loop):\n"
2861 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2862 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2863 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2864 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002865 elapsed * .000000001, n, perLoop * .000001,
2866 mean * .001,
2867 stddev * .001,
2868 minimum * .001,
2869 maximum * .001,
2870 mean / perLoop100,
2871 stddev / perLoop100,
2872 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002873 maximum / perLoop100,
2874 meanCycles / perLoop1k,
2875 stddevCycles / perLoop1k,
2876 minCycles / perLoop1k,
2877 maxCycles / perLoop1k);
2878
Glenn Kasten83efdd02012-02-24 07:21:32 -08002879 }
2880 }
2881#endif
2882};
2883
Glenn Kasten37d825e2012-02-24 07:21:48 -08002884void AudioFlinger::PlaybackThread::checkSilentMode_l()
2885{
2886 if (!mMasterMute) {
2887 char value[PROPERTY_VALUE_MAX];
2888 if (property_get("ro.audio.silent", value, "0") > 0) {
2889 char *endptr;
2890 unsigned long ul = strtoul(value, &endptr, 0);
2891 if (*endptr == '\0' && ul != 0) {
2892 ALOGD("Silence is golden");
2893 // The setprop command will not allow a property to be changed after
2894 // the first time it is set, so we don't have to worry about un-muting.
2895 setMasterMute_l(true);
2896 }
2897 }
2898 }
2899}
2900
Glenn Kasten000f0e32012-03-01 17:10:56 -08002901bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902{
2903 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002904
Glenn Kasten000f0e32012-03-01 17:10:56 -08002905 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002906
2907 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002909
Glenn Kasten000f0e32012-03-01 17:10:56 -08002910 // DUPLICATING
2911 // FIXME could this be made local to while loop?
2912 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002913
Glenn Kasten66fcab92012-02-24 14:59:21 -08002914 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002915 sleepTime = idleSleepTime;
2916
Glenn Kasten9f34a362012-03-20 16:46:41 -07002917 if (mType == MIXER) {
2918 sleepTimeShift = 0;
2919 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002920
Glenn Kasten83efdd02012-02-24 07:21:32 -08002921 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002922 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923
Eric Laurentfeb0db62011-07-22 09:04:31 -07002924 acquireWakeLock();
2925
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 while (!exitPending())
2927 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002928 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002929
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002930 Vector< sp<EffectChain> > effectChains;
2931
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 processConfigEvents();
2933
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 { // scope for mLock
2935
2936 Mutex::Autolock _l(mLock);
2937
2938 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002939 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 }
2941
Glenn Kastenfa26a852012-03-06 11:28:04 -08002942 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002943
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002945 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002946 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002948
2949 threadLoop_standby();
2950
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952 }
2953
Glenn Kasten3e074702012-02-28 18:40:35 -08002954 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955 // we're about to wait, flush the binder command buffer
2956 IPCThreadState::self()->flushCommands();
2957
Glenn Kastenfa26a852012-03-06 11:28:04 -08002958 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002959
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 if (exitPending()) break;
2961
Eric Laurentfeb0db62011-07-22 09:04:31 -07002962 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002964 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002966 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002967 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968
Eric Laurentda747442012-04-25 18:53:13 -07002969 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002970 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002971 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002972
Glenn Kasten37d825e2012-02-24 07:21:48 -08002973 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974
Glenn Kasten000f0e32012-03-01 17:10:56 -08002975 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002977 if (mType == MIXER) {
2978 sleepTimeShift = 0;
2979 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002980
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981 continue;
2982 }
2983 }
2984
Glenn Kasten81028042012-04-30 18:15:12 -07002985 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002986 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987
2988 // prevent any changes in effect chain list and in each effect chain
2989 // during mixing and effect process as the audio buffers could be deleted
2990 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002991 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993
Glenn Kastenfec279f2012-03-08 07:47:15 -08002994 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002995 threadLoop_mix();
2996 } else {
2997 threadLoop_sleepTime();
2998 }
2999
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003000 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003001 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07003002 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003003 }
3004
3005 // only process effects if we're going to write
3006 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003007 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08003008#ifdef QCOM_HARDWARE
3009 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
3010#endif
3011 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003012 }
3013 }
3014
3015 // enable changes in effect chain
3016 unlockEffectChains(effectChains);
3017
3018 // sleepTime == 0 means we must write to audio hardware
3019 if (sleepTime == 0) {
3020
3021 threadLoop_write();
3022
3023if (mType == MIXER) {
3024 // write blocked detection
3025 nsecs_t now = systemTime();
3026 nsecs_t delta = now - mLastWriteTime;
3027 if (!mStandby && delta > maxPeriod) {
3028 mNumDelayedWrites++;
3029 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003030#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003031 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003032#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003033 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3034 ns2ms(delta), mNumDelayedWrites, this);
3035 lastWarning = now;
3036 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003037 }
3038}
3039
3040 mStandby = false;
3041 } else {
3042 usleep(sleepTime);
3043 }
3044
Glenn Kasten58912562012-04-03 10:45:00 -07003045 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003046 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003047 // same lock. This will also mutate and push a new fast mixer state.
3048 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003049 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003050
Glenn Kastenfa26a852012-03-06 11:28:04 -08003051 // FIXME I don't understand the need for this here;
3052 // it was in the original code but maybe the
3053 // assignment in saveOutputTracks() makes this unnecessary?
3054 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003055
3056 // Effect chains will be actually deleted here if they were removed from
3057 // mEffectChains list during mixing or effects processing
3058 effectChains.clear();
3059
3060 // FIXME Note that the above .clear() is no longer necessary since effectChains
3061 // is now local to this block, but will keep it for now (at least until merge done).
3062 }
3063
Glenn Kasten9f34a362012-03-20 16:46:41 -07003064 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3065 if (mType == MIXER || mType == DIRECT) {
3066 // put output stream into standby mode
3067 if (!mStandby) {
3068 mOutput->stream->common.standby(&mOutput->stream->common);
3069 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003070 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003071
3072 releaseWakeLock();
3073
3074 ALOGV("Thread %p type %d exiting", this, mType);
3075 return false;
3076}
3077
Glenn Kasten58912562012-04-03 10:45:00 -07003078void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3079{
Glenn Kasten58912562012-04-03 10:45:00 -07003080 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3081}
3082
3083void AudioFlinger::MixerThread::threadLoop_write()
3084{
3085 // FIXME we should only do one push per cycle; confirm this is true
3086 // Start the fast mixer if it's not already running
3087 if (mFastMixer != NULL) {
3088 FastMixerStateQueue *sq = mFastMixer->sq();
3089 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003090 if (state->mCommand != FastMixerState::MIX_WRITE &&
3091 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003092 if (state->mCommand == FastMixerState::COLD_IDLE) {
3093 int32_t old = android_atomic_inc(&mFastMixerFutex);
3094 if (old == -1) {
3095 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3096 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003097#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003098 if (mAudioWatchdog != 0) {
3099 mAudioWatchdog->resume();
3100 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003101#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003102 }
3103 state->mCommand = FastMixerState::MIX_WRITE;
3104 sq->end();
3105 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003106 if (kUseFastMixer == FastMixer_Dynamic) {
3107 mNormalSink = mPipeSink;
3108 }
Glenn Kasten58912562012-04-03 10:45:00 -07003109 } else {
3110 sq->end(false /*didModify*/);
3111 }
3112 }
3113 PlaybackThread::threadLoop_write();
3114}
3115
Glenn Kasten000f0e32012-03-01 17:10:56 -08003116// shared by MIXER and DIRECT, overridden by DUPLICATING
3117void AudioFlinger::PlaybackThread::threadLoop_write()
3118{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003119 // FIXME rewrite to reduce number of system calls
3120 mLastWriteTime = systemTime();
3121 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003122 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003123
Eric Laurent67c0a582012-05-01 19:31:12 -07003124 // If an NBAIO sink is present, use it to write the normal mixer's submix
3125 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003126#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003127 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003128#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003129 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003130#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003131 // update the setpoint when gScreenState changes
3132 uint32_t screenState = gScreenState;
3133 if (screenState != mScreenState) {
3134 mScreenState = screenState;
3135 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3136 if (pipe != NULL) {
3137 pipe->setAvgFrames((mScreenState & 1) ?
3138 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3139 }
3140 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003141 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003142#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003143 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003144#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003145 if (framesWritten > 0) {
3146 bytesWritten = framesWritten << mBitShift;
3147 } else {
3148 bytesWritten = framesWritten;
3149 }
3150 // otherwise use the HAL / AudioStreamOut directly
3151 } else {
3152 // Direct output thread.
3153 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003154 }
3155
Eric Laurent67c0a582012-05-01 19:31:12 -07003156 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003157 mNumWrites++;
3158 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003159}
3160
Glenn Kasten58912562012-04-03 10:45:00 -07003161void AudioFlinger::MixerThread::threadLoop_standby()
3162{
3163 // Idle the fast mixer if it's currently running
3164 if (mFastMixer != NULL) {
3165 FastMixerStateQueue *sq = mFastMixer->sq();
3166 FastMixerState *state = sq->begin();
3167 if (!(state->mCommand & FastMixerState::IDLE)) {
3168 state->mCommand = FastMixerState::COLD_IDLE;
3169 state->mColdFutexAddr = &mFastMixerFutex;
3170 state->mColdGen++;
3171 mFastMixerFutex = 0;
3172 sq->end();
3173 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3174 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003175 if (kUseFastMixer == FastMixer_Dynamic) {
3176 mNormalSink = mOutputSink;
3177 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003178#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003179 if (mAudioWatchdog != 0) {
3180 mAudioWatchdog->pause();
3181 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003182#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003183 } else {
3184 sq->end(false /*didModify*/);
3185 }
3186 }
3187 PlaybackThread::threadLoop_standby();
3188}
3189
Glenn Kasten000f0e32012-03-01 17:10:56 -08003190// shared by MIXER and DIRECT, overridden by DUPLICATING
3191void AudioFlinger::PlaybackThread::threadLoop_standby()
3192{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003193 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003194 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003195}
3196
3197void AudioFlinger::MixerThread::threadLoop_mix()
3198{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003199 // obtain the presentation timestamp of the next output buffer
3200 int64_t pts;
3201 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003202
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003203#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003204 if (mNormalSink != 0) {
3205 status = mNormalSink->getNextWriteTimestamp(&pts);
3206 } else {
3207 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003208 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003209#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003210
Glenn Kasten952eeb22012-03-06 11:30:57 -08003211 if (status != NO_ERROR) {
3212 pts = AudioBufferProvider::kInvalidPTS;
3213 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003214
Glenn Kasten952eeb22012-03-06 11:30:57 -08003215 // mix buffers...
3216 mAudioMixer->process(pts);
3217 // increase sleep time progressively when application underrun condition clears.
3218 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3219 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3220 // such that we would underrun the audio HAL.
3221 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3222 sleepTimeShift--;
3223 }
3224 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003225 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003226 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003227}
3228
3229void AudioFlinger::MixerThread::threadLoop_sleepTime()
3230{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003231 // If no tracks are ready, sleep once for the duration of an output
3232 // buffer size, then write 0s to the output
3233 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003234 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003235 sleepTime = activeSleepTime >> sleepTimeShift;
3236 if (sleepTime < kMinThreadSleepTimeUs) {
3237 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003239 // reduce sleep time in case of consecutive application underruns to avoid
3240 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3241 // duration we would end up writing less data than needed by the audio HAL if
3242 // the condition persists.
3243 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3244 sleepTimeShift++;
3245 }
3246 } else {
3247 sleepTime = idleSleepTime;
3248 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003249 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003250 memset (mMixBuffer, 0, mixBufferSize);
3251 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003252 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003253 }
3254 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255}
3256
3257// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003258AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003259 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260{
3261
Glenn Kasten29c23c32012-01-26 13:37:52 -08003262 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003264 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 size_t mixedTracks = 0;
3266 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003267 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003268 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003269 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270
3271 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003272 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273
Eric Laurent571d49c2010-08-11 05:20:11 -07003274 if (masterMute) {
3275 masterVolume = 0;
3276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003278 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003280 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003281 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282 masterVolume = (float)((v + (1 << 23)) >> 24);
3283 chain.clear();
3284 }
3285
Glenn Kasten288ed212012-04-25 17:52:27 -07003286 // prepare a new state to push
3287 FastMixerStateQueue *sq = NULL;
3288 FastMixerState *state = NULL;
3289 bool didModify = false;
3290 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3291 if (mFastMixer != NULL) {
3292 sq = mFastMixer->sq();
3293 state = sq->begin();
3294 }
3295
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003297 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 if (t == 0) continue;
3299
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003300 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003302
Glenn Kasten288ed212012-04-25 17:52:27 -07003303 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003304 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003305
3306 // It's theoretically possible (though unlikely) for a fast track to be created
3307 // and then removed within the same normal mix cycle. This is not a problem, as
3308 // the track never becomes active so it's fast mixer slot is never touched.
3309 // The converse, of removing an (active) track and then creating a new track
3310 // at the identical fast mixer slot within the same normal mix cycle,
3311 // is impossible because the slot isn't marked available until the end of each cycle.
3312 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003313 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3314 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 FastTrack *fastTrack = &state->mFastTracks[j];
3316
3317 // Determine whether the track is currently in underrun condition,
3318 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003319 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3320 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003321 uint32_t recentFull = (underruns.mBitFields.mFull -
3322 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3323 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3324 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3325 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3326 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3327 uint32_t recentUnderruns = recentPartial + recentEmpty;
3328 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003329 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003330 // or stopped which can occur when flush() is called while active
3331 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003332 track->mUnderrunCount += recentUnderruns;
3333 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003334
Glenn Kastend08f48c2012-05-01 18:14:02 -07003335 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003336 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003337 bool isActive = true;
3338 switch (track->mState) {
3339 case TrackBase::STOPPING_1:
3340 // track stays active in STOPPING_1 state until first underrun
3341 if (recentUnderruns > 0) {
3342 track->mState = TrackBase::STOPPING_2;
3343 }
3344 break;
3345 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003346 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003347 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003348 break;
3349 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003350 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003351 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003352 break;
3353 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003354 if (recentFull > 0 || recentPartial > 0) {
3355 // track has provided at least some frames recently: reset retry count
3356 track->mRetryCount = kMaxTrackRetries;
3357 }
3358 if (recentUnderruns == 0) {
3359 // no recent underruns: stay active
3360 break;
3361 }
3362 // there has recently been an underrun of some kind
3363 if (track->sharedBuffer() == 0) {
3364 // were any of the recent underruns "empty" (no frames available)?
3365 if (recentEmpty == 0) {
3366 // no, then ignore the partial underruns as they are allowed indefinitely
3367 break;
3368 }
3369 // there has recently been an "empty" underrun: decrement the retry counter
3370 if (--(track->mRetryCount) > 0) {
3371 break;
3372 }
3373 // indicate to client process that the track was disabled because of underrun;
3374 // it will then automatically call start() when data is available
3375 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3376 // remove from active list, but state remains ACTIVE [confusing but true]
3377 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003378 break;
3379 }
3380 // fall through
3381 case TrackBase::STOPPING_2:
3382 case TrackBase::PAUSED:
3383 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003384 case TrackBase::STOPPED:
3385 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003386 // Check for presentation complete if track is inactive
3387 // We have consumed all the buffers of this track.
3388 // This would be incomplete if we auto-paused on underrun
3389 {
3390 size_t audioHALFrames =
3391 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3392 size_t framesWritten =
3393 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003394 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003395 // track stays in active list until presentation is complete
3396 break;
3397 }
3398 }
3399 if (track->isStopping_2()) {
3400 track->mState = TrackBase::STOPPED;
3401 }
3402 if (track->isStopped()) {
3403 // Can't reset directly, as fast mixer is still polling this track
3404 // track->reset();
3405 // So instead mark this track as needing to be reset after push with ack
3406 resetMask |= 1 << i;
3407 }
3408 isActive = false;
3409 break;
3410 case TrackBase::IDLE:
3411 default:
3412 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003413 }
3414
3415 if (isActive) {
3416 // was it previously inactive?
3417 if (!(state->mTrackMask & (1 << j))) {
3418 ExtendedAudioBufferProvider *eabp = track;
3419 VolumeProvider *vp = track;
3420 fastTrack->mBufferProvider = eabp;
3421 fastTrack->mVolumeProvider = vp;
3422 fastTrack->mSampleRate = track->mSampleRate;
3423 fastTrack->mChannelMask = track->mChannelMask;
3424 fastTrack->mGeneration++;
3425 state->mTrackMask |= 1 << j;
3426 didModify = true;
3427 // no acknowledgement required for newly active tracks
3428 }
3429 // cache the combined master volume and stream type volume for fast mixer; this
3430 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3431 track->mCachedVolume = track->isMuted() ?
3432 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3433 ++fastTracks;
3434 } else {
3435 // was it previously active?
3436 if (state->mTrackMask & (1 << j)) {
3437 fastTrack->mBufferProvider = NULL;
3438 fastTrack->mGeneration++;
3439 state->mTrackMask &= ~(1 << j);
3440 didModify = true;
3441 // If any fast tracks were removed, we must wait for acknowledgement
3442 // because we're about to decrement the last sp<> on those tracks.
3443 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003444 } else {
3445 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003446 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003447 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003448 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003449 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003450 }
3451 continue;
3452 }
3453
3454 { // local variable scope to avoid goto warning
3455
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 audio_track_cblk_t* cblk = track->cblk();
3457
3458 // The first time a track is added we wait
3459 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003460 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003461 // make sure that we have enough frames to mix one full buffer.
3462 // enforce this condition only once to enable draining the buffer in case the client
3463 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003464 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003465 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003466 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003467 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003468 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003469 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003470 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003471 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003472 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003473 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003474 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003475 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003476 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3477 // the minimum track buffer size is normally twice the number of frames necessary
3478 // to fill one buffer and the resampler should not leave more than one buffer worth
3479 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003480 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003481 }
3482 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003483 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 !track->isPaused() && !track->isTerminated())
3485 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003486 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487
3488 mixedTracks++;
3489
3490 // track->mainBuffer() != mMixBuffer means there is an effect chain
3491 // connected to the track
3492 chain.clear();
3493 if (track->mainBuffer() != mMixBuffer) {
3494 chain = getEffectChain_l(track->sessionId());
3495 // Delegate volume control to effect in track effect chain if needed
3496 if (chain != 0) {
3497 tracksWithEffect++;
3498 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003499 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003500 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 }
3502 }
3503
3504
3505 int param = AudioMixer::VOLUME;
3506 if (track->mFillingUpStatus == Track::FS_FILLED) {
3507 // no ramp for the first volume setting
3508 track->mFillingUpStatus = Track::FS_ACTIVE;
3509 if (track->mState == TrackBase::RESUMING) {
3510 track->mState = TrackBase::ACTIVE;
3511 param = AudioMixer::RAMP_VOLUME;
3512 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003513 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 } else if (cblk->server != 0) {
3515 // If the track is stopped before the first frame was mixed,
3516 // do not apply ramp
3517 param = AudioMixer::RAMP_VOLUME;
3518 }
3519
3520 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003521 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003522 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003523 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003524 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 if (track->isPausing()) {
3526 track->setPaused();
3527 }
3528 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003529
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003531 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003533 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003534 vl = vlr & 0xFFFF;
3535 vr = vlr >> 16;
3536 // track volumes come from shared memory, so can't be trusted and must be clamped
3537 if (vl > MAX_GAIN_INT) {
3538 ALOGV("Track left volume out of range: %04X", vl);
3539 vl = MAX_GAIN_INT;
3540 }
3541 if (vr > MAX_GAIN_INT) {
3542 ALOGV("Track right volume out of range: %04X", vr);
3543 vr = MAX_GAIN_INT;
3544 }
3545 // now apply the master volume and stream type volume
3546 vl = (uint32_t)(v * vl) << 12;
3547 vr = (uint32_t)(v * vr) << 12;
3548 // assuming master volume and stream type volume each go up to 1.0,
3549 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550
Glenn Kasten05632a52012-01-03 14:22:33 -08003551 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3552 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003553 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003554 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003555 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003556 }
3557 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003559 // Delegate volume control to effect in track effect chain if needed
3560 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3561 // Do not ramp volume if volume is controlled by effect
3562 param = AudioMixer::VOLUME;
3563 track->mHasVolumeController = true;
3564 } else {
3565 // force no volume ramp when volume controller was just disabled or removed
3566 // from effect chain to avoid volume spike
3567 if (track->mHasVolumeController) {
3568 param = AudioMixer::VOLUME;
3569 }
3570 track->mHasVolumeController = false;
3571 }
3572
3573 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003574 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003575 vl = (vl + (1 << 11)) >> 12;
3576 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3577 vr = (vr + (1 << 11)) >> 12;
3578 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003579
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003580 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 -07003581
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003583 mAudioMixer->setBufferProvider(name, track);
3584 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003586 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3587 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3588 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003590 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 AudioMixer::TRACK,
3592 AudioMixer::FORMAT, (void *)track->format());
3593 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003594 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003596 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003598 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599 AudioMixer::RESAMPLE,
3600 AudioMixer::SAMPLE_RATE,
3601 (void *)(cblk->sampleRate));
3602 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003603 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 AudioMixer::TRACK,
3605 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3606 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003607 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 AudioMixer::TRACK,
3609 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3610
3611 // reset retry count
3612 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003613
Eric Laurent27741442012-01-17 19:20:12 -08003614 // If one track is ready, set the mixer ready if:
3615 // - the mixer was not ready during previous round OR
3616 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003617 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003618 mixerStatus != MIXER_TRACKS_ENABLED) {
3619 mixerStatus = MIXER_TRACKS_READY;
3620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003622 // clear effect chain input buffer if an active track underruns to avoid sending
3623 // previous audio buffer again to effects
3624 chain = getEffectChain_l(track->sessionId());
3625 if (chain != 0) {
3626 chain->clearInputBuffer();
3627 }
3628
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003629 //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 -07003630 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003631 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 // We have consumed all the buffers of this track.
3633 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003634 // TODO: use actual buffer filling status instead of latency when available from
3635 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003636 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003637 size_t framesWritten =
3638 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003639 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003640 if (track->isStopped()) {
3641 track->reset();
3642 }
Eric Laurenta011e352012-03-29 15:51:43 -07003643 tracksToRemove->add(track);
3644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003646 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647 // No buffers for this track. Give it a few chances to
3648 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003649 if (--(track->mRetryCount) <= 0) {
3650 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003652 // indicate to client process that the track was disabled because of underrun;
3653 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003654 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003655 // If one track is not ready, mark the mixer also not ready if:
3656 // - the mixer was ready during previous round OR
3657 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003658 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003659 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 mixerStatus = MIXER_TRACKS_ENABLED;
3661 }
3662 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003663 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 }
Glenn Kasten58912562012-04-03 10:45:00 -07003665
3666 } // local variable scope to avoid goto warning
3667track_is_ready: ;
3668
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 }
3670
Glenn Kasten288ed212012-04-25 17:52:27 -07003671 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003672 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003673 if (didModify) {
3674 state->mFastTracksGen++;
3675 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3676 if (kUseFastMixer == FastMixer_Dynamic &&
3677 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3678 state->mCommand = FastMixerState::COLD_IDLE;
3679 state->mColdFutexAddr = &mFastMixerFutex;
3680 state->mColdGen++;
3681 mFastMixerFutex = 0;
3682 if (kUseFastMixer == FastMixer_Dynamic) {
3683 mNormalSink = mOutputSink;
3684 }
3685 // If we go into cold idle, need to wait for acknowledgement
3686 // so that fast mixer stops doing I/O.
3687 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003688 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003689 }
3690 sq->end();
3691 }
3692 if (sq != NULL) {
3693 sq->end(didModify);
3694 sq->push(block);
3695 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003696#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003697 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3698 mAudioWatchdog->pause();
3699 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003700#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003701
3702 // Now perform the deferred reset on fast tracks that have stopped
3703 while (resetMask != 0) {
3704 size_t i = __builtin_ctz(resetMask);
3705 ALOG_ASSERT(i < count);
3706 resetMask &= ~(1 << i);
3707 sp<Track> t = mActiveTracks[i].promote();
3708 if (t == 0) continue;
3709 Track* track = t.get();
3710 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3711 track->reset();
3712 }
Glenn Kasten58912562012-04-03 10:45:00 -07003713
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714 // remove all the tracks that need to be...
3715 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003716 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 for (size_t i=0 ; i<count ; i++) {
3718 const sp<Track>& track = tracksToRemove->itemAt(i);
3719 mActiveTracks.remove(track);
3720 if (track->mainBuffer() != mMixBuffer) {
3721 chain = getEffectChain_l(track->sessionId());
3722 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003723 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003724 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 }
3726 }
3727 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003728 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 }
3730 }
3731 }
3732
3733 // mix buffer must be cleared if all tracks are connected to an
3734 // effect chain as in this case the mixer will not write to
3735 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003736 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3737 // FIXME as a performance optimization, should remember previous zero status
3738 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003739 }
3740
Glenn Kasten58912562012-04-03 10:45:00 -07003741 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003742 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003743 if (fastTracks > 0) {
3744 mixerStatus = MIXER_TRACKS_READY;
3745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 return mixerStatus;
3747}
3748
Glenn Kasten66fcab92012-02-24 14:59:21 -08003749/*
3750The derived values that are cached:
3751 - mixBufferSize from frame count * frame size
3752 - activeSleepTime from activeSleepTimeUs()
3753 - idleSleepTime from idleSleepTimeUs()
3754 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3755 - maxPeriod from frame count and sample rate (MIXER only)
3756
3757The parameters that affect these derived values are:
3758 - frame count
3759 - frame size
3760 - sample rate
3761 - device type: A2DP or not
3762 - device latency
3763 - format: PCM or not
3764 - active sleep time
3765 - idle sleep time
3766*/
3767
3768void AudioFlinger::PlaybackThread::cacheParameters_l()
3769{
Glenn Kasten58912562012-04-03 10:45:00 -07003770 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003771 activeSleepTime = activeSleepTimeUs();
3772 idleSleepTime = idleSleepTimeUs();
3773}
3774
Eric Laurent22167852012-06-20 12:26:32 -07003775void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776{
Steve Block3856b092011-10-20 11:56:00 +01003777 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003778 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003780
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 size_t size = mTracks.size();
3782 for (size_t i = 0; i < size; i++) {
3783 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003784 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003785 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787 }
3788 }
3789}
3790
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003792int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003794 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795}
3796
3797// deleteTrackName_l() must be called with ThreadBase::mLock held
3798void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3799{
Steve Block3856b092011-10-20 11:56:00 +01003800 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 mAudioMixer->deleteTrackName(name);
3802}
3803
3804// checkForNewParameters_l() must be called with ThreadBase::mLock held
3805bool AudioFlinger::MixerThread::checkForNewParameters_l()
3806{
Glenn Kasten58912562012-04-03 10:45:00 -07003807 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3808 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 bool reconfig = false;
3810
3811 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003812
3813 if (mFastMixer != NULL) {
3814 FastMixerStateQueue *sq = mFastMixer->sq();
3815 FastMixerState *state = sq->begin();
3816 if (!(state->mCommand & FastMixerState::IDLE)) {
3817 previousCommand = state->mCommand;
3818 state->mCommand = FastMixerState::HOT_IDLE;
3819 sq->end();
3820 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3821 } else {
3822 sq->end(false /*didModify*/);
3823 }
3824 }
3825
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 status_t status = NO_ERROR;
3827 String8 keyValuePair = mNewParameters[0];
3828 AudioParameter param = AudioParameter(keyValuePair);
3829 int value;
3830
3831 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3832 reconfig = true;
3833 }
3834 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003835 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 status = BAD_VALUE;
3837 } else {
3838 reconfig = true;
3839 }
3840 }
3841 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003842 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 status = BAD_VALUE;
3844 } else {
3845 reconfig = true;
3846 }
3847 }
3848 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3849 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003850 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003851 // if frame count is changed after track creation
3852 if (!mTracks.isEmpty()) {
3853 status = INVALID_OPERATION;
3854 } else {
3855 reconfig = true;
3856 }
3857 }
3858 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003859#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003860 // when changing the audio output device, call addBatteryData to notify
3861 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003862 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003863 uint32_t params = 0;
3864 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003865 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003866 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3867 }
3868
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003869 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003870 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003871 // check if any other device (except speaker) is on
3872 if (value & deviceWithoutSpeaker ) {
3873 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3874 }
3875
3876 if (params != 0) {
3877 addBatteryData(params);
3878 }
3879 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003880#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003881
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882 // forward device change to effects that have requested to be
3883 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003884 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003886 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 }
3888 }
3889
3890 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003891 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003892 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003894 mOutput->stream->common.standby(&mOutput->stream->common);
3895 mStandby = true;
3896 mBytesWritten = 0;
3897 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003898 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 }
3900 if (status == NO_ERROR && reconfig) {
3901 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003902 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3903 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003905 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003907 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908 if (name < 0) break;
3909 mTracks[i]->mName = name;
3910 // limit track sample rate to 2 x new output sample rate
3911 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3912 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3913 }
3914 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003915 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 }
3917 }
3918
3919 mNewParameters.removeAt(0);
3920
3921 mParamStatus = status;
3922 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003923 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3924 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003925 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926 }
Glenn Kasten58912562012-04-03 10:45:00 -07003927
3928 if (!(previousCommand & FastMixerState::IDLE)) {
3929 ALOG_ASSERT(mFastMixer != NULL);
3930 FastMixerStateQueue *sq = mFastMixer->sq();
3931 FastMixerState *state = sq->begin();
3932 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3933 state->mCommand = previousCommand;
3934 sq->end();
3935 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3936 }
3937
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 return reconfig;
3939}
3940
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003941void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942{
3943 const size_t SIZE = 256;
3944 char buffer[SIZE];
3945 String8 result;
3946
3947 PlaybackThread::dumpInternals(fd, args);
3948
3949 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3950 result.append(buffer);
3951 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003952
3953 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3954 FastMixerDumpState copy = mFastMixerDumpState;
3955 copy.dump(fd);
3956
Glenn Kasten39993082012-05-31 13:40:27 -07003957#ifdef STATE_QUEUE_DUMP
3958 // Similar for state queue
3959 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3960 observerCopy.dump(fd);
3961 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3962 mutatorCopy.dump(fd);
3963#endif
3964
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003965 // Write the tee output to a .wav file
3966 NBAIO_Source *teeSource = mTeeSource.get();
3967 if (teeSource != NULL) {
3968 char teePath[64];
3969 struct timeval tv;
3970 gettimeofday(&tv, NULL);
3971 struct tm tm;
3972 localtime_r(&tv.tv_sec, &tm);
3973 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3974 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3975 if (teeFd >= 0) {
3976 char wavHeader[44];
3977 memcpy(wavHeader,
3978 "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",
3979 sizeof(wavHeader));
3980 NBAIO_Format format = teeSource->format();
3981 unsigned channelCount = Format_channelCount(format);
3982 ALOG_ASSERT(channelCount <= FCC_2);
3983 unsigned sampleRate = Format_sampleRate(format);
3984 wavHeader[22] = channelCount; // number of channels
3985 wavHeader[24] = sampleRate; // sample rate
3986 wavHeader[25] = sampleRate >> 8;
3987 wavHeader[32] = channelCount * 2; // block alignment
3988 write(teeFd, wavHeader, sizeof(wavHeader));
3989 size_t total = 0;
3990 bool firstRead = true;
3991 for (;;) {
3992#define TEE_SINK_READ 1024
3993 short buffer[TEE_SINK_READ * FCC_2];
3994 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003995 ssize_t actual = teeSource->read(buffer, count,
3996 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003997 bool wasFirstRead = firstRead;
3998 firstRead = false;
3999 if (actual <= 0) {
4000 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
4001 continue;
4002 }
4003 break;
4004 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07004005 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004006 write(teeFd, buffer, actual * channelCount * sizeof(short));
4007 total += actual;
4008 }
4009 lseek(teeFd, (off_t) 4, SEEK_SET);
4010 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
4011 write(teeFd, &temp, sizeof(temp));
4012 lseek(teeFd, (off_t) 40, SEEK_SET);
4013 temp = total * channelCount * sizeof(short);
4014 write(teeFd, &temp, sizeof(temp));
4015 close(teeFd);
4016 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
4017 } else {
4018 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
4019 }
4020 }
4021
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004022#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07004023 if (mAudioWatchdog != 0) {
4024 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4025 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4026 wdCopy.dump(fd);
4027 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004028#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004031uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032{
Glenn Kasten58912562012-04-03 10:45:00 -07004033 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034}
4035
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004036uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004037{
Glenn Kasten58912562012-04-03 10:45:00 -07004038 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004039}
4040
Glenn Kasten66fcab92012-02-24 14:59:21 -08004041void AudioFlinger::MixerThread::cacheParameters_l()
4042{
4043 PlaybackThread::cacheParameters_l();
4044
4045 // FIXME: Relaxed timing because of a certain device that can't meet latency
4046 // Should be reduced to 2x after the vendor fixes the driver issue
4047 // increase threshold again due to low power audio mode. The way this warning
4048 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004049 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004050}
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004053AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004054 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004055 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004056 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058}
4059
4060AudioFlinger::DirectOutputThread::~DirectOutputThread()
4061{
4062}
4063
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004064AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4065 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004066)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004068 sp<Track> trackToRemove;
4069
Glenn Kastenfec279f2012-03-08 07:47:15 -08004070 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071
Glenn Kasten952eeb22012-03-06 11:30:57 -08004072 // find out which tracks need to be processed
4073 if (mActiveTracks.size() != 0) {
4074 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004075 // The track died recently
4076 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077
Glenn Kasten952eeb22012-03-06 11:30:57 -08004078 Track* const track = t.get();
4079 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080
Glenn Kasten952eeb22012-03-06 11:30:57 -08004081 // The first time a track is added we wait
4082 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004083 uint32_t minFrames;
4084 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4085 minFrames = mNormalFrameCount;
4086 } else {
4087 minFrames = 1;
4088 }
4089 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004090 !track->isPaused() && !track->isTerminated())
4091 {
4092 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093
Glenn Kasten952eeb22012-03-06 11:30:57 -08004094 if (track->mFillingUpStatus == Track::FS_FILLED) {
4095 track->mFillingUpStatus = Track::FS_ACTIVE;
4096 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004097 if (track->mState == TrackBase::RESUMING) {
4098 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004099 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004100 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004101
Glenn Kasten952eeb22012-03-06 11:30:57 -08004102 // compute volume for this track
4103 float left, right;
4104 if (track->isMuted() || mMasterMute || track->isPausing() ||
4105 mStreamTypes[track->streamType()].mute) {
4106 left = right = 0;
4107 if (track->isPausing()) {
4108 track->setPaused();
4109 }
4110 } else {
4111 float typeVolume = mStreamTypes[track->streamType()].volume;
4112 float v = mMasterVolume * typeVolume;
4113 uint32_t vlr = cblk->getVolumeLR();
4114 float v_clamped = v * (vlr & 0xFFFF);
4115 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4116 left = v_clamped/MAX_GAIN;
4117 v_clamped = v * (vlr >> 16);
4118 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4119 right = v_clamped/MAX_GAIN;
4120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121
Glenn Kasten952eeb22012-03-06 11:30:57 -08004122 if (left != mLeftVolFloat || right != mRightVolFloat) {
4123 mLeftVolFloat = left;
4124 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125
Glenn Kasten952eeb22012-03-06 11:30:57 -08004126 // Convert volumes from float to 8.24
4127 uint32_t vl = (uint32_t)(left * (1 << 24));
4128 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129
Glenn Kasten952eeb22012-03-06 11:30:57 -08004130 // Delegate volume control to effect in track effect chain if needed
4131 // only one effect chain can be present on DirectOutputThread, so if
4132 // there is one, the track is connected to it
4133 if (!mEffectChains.isEmpty()) {
4134 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004135 mEffectChains[0]->setVolume_l(&vl, &vr);
4136 left = (float)vl / (1 << 24);
4137 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004138 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004139 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004140 }
4141
4142 // reset retry count
4143 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004144 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004145 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004146 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004147 // clear effect chain input buffer if an active track underruns to avoid sending
4148 // previous audio buffer again to effects
4149 if (!mEffectChains.isEmpty()) {
4150 mEffectChains[0]->clearInputBuffer();
4151 }
4152
Glenn Kasten952eeb22012-03-06 11:30:57 -08004153 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004154 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004155 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004156 // We have consumed all the buffers of this track.
4157 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004158 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004159 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004160 size_t framesWritten =
4161 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004162 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004163 if (track->isStopped()) {
4164 track->reset();
4165 }
Eric Laurenta011e352012-03-29 15:51:43 -07004166 trackToRemove = track;
4167 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004168 } else {
4169 // No buffers for this track. Give it a few chances to
4170 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004171 if (--(track->mRetryCount) <= 0) {
4172 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004173 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004175 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 }
4177 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004178 }
4179 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004181 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004182 // remove all the tracks that need to be...
4183 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004184 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004185 mActiveTracks.remove(trackToRemove);
4186 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004187 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004188 trackToRemove->sessionId());
4189 mEffectChains[0]->decActiveTrackCnt();
4190 }
4191 if (trackToRemove->isTerminated()) {
4192 removeTrack_l(trackToRemove);
4193 }
4194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195
Glenn Kastenfec279f2012-03-08 07:47:15 -08004196 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004197}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198
Glenn Kasten000f0e32012-03-01 17:10:56 -08004199void AudioFlinger::DirectOutputThread::threadLoop_mix()
4200{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004201 AudioBufferProvider::Buffer buffer;
4202 size_t frameCount = mFrameCount;
4203 int8_t *curBuf = (int8_t *)mMixBuffer;
4204 // output audio to hardware
4205 while (frameCount) {
4206 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004207 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004208 if (CC_UNLIKELY(buffer.raw == NULL)) {
4209 memset(curBuf, 0, frameCount * mFrameSize);
4210 break;
4211 }
4212 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4213 frameCount -= buffer.frameCount;
4214 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004215 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004216 }
4217 sleepTime = 0;
4218 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004219 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004220
Glenn Kasten000f0e32012-03-01 17:10:56 -08004221}
4222
4223void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4224{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004225 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004226 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004227 sleepTime = activeSleepTime;
4228 } else {
4229 sleepTime = idleSleepTime;
4230 }
4231 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004232 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004233 sleepTime = 0;
4234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235}
4236
4237// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004238int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4239 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240{
4241 return 0;
4242}
4243
4244// deleteTrackName_l() must be called with ThreadBase::mLock held
4245void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4246{
4247}
4248
4249// checkForNewParameters_l() must be called with ThreadBase::mLock held
4250bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4251{
4252 bool reconfig = false;
4253
4254 while (!mNewParameters.isEmpty()) {
4255 status_t status = NO_ERROR;
4256 String8 keyValuePair = mNewParameters[0];
4257 AudioParameter param = AudioParameter(keyValuePair);
4258 int value;
4259
4260 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4261 // do not accept frame count changes if tracks are open as the track buffer
4262 // size depends on frame count and correct behavior would not be garantied
4263 // if frame count is changed after track creation
4264 if (!mTracks.isEmpty()) {
4265 status = INVALID_OPERATION;
4266 } else {
4267 reconfig = true;
4268 }
4269 }
4270 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004271 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004272 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004274 mOutput->stream->common.standby(&mOutput->stream->common);
4275 mStandby = true;
4276 mBytesWritten = 0;
4277 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004278 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 }
4280 if (status == NO_ERROR && reconfig) {
4281 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004282 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 }
4284 }
4285
4286 mNewParameters.removeAt(0);
4287
4288 mParamStatus = status;
4289 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004290 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4291 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004292 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 }
4294 return reconfig;
4295}
4296
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004297uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298{
4299 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004300 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004301 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 } else {
4303 time = 10000;
4304 }
4305 return time;
4306}
4307
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004308uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309{
4310 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004311 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004312 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 } else {
4314 time = 10000;
4315 }
4316 return time;
4317}
4318
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004319uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004320{
4321 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004322 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004323 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4324 } else {
4325 time = 10000;
4326 }
4327 return time;
4328}
4329
Glenn Kasten66fcab92012-02-24 14:59:21 -08004330void AudioFlinger::DirectOutputThread::cacheParameters_l()
4331{
4332 PlaybackThread::cacheParameters_l();
4333
4334 // use shorter standby delay as on normal output to release
4335 // hardware resources as soon as possible
4336 standbyDelay = microseconds(activeSleepTime*2);
4337}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004338
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339// ----------------------------------------------------------------------------
4340
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004341AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004342 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004343 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004344 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 addOutputTrack(mainThread);
4347}
4348
4349AudioFlinger::DuplicatingThread::~DuplicatingThread()
4350{
4351 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4352 mOutputTracks[i]->destroy();
4353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354}
4355
Glenn Kasten000f0e32012-03-01 17:10:56 -08004356void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004358 // mix buffers...
4359 if (outputsReady(outputTracks)) {
4360 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4361 } else {
4362 memset(mMixBuffer, 0, mixBufferSize);
4363 }
4364 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004365 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004366 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004367}
4368
4369void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4370{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004371 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004372 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004373 sleepTime = activeSleepTime;
4374 } else {
4375 sleepTime = idleSleepTime;
4376 }
4377 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004378 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4379 writeFrames = mNormalFrameCount;
4380 memset(mMixBuffer, 0, mixBufferSize);
4381 } else {
4382 // flush remaining overflow buffers in output tracks
4383 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004384 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004385 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004386 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004387}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388
Glenn Kasten000f0e32012-03-01 17:10:56 -08004389void AudioFlinger::DuplicatingThread::threadLoop_write()
4390{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004391 for (size_t i = 0; i < outputTracks.size(); i++) {
4392 outputTracks[i]->write(mMixBuffer, writeFrames);
4393 }
4394 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004395}
Glenn Kasten688a6402012-02-29 07:57:06 -08004396
Glenn Kasten000f0e32012-03-01 17:10:56 -08004397void AudioFlinger::DuplicatingThread::threadLoop_standby()
4398{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004399 // DuplicatingThread implements standby by stopping all tracks
4400 for (size_t i = 0; i < outputTracks.size(); i++) {
4401 outputTracks[i]->stop();
4402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403}
4404
Glenn Kastenfa26a852012-03-06 11:28:04 -08004405void AudioFlinger::DuplicatingThread::saveOutputTracks()
4406{
4407 outputTracks = mOutputTracks;
4408}
4409
4410void AudioFlinger::DuplicatingThread::clearOutputTracks()
4411{
4412 outputTracks.clear();
4413}
4414
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4416{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004417 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004418 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004419 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004420 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 this,
4422 mSampleRate,
4423 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004424 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 frameCount);
4426 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004427 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004429 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004430 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 }
4432}
4433
4434void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4435{
4436 Mutex::Autolock _l(mLock);
4437 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004438 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 mOutputTracks[i]->destroy();
4440 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004441 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442 return;
4443 }
4444 }
Steve Block3856b092011-10-20 11:56:00 +01004445 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446}
4447
Glenn Kasten438b0362012-03-06 11:24:48 -08004448// caller must hold mLock
4449void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450{
4451 mWaitTimeMs = UINT_MAX;
4452 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4453 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004454 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4456 if (waitTimeMs < mWaitTimeMs) {
4457 mWaitTimeMs = waitTimeMs;
4458 }
4459 }
4460 }
4461}
4462
4463
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004464bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465{
4466 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004467 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004469 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470 return false;
4471 }
4472 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004473 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004475 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 return false;
4477 }
4478 }
4479 return true;
4480}
4481
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004482uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483{
4484 return (mWaitTimeMs * 1000) / 2;
4485}
4486
Glenn Kasten66fcab92012-02-24 14:59:21 -08004487void AudioFlinger::DuplicatingThread::cacheParameters_l()
4488{
4489 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4490 updateWaitTime_l();
4491
4492 MixerThread::cacheParameters_l();
4493}
4494
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495// ----------------------------------------------------------------------------
4496
4497// TrackBase constructor must be called with AudioFlinger::mLock held
4498AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004499 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 const sp<Client>& client,
4501 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004502 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004503 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505 const sp<IMemory>& sharedBuffer,
4506 int sessionId)
4507 : RefBase(),
4508 mThread(thread),
4509 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004510 mCblk(NULL),
4511 // mBuffer
4512 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 mFrameCount(0),
4514 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004515 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004517 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004519 // mChannelCount
4520 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521{
Steve Block3856b092011-10-20 11:56:00 +01004522 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523
Steve Blockb8a80522011-12-20 16:23:08 +00004524 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004525 size_t size = sizeof(audio_track_cblk_t);
4526 uint8_t channelCount = popcount(channelMask);
4527 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4528 if (sharedBuffer == 0) {
4529 size += bufferSize;
4530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004532 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mCblkMemory = client->heap()->allocate(size);
4534 if (mCblkMemory != 0) {
4535 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004536 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 new(mCblk) audio_track_cblk_t();
4538 // clear all buffers
4539 mCblk->frameCount = frameCount;
4540 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004541// uncomment the following lines to quickly test 32-bit wraparound
4542// mCblk->user = 0xffff0000;
4543// mCblk->server = 0xffff0000;
4544// mCblk->userBase = 0xffff0000;
4545// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004546 mChannelCount = channelCount;
4547 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 if (sharedBuffer == 0) {
4549 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4550 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4551 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004552 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 mCblk->flags = CBLK_UNDERRUN_ON;
4554 } else {
4555 mBuffer = sharedBuffer->pointer();
4556 }
4557 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4558 }
4559 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004560 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 client->heap()->dump("AudioTrack");
4562 return;
4563 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004564 } else {
4565 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004566 // construct the shared structure in-place.
4567 new(mCblk) audio_track_cblk_t();
4568 // clear all buffers
4569 mCblk->frameCount = frameCount;
4570 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004571// uncomment the following lines to quickly test 32-bit wraparound
4572// mCblk->user = 0xffff0000;
4573// mCblk->server = 0xffff0000;
4574// mCblk->userBase = 0xffff0000;
4575// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004576 mChannelCount = channelCount;
4577 mChannelMask = channelMask;
4578 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4579 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4580 // Force underrun condition to avoid false underrun callback until first data is
4581 // written to buffer (other flags are cleared)
4582 mCblk->flags = CBLK_UNDERRUN_ON;
4583 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004584 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585}
4586
4587AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4588{
Glenn Kastena0d68332012-01-27 16:47:15 -08004589 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004590 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004592 } else {
4593 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 }
4595 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004596 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004597 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004598 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004600 // If the client's reference count drops to zero, the associated destructor
4601 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4602 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 mClient.clear();
4604 }
4605}
4606
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004607// AudioBufferProvider interface
4608// getNextBuffer() = 0;
4609// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4611{
Glenn Kastene0feee32011-12-13 11:53:26 -08004612 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004614 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004615 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 buffer->frameCount = 0;
4617}
4618
4619bool AudioFlinger::ThreadBase::TrackBase::step() {
4620 bool result;
4621 audio_track_cblk_t* cblk = this->cblk();
4622
4623 result = cblk->stepServer(mFrameCount);
4624 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004625 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004626 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 }
4628 return result;
4629}
4630
4631void AudioFlinger::ThreadBase::TrackBase::reset() {
4632 audio_track_cblk_t* cblk = this->cblk();
4633
4634 cblk->user = 0;
4635 cblk->server = 0;
4636 cblk->userBase = 0;
4637 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004638 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004639 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640}
4641
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4643 return (int)mCblk->sampleRate;
4644}
4645
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4647 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004648 size_t frameSize = cblk->frameSize;
4649 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4650 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651
4652 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004653 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4654 "TrackBase::getBuffer buffer out of range:\n"
4655 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4656 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004658 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659
4660 return bufferStart;
4661}
4662
Eric Laurenta011e352012-03-29 15:51:43 -07004663status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4664{
4665 mSyncEvents.add(event);
4666 return NO_ERROR;
4667}
4668
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669// ----------------------------------------------------------------------------
4670
4671// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4672AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004673 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004674 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004675 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004677 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004678 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 int frameCount,
4680 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004681 int sessionId,
4682 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004683 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004684 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004685 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004686 // mRetryCount initialized later when needed
4687 mSharedBuffer(sharedBuffer),
4688 mStreamType(streamType),
4689 mName(-1), // see note below
4690 mMainBuffer(thread->mixBuffer()),
4691 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004692 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004693 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004694 mFlags(flags),
4695 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004696 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004697 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004698{
4699 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4701 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004702 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004703 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004704 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004705 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004706 if (mName < 0) {
4707 ALOGE("no more track names available");
4708 return;
4709 }
4710 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004711 if (flags & IAudioFlinger::TRACK_FAST) {
4712 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4713 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4714 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004715 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004716 // FIXME This is too eager. We allocate a fast track index before the
4717 // fast track becomes active. Since fast tracks are a scarce resource,
4718 // this means we are potentially denying other more important fast tracks from
4719 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004720 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004721 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004722 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004723 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004724 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004727 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728}
4729
4730AudioFlinger::PlaybackThread::Track::~Track()
4731{
Steve Block3856b092011-10-20 11:56:00 +01004732 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733}
4734
4735void AudioFlinger::PlaybackThread::Track::destroy()
4736{
4737 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4738 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004739 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 // we must acquire a strong reference on this Track before locking mLock
4741 // here so that the destructor is called only when exiting this function.
4742 // On the other hand, as long as Track::destroy() is only called by
4743 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4744 // this Track with its member mTrack.
4745 sp<Track> keep(this);
4746 { // scope for mLock
4747 sp<ThreadBase> thread = mThread.promote();
4748 if (thread != 0) {
4749 if (!isOutputTrack()) {
4750 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004751 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004752
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004753#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004754 // to track the speaker usage
4755 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004756#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004757 }
4758 AudioSystem::releaseOutput(thread->id());
4759 }
4760 Mutex::Autolock _l(thread->mLock);
4761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4762 playbackThread->destroyTrack_l(this);
4763 }
4764 }
4765}
4766
Glenn Kasten288ed212012-04-25 17:52:27 -07004767/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4768{
Glenn Kastene213c862012-04-25 13:46:15 -07004769 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 -07004770 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004771}
4772
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4774{
Glenn Kasten83d86532012-01-17 14:39:34 -08004775 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004776 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004777 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004778 } else {
4779 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4780 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004781 track_state state = mState;
4782 char stateChar;
4783 switch (state) {
4784 case IDLE:
4785 stateChar = 'I';
4786 break;
4787 case TERMINATED:
4788 stateChar = 'T';
4789 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004790 case STOPPING_1:
4791 stateChar = 's';
4792 break;
4793 case STOPPING_2:
4794 stateChar = '5';
4795 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004796 case STOPPED:
4797 stateChar = 'S';
4798 break;
4799 case RESUMING:
4800 stateChar = 'R';
4801 break;
4802 case ACTIVE:
4803 stateChar = 'A';
4804 break;
4805 case PAUSING:
4806 stateChar = 'p';
4807 break;
4808 case PAUSED:
4809 stateChar = 'P';
4810 break;
Eric Laurent29864602012-05-08 18:57:51 -07004811 case FLUSHED:
4812 stateChar = 'F';
4813 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004814 default:
4815 stateChar = '?';
4816 break;
4817 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004818 char nowInUnderrun;
4819 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4820 case UNDERRUN_FULL:
4821 nowInUnderrun = ' ';
4822 break;
4823 case UNDERRUN_PARTIAL:
4824 nowInUnderrun = '<';
4825 break;
4826 case UNDERRUN_EMPTY:
4827 nowInUnderrun = '*';
4828 break;
4829 default:
4830 nowInUnderrun = '?';
4831 break;
4832 }
Glenn Kastene213c862012-04-25 13:46:15 -07004833 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4834 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004835 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004836 mStreamType,
4837 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004838 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839 mSessionId,
4840 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004841 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004842 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004843 mMute,
4844 mFillingUpStatus,
4845 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004846 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4847 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004848 mCblk->server,
4849 mCblk->user,
4850 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004851 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004852 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004853 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004854 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855}
4856
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004857// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004858status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004859 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004861 audio_track_cblk_t* cblk = this->cblk();
4862 uint32_t framesReady;
4863 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004865 // Check if last stepServer failed, try to step now
4866 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004867 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4868 // Since the fast mixer is higher priority than client callback thread,
4869 // it does not result in priority inversion for client.
4870 // But a non-blocking solution would be preferable to avoid
4871 // fast mixer being unable to tryLock(), and
4872 // to avoid the extra context switches if the client wakes up,
4873 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004874 if (!step()) goto getNextBuffer_exit;
4875 ALOGV("stepServer recovered");
4876 mStepServerFailed = false;
4877 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878
Glenn Kasten288ed212012-04-25 17:52:27 -07004879 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004880 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004882 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883 uint32_t s = cblk->server;
4884 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4885
4886 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4887 if (framesReq > framesReady) {
4888 framesReq = framesReady;
4889 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004890 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004891 framesReq = bufferEnd - s;
4892 }
4893
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004894 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004895 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004897 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898
4899getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004900 buffer->raw = NULL;
4901 buffer->frameCount = 0;
4902 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4903 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904}
4905
Glenn Kasten288ed212012-04-25 17:52:27 -07004906// Note that framesReady() takes a mutex on the control block using tryLock().
4907// This could result in priority inversion if framesReady() is called by the normal mixer,
4908// as the normal mixer thread runs at lower
4909// priority than the client's callback thread: there is a short window within framesReady()
4910// during which the normal mixer could be preempted, and the client callback would block.
4911// Another problem can occur if framesReady() is called by the fast mixer:
4912// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4913// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4914size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004915 return mCblk->framesReady();
4916}
4917
Glenn Kasten288ed212012-04-25 17:52:27 -07004918// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004920 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921
John Grossman4ff14ba2012-02-08 16:37:41 -08004922 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004923 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4924 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004925 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 return true;
4927 }
4928 return false;
4929}
4930
Glenn Kasten3acbd052012-02-28 10:39:56 -08004931status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004932 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933{
4934 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004935 ALOGV("start(%d), calling pid %d session %d",
4936 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004937
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 sp<ThreadBase> thread = mThread.promote();
4939 if (thread != 0) {
4940 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004941 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 // here the track could be either new, or restarted
4943 // in both cases "unstop" the track
4944 if (mState == PAUSED) {
4945 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004946 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 } else {
4948 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004949 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 }
4951
4952 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4953 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004954 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004956
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004957#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004958 // to track the speaker usage
4959 if (status == NO_ERROR) {
4960 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4961 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004962#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 }
4964 if (status == NO_ERROR) {
4965 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4966 playbackThread->addTrack_l(this);
4967 } else {
4968 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004969 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970 }
4971 } else {
4972 status = BAD_VALUE;
4973 }
4974 return status;
4975}
4976
4977void AudioFlinger::PlaybackThread::Track::stop()
4978{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004979 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 sp<ThreadBase> thread = mThread.promote();
4981 if (thread != 0) {
4982 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004983 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004984 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 // If the track is not active (PAUSED and buffers full), flush buffers
4986 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4987 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4988 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004989 mState = STOPPED;
4990 } else if (!isFastTrack()) {
4991 mState = STOPPED;
4992 } else {
4993 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4994 // and then to STOPPED and reset() when presentation is complete
4995 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004997 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 }
4999 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
5000 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005001 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005003
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005004#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005005 // to track the speaker usage
5006 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005007#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 }
5009 }
5010}
5011
5012void AudioFlinger::PlaybackThread::Track::pause()
5013{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005014 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 sp<ThreadBase> thread = mThread.promote();
5016 if (thread != 0) {
5017 Mutex::Autolock _l(thread->mLock);
5018 if (mState == ACTIVE || mState == RESUMING) {
5019 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01005020 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 if (!isOutputTrack()) {
5022 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005023 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005024 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005025
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005026#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005027 // to track the speaker usage
5028 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005029#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005030 }
5031 }
5032 }
5033}
5034
5035void AudioFlinger::PlaybackThread::Track::flush()
5036{
Steve Block3856b092011-10-20 11:56:00 +01005037 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 sp<ThreadBase> thread = mThread.promote();
5039 if (thread != 0) {
5040 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005041 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005042 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043 return;
5044 }
5045 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005046 // FLUSHED state
5047 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005048 // do not reset the track if it is still in the process of being stopped or paused.
5049 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005050 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005051 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005052 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5053 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5054 reset();
5055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056 }
5057}
5058
5059void AudioFlinger::PlaybackThread::Track::reset()
5060{
5061 // Do not reset twice to avoid discarding data written just after a flush and before
5062 // the audioflinger thread detects the track is stopped.
5063 if (!mResetDone) {
5064 TrackBase::reset();
5065 // Force underrun condition to avoid false underrun callback until first data is
5066 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005067 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5068 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 mFillingUpStatus = FS_FILLING;
5070 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005071 if (mState == FLUSHED) {
5072 mState = IDLE;
5073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074 }
5075}
5076
5077void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5078{
5079 mMute = muted;
5080}
5081
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5083{
5084 status_t status = DEAD_OBJECT;
5085 sp<ThreadBase> thread = mThread.promote();
5086 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005087 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005088 sp<AudioFlinger> af = mClient->audioFlinger();
5089
5090 Mutex::Autolock _l(af->mLock);
5091
5092 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005093
Eric Laurent109347d2012-07-02 12:31:03 -07005094 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005095 Mutex::Autolock _dl(playbackThread->mLock);
5096 Mutex::Autolock _sl(srcThread->mLock);
5097 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5098 if (chain == 0) {
5099 return INVALID_OPERATION;
5100 }
5101
5102 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5103 if (effect == 0) {
5104 return INVALID_OPERATION;
5105 }
5106 srcThread->removeEffect_l(effect);
5107 playbackThread->addEffect_l(effect);
5108 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5109 if (effect->state() == EffectModule::ACTIVE ||
5110 effect->state() == EffectModule::STOPPING) {
5111 effect->start();
5112 }
5113
5114 sp<EffectChain> dstChain = effect->chain().promote();
5115 if (dstChain == 0) {
5116 srcThread->addEffect_l(effect);
5117 return INVALID_OPERATION;
5118 }
5119 AudioSystem::unregisterEffect(effect->id());
5120 AudioSystem::registerEffect(&effect->desc(),
5121 srcThread->id(),
5122 dstChain->strategy(),
5123 AUDIO_SESSION_OUTPUT_MIX,
5124 effect->id());
5125 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005126 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 }
5128 return status;
5129}
5130
5131void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5132{
5133 mAuxEffectId = EffectId;
5134 mAuxBuffer = buffer;
5135}
5136
Eric Laurenta011e352012-03-29 15:51:43 -07005137bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5138 size_t audioHalFrames)
5139{
5140 // a track is considered presented when the total number of frames written to audio HAL
5141 // corresponds to the number of frames written when presentationComplete() is called for the
5142 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5143 if (mPresentationCompleteFrames == 0) {
5144 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5145 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5146 mPresentationCompleteFrames, audioHalFrames);
5147 }
5148 if (framesWritten >= mPresentationCompleteFrames) {
5149 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5150 mSessionId, framesWritten);
5151 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005152 return true;
5153 }
5154 return false;
5155}
5156
5157void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5158{
5159 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5160 if (mSyncEvents[i]->type() == type) {
5161 mSyncEvents[i]->trigger();
5162 mSyncEvents.removeAt(i);
5163 i--;
5164 }
5165 }
5166}
5167
Glenn Kasten58912562012-04-03 10:45:00 -07005168// implement VolumeBufferProvider interface
5169
5170uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5171{
5172 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5173 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5174 uint32_t vlr = mCblk->getVolumeLR();
5175 uint32_t vl = vlr & 0xFFFF;
5176 uint32_t vr = vlr >> 16;
5177 // track volumes come from shared memory, so can't be trusted and must be clamped
5178 if (vl > MAX_GAIN_INT) {
5179 vl = MAX_GAIN_INT;
5180 }
5181 if (vr > MAX_GAIN_INT) {
5182 vr = MAX_GAIN_INT;
5183 }
5184 // now apply the cached master volume and stream type volume;
5185 // this is trusted but lacks any synchronization or barrier so may be stale
5186 float v = mCachedVolume;
5187 vl *= v;
5188 vr *= v;
5189 // re-combine into U4.16
5190 vlr = (vr << 16) | (vl & 0xFFFF);
5191 // FIXME look at mute, pause, and stop flags
5192 return vlr;
5193}
Eric Laurenta011e352012-03-29 15:51:43 -07005194
Eric Laurent29864602012-05-08 18:57:51 -07005195status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5196{
5197 if (mState == TERMINATED || mState == PAUSED ||
5198 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5199 (mState == STOPPED)))) {
5200 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5201 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5202 event->cancel();
5203 return INVALID_OPERATION;
5204 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005205 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005206 return NO_ERROR;
5207}
5208
John Grossman4ff14ba2012-02-08 16:37:41 -08005209// timed audio tracks
5210
5211sp<AudioFlinger::PlaybackThread::TimedTrack>
5212AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005213 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005214 const sp<Client>& client,
5215 audio_stream_type_t streamType,
5216 uint32_t sampleRate,
5217 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005218 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005219 int frameCount,
5220 const sp<IMemory>& sharedBuffer,
5221 int sessionId) {
5222 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005223 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005224
Glenn Kastena0356762012-03-19 10:38:51 -07005225 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005226 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5227 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005228}
5229
5230AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005231 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005232 const sp<Client>& client,
5233 audio_stream_type_t streamType,
5234 uint32_t sampleRate,
5235 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005236 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005237 int frameCount,
5238 const sp<IMemory>& sharedBuffer,
5239 int sessionId)
5240 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005241 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005242 mQueueHeadInFlight(false),
5243 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005244 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005245 mTimedSilenceBuffer(NULL),
5246 mTimedSilenceBufferSize(0),
5247 mTimedAudioOutputOnTime(false),
5248 mMediaTimeTransformValid(false)
5249{
5250 LocalClock lc;
5251 mLocalTimeFreq = lc.getLocalFreq();
5252
5253 mLocalTimeToSampleTransform.a_zero = 0;
5254 mLocalTimeToSampleTransform.b_zero = 0;
5255 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5256 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5257 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5258 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005259
5260 mMediaTimeToSampleTransform.a_zero = 0;
5261 mMediaTimeToSampleTransform.b_zero = 0;
5262 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5263 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5264 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5265 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005266}
5267
5268AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5269 mClient->releaseTimedTrack();
5270 delete [] mTimedSilenceBuffer;
5271}
5272
5273status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5274 size_t size, sp<IMemory>* buffer) {
5275
5276 Mutex::Autolock _l(mTimedBufferQueueLock);
5277
5278 trimTimedBufferQueue_l();
5279
5280 // lazily initialize the shared memory heap for timed buffers
5281 if (mTimedMemoryDealer == NULL) {
5282 const int kTimedBufferHeapSize = 512 << 10;
5283
5284 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5285 "AudioFlingerTimed");
5286 if (mTimedMemoryDealer == NULL)
5287 return NO_MEMORY;
5288 }
5289
5290 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5291 if (newBuffer == NULL) {
5292 newBuffer = mTimedMemoryDealer->allocate(size);
5293 if (newBuffer == NULL)
5294 return NO_MEMORY;
5295 }
5296
5297 *buffer = newBuffer;
5298 return NO_ERROR;
5299}
5300
5301// caller must hold mTimedBufferQueueLock
5302void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5303 int64_t mediaTimeNow;
5304 {
5305 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5306 if (!mMediaTimeTransformValid)
5307 return;
5308
5309 int64_t targetTimeNow;
5310 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5311 ? mCCHelper.getCommonTime(&targetTimeNow)
5312 : mCCHelper.getLocalTime(&targetTimeNow);
5313
5314 if (OK != res)
5315 return;
5316
5317 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5318 &mediaTimeNow)) {
5319 return;
5320 }
5321 }
5322
John Grossman1c345192012-03-27 14:00:17 -07005323 size_t trimEnd;
5324 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005325 int64_t bufEnd;
5326
John Grossmanc95cfbb2012-04-12 11:53:11 -07005327 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5328 // We have a next buffer. Just use its PTS as the PTS of the frame
5329 // following the last frame in this buffer. If the stream is sparse
5330 // (ie, there are deliberate gaps left in the stream which should be
5331 // filled with silence by the TimedAudioTrack), then this can result
5332 // in one extra buffer being left un-trimmed when it could have
5333 // been. In general, this is not typical, and we would rather
5334 // optimized away the TS calculation below for the more common case
5335 // where PTSes are contiguous.
5336 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5337 } else {
5338 // We have no next buffer. Compute the PTS of the frame following
5339 // the last frame in this buffer by computing the duration of of
5340 // this frame in media time units and adding it to the PTS of the
5341 // buffer.
5342 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5343 / mCblk->frameSize;
5344
5345 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5346 &bufEnd)) {
5347 ALOGE("Failed to convert frame count of %lld to media time"
5348 " duration" " (scale factor %d/%u) in %s",
5349 frameCount,
5350 mMediaTimeToSampleTransform.a_to_b_numer,
5351 mMediaTimeToSampleTransform.a_to_b_denom,
5352 __PRETTY_FUNCTION__);
5353 break;
5354 }
5355 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005356 }
John Grossman9fbdee12012-03-26 17:51:46 -07005357
5358 if (bufEnd > mediaTimeNow)
5359 break;
5360
5361 // Is the buffer we want to use in the middle of a mix operation right
5362 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5363 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005364 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005365 mTrimQueueHeadOnRelease = true;
5366 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005367 }
5368
John Grossman9fbdee12012-03-26 17:51:46 -07005369 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005370 if (trimStart < trimEnd) {
5371 // Update the bookkeeping for framesReady()
5372 for (size_t i = trimStart; i < trimEnd; ++i) {
5373 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5374 }
5375
5376 // Now actually remove the buffers from the queue.
5377 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005378 }
5379}
5380
John Grossman1c345192012-03-27 14:00:17 -07005381void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5382 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005383 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5384 "%s called (reason \"%s\"), but timed buffer queue has no"
5385 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005386
5387 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5388 mTimedBufferQueue.removeAt(0);
5389}
5390
5391void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5392 const TimedBuffer& buf,
5393 const char* logTag) {
5394 uint32_t bufBytes = buf.buffer()->size();
5395 uint32_t consumedAlready = buf.position();
5396
Eric Laurentb388e532012-04-14 13:32:48 -07005397 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005398 "Bad bookkeeping while updating frames pending. Timed buffer is"
5399 " only %u bytes long, but claims to have consumed %u"
5400 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005401 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005402
5403 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005404 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5405 "Bad bookkeeping while updating frames pending. Should have at"
5406 " least %u queued frames, but we think we have only %u. (update"
5407 " reason: \"%s\")",
5408 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005409
5410 mFramesPendingInQueue -= bufFrames;
5411}
5412
John Grossman4ff14ba2012-02-08 16:37:41 -08005413status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5414 const sp<IMemory>& buffer, int64_t pts) {
5415
5416 {
5417 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5418 if (!mMediaTimeTransformValid)
5419 return INVALID_OPERATION;
5420 }
5421
5422 Mutex::Autolock _l(mTimedBufferQueueLock);
5423
John Grossman1c345192012-03-27 14:00:17 -07005424 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5425 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005426 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5427
5428 return NO_ERROR;
5429}
5430
5431status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5432 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5433
John Grossman1c345192012-03-27 14:00:17 -07005434 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5435 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5436 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005437
5438 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5439 target == TimedAudioTrack::COMMON_TIME)) {
5440 return BAD_VALUE;
5441 }
5442
5443 Mutex::Autolock lock(mMediaTimeTransformLock);
5444 mMediaTimeTransform = xform;
5445 mMediaTimeTransformTarget = target;
5446 mMediaTimeTransformValid = true;
5447
5448 return NO_ERROR;
5449}
5450
5451#define min(a, b) ((a) < (b) ? (a) : (b))
5452
5453// implementation of getNextBuffer for tracks whose buffers have timestamps
5454status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5455 AudioBufferProvider::Buffer* buffer, int64_t pts)
5456{
5457 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005458 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005459 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005460 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005461 return INVALID_OPERATION;
5462 }
5463
John Grossman4ff14ba2012-02-08 16:37:41 -08005464 Mutex::Autolock _l(mTimedBufferQueueLock);
5465
John Grossman9fbdee12012-03-26 17:51:46 -07005466 ALOG_ASSERT(!mQueueHeadInFlight,
5467 "getNextBuffer called without releaseBuffer!");
5468
John Grossman4ff14ba2012-02-08 16:37:41 -08005469 while (true) {
5470
5471 // if we have no timed buffers, then fail
5472 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005473 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005474 buffer->frameCount = 0;
5475 return NOT_ENOUGH_DATA;
5476 }
5477
5478 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5479
5480 // calculate the PTS of the head of the timed buffer queue expressed in
5481 // local time
5482 int64_t headLocalPTS;
5483 {
5484 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5485
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005486 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005487
5488 if (mMediaTimeTransform.a_to_b_denom == 0) {
5489 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005490 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005491 return NO_ERROR;
5492 }
5493
5494 int64_t transformedPTS;
5495 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5496 &transformedPTS)) {
5497 // the transform failed. this shouldn't happen, but if it does
5498 // then just drop this buffer
5499 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005500 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005501 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005502 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005503 return NO_ERROR;
5504 }
5505
5506 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5507 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5508 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005509 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005510 buffer->frameCount = 0;
5511 return INVALID_OPERATION;
5512 }
5513 } else {
5514 headLocalPTS = transformedPTS;
5515 }
5516 }
5517
5518 // adjust the head buffer's PTS to reflect the portion of the head buffer
5519 // that has already been consumed
5520 int64_t effectivePTS = headLocalPTS +
5521 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5522
5523 // Calculate the delta in samples between the head of the input buffer
5524 // queue and the start of the next output buffer that will be written.
5525 // If the transformation fails because of over or underflow, it means
5526 // that the sample's position in the output stream is so far out of
5527 // whack that it should just be dropped.
5528 int64_t sampleDelta;
5529 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5530 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005531 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5532 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005533 continue;
5534 }
5535 if (!mLocalTimeToSampleTransform.doForwardTransform(
5536 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005537 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005538 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005539 continue;
5540 }
5541
John Grossman1c345192012-03-27 14:00:17 -07005542 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5543 " sampleDelta=[%d.%08x]",
5544 head.pts(), head.position(), pts,
5545 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5546 + (sampleDelta >> 32)),
5547 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005548
5549 // if the delta between the ideal placement for the next input sample and
5550 // the current output position is within this threshold, then we will
5551 // concatenate the next input samples to the previous output
5552 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005553 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005554
5555 // if this is the first buffer of audio that we're emitting from this track
5556 // then it should be almost exactly on time.
5557 const int64_t kSampleStartupThreshold = 1LL << 32;
5558
5559 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005560 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005561 // the next input is close enough to being on time, so concatenate it
5562 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005563 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005564
John Grossman1c345192012-03-27 14:00:17 -07005565 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5566 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005567 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005568 }
5569
5570 // Looks like our output is not on time. Reset our on timed status.
5571 // Next time we mix samples from our input queue, then should be within
5572 // the StartupThreshold.
5573 mTimedAudioOutputOnTime = false;
5574 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005575 // the gap between the current output position and the proper start of
5576 // the next input sample is too big, so fill it with silence
5577 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5578
John Grossman9fbdee12012-03-26 17:51:46 -07005579 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005580 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5581 return NO_ERROR;
5582 } else {
5583 // the next input sample is late
5584 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5585 size_t onTimeSamplePosition =
5586 head.position() + lateFrames * mCblk->frameSize;
5587
5588 if (onTimeSamplePosition > head.buffer()->size()) {
5589 // all the remaining samples in the head are too late, so
5590 // drop it and move on
5591 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005592 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005593 continue;
5594 } else {
5595 // skip over the late samples
5596 head.setPosition(onTimeSamplePosition);
5597
5598 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005599 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005600
5601 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5602 return NO_ERROR;
5603 }
5604 }
5605 }
5606}
5607
5608// Yield samples from the timed buffer queue head up to the given output
5609// buffer's capacity.
5610//
5611// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005612void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005613 AudioBufferProvider::Buffer* buffer) {
5614
5615 const TimedBuffer& head = mTimedBufferQueue[0];
5616
5617 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5618 head.position());
5619
5620 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5621 mCblk->frameSize);
5622 size_t framesRequested = buffer->frameCount;
5623 buffer->frameCount = min(framesLeftInHead, framesRequested);
5624
John Grossman9fbdee12012-03-26 17:51:46 -07005625 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005626 mTimedAudioOutputOnTime = true;
5627}
5628
5629// Yield samples of silence up to the given output buffer's capacity
5630//
5631// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005632void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005633 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5634
5635 // lazily allocate a buffer filled with silence
5636 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5637 delete [] mTimedSilenceBuffer;
5638 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5639 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5640 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5641 }
5642
5643 buffer->raw = mTimedSilenceBuffer;
5644 size_t framesRequested = buffer->frameCount;
5645 buffer->frameCount = min(numFrames, framesRequested);
5646
5647 mTimedAudioOutputOnTime = false;
5648}
5649
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005650// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005651void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5652 AudioBufferProvider::Buffer* buffer) {
5653
5654 Mutex::Autolock _l(mTimedBufferQueueLock);
5655
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005656 // If the buffer which was just released is part of the buffer at the head
5657 // of the queue, be sure to update the amt of the buffer which has been
5658 // consumed. If the buffer being returned is not part of the head of the
5659 // queue, its either because the buffer is part of the silence buffer, or
5660 // because the head of the timed queue was trimmed after the mixer called
5661 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005662 if (buffer->raw == mTimedSilenceBuffer) {
5663 ALOG_ASSERT(!mQueueHeadInFlight,
5664 "Queue head in flight during release of silence buffer!");
5665 goto done;
5666 }
5667
5668 ALOG_ASSERT(mQueueHeadInFlight,
5669 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5670 " head in flight.");
5671
5672 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005673 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005674
5675 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005676 void* end = reinterpret_cast<void*>(
5677 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5678 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005679
John Grossman9fbdee12012-03-26 17:51:46 -07005680 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5681 "released buffer not within the head of the timed buffer"
5682 " queue; qHead = [%p, %p], released buffer = %p",
5683 start, end, buffer->raw);
5684
5685 head.setPosition(head.position() +
5686 (buffer->frameCount * mCblk->frameSize));
5687 mQueueHeadInFlight = false;
5688
John Grossman1c345192012-03-27 14:00:17 -07005689 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5690 "Bad bookkeeping during releaseBuffer! Should have at"
5691 " least %u queued frames, but we think we have only %u",
5692 buffer->frameCount, mFramesPendingInQueue);
5693
5694 mFramesPendingInQueue -= buffer->frameCount;
5695
John Grossman9fbdee12012-03-26 17:51:46 -07005696 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5697 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005698 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005699 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005700 }
John Grossman9fbdee12012-03-26 17:51:46 -07005701 } else {
5702 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5703 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005704 }
5705
John Grossman9fbdee12012-03-26 17:51:46 -07005706done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005707 buffer->raw = 0;
5708 buffer->frameCount = 0;
5709}
5710
Glenn Kasten288ed212012-04-25 17:52:27 -07005711size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005712 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005713 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005714}
5715
5716AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5717 : mPTS(0), mPosition(0) {}
5718
5719AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5720 const sp<IMemory>& buffer, int64_t pts)
5721 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5722
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723// ----------------------------------------------------------------------------
5724
5725// RecordTrack constructor must be called with AudioFlinger::mLock held
5726AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005727 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 const sp<Client>& client,
5729 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005730 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005731 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 int sessionId)
5734 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005735 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 mOverflow(false)
5737{
5738 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005739 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5740 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5741 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5742 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5743 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5744 } else {
5745 mCblk->frameSize = sizeof(int8_t);
5746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 }
5748}
5749
5750AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5751{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005752 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753}
5754
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005755// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005756status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005757{
5758 audio_track_cblk_t* cblk = this->cblk();
5759 uint32_t framesAvail;
5760 uint32_t framesReq = buffer->frameCount;
5761
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005762 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005763 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005765 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005766 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767 }
5768
5769 framesAvail = cblk->framesAvailable_l();
5770
Glenn Kastenf6b16782011-12-15 09:51:17 -08005771 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 uint32_t s = cblk->server;
5773 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5774
5775 if (framesReq > framesAvail) {
5776 framesReq = framesAvail;
5777 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005778 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 framesReq = bufferEnd - s;
5780 }
5781
5782 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 buffer->frameCount = framesReq;
5784 return NO_ERROR;
5785 }
5786
5787getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005788 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789 buffer->frameCount = 0;
5790 return NOT_ENOUGH_DATA;
5791}
5792
Glenn Kasten3acbd052012-02-28 10:39:56 -08005793status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005794 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795{
5796 sp<ThreadBase> thread = mThread.promote();
5797 if (thread != 0) {
5798 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005799 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 } else {
5801 return BAD_VALUE;
5802 }
5803}
5804
5805void AudioFlinger::RecordThread::RecordTrack::stop()
5806{
5807 sp<ThreadBase> thread = mThread.promote();
5808 if (thread != 0) {
5809 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005810 recordThread->mLock.lock();
5811 bool doStop = recordThread->stop_l(this);
5812 if (doStop) {
5813 TrackBase::reset();
5814 // Force overrun condition to avoid false overrun callback until first data is
5815 // read from buffer
5816 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5817 }
5818 recordThread->mLock.unlock();
5819 if (doStop) {
5820 AudioSystem::stopInput(recordThread->id());
5821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 }
5823}
5824
Glenn Kasten510a3d62012-07-16 14:24:34 -07005825/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5826{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005827 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005828}
5829
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5831{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005832 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005833 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005835 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 mSessionId,
5837 mFrameCount,
5838 mState,
5839 mCblk->sampleRate,
5840 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005841 mCblk->user,
5842 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843}
5844
5845
5846// ----------------------------------------------------------------------------
5847
5848AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005849 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 DuplicatingThread *sourceThread,
5851 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005852 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005853 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005855 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5856 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 mActive(false), mSourceThread(sourceThread)
5858{
5859
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860 if (mCblk != NULL) {
5861 mCblk->flags |= CBLK_DIRECTION_OUT;
5862 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 mOutBuffer.frameCount = 0;
5864 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005865 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005866 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5867 mCblk, mBuffer, mCblk->buffers,
5868 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005870 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 }
5872}
5873
5874AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5875{
5876 clearBufferQueue();
5877}
5878
Glenn Kasten3acbd052012-02-28 10:39:56 -08005879status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005880 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005882 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 if (status != NO_ERROR) {
5884 return status;
5885 }
5886
5887 mActive = true;
5888 mRetryCount = 127;
5889 return status;
5890}
5891
5892void AudioFlinger::PlaybackThread::OutputTrack::stop()
5893{
5894 Track::stop();
5895 clearBufferQueue();
5896 mOutBuffer.frameCount = 0;
5897 mActive = false;
5898}
5899
5900bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5901{
5902 Buffer *pInBuffer;
5903 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005904 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905 bool outputBufferFull = false;
5906 inBuffer.frameCount = frames;
5907 inBuffer.i16 = data;
5908
5909 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5910
5911 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005912 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 sp<ThreadBase> thread = mThread.promote();
5914 if (thread != 0) {
5915 MixerThread *mixerThread = (MixerThread *)thread.get();
5916 if (mCblk->frameCount > frames){
5917 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5918 uint32_t startFrames = (mCblk->frameCount - frames);
5919 pInBuffer = new Buffer;
5920 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5921 pInBuffer->frameCount = startFrames;
5922 pInBuffer->i16 = pInBuffer->mBuffer;
5923 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5924 mBufferQueue.add(pInBuffer);
5925 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005926 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 }
5928 }
5929 }
5930 }
5931
5932 while (waitTimeLeftMs) {
5933 // First write pending buffers, then new data
5934 if (mBufferQueue.size()) {
5935 pInBuffer = mBufferQueue.itemAt(0);
5936 } else {
5937 pInBuffer = &inBuffer;
5938 }
5939
5940 if (pInBuffer->frameCount == 0) {
5941 break;
5942 }
5943
5944 if (mOutBuffer.frameCount == 0) {
5945 mOutBuffer.frameCount = pInBuffer->frameCount;
5946 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005947 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005948 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 outputBufferFull = true;
5950 break;
5951 }
5952 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5953 if (waitTimeLeftMs >= waitTimeMs) {
5954 waitTimeLeftMs -= waitTimeMs;
5955 } else {
5956 waitTimeLeftMs = 0;
5957 }
5958 }
5959
5960 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5961 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5962 mCblk->stepUser(outFrames);
5963 pInBuffer->frameCount -= outFrames;
5964 pInBuffer->i16 += outFrames * channelCount;
5965 mOutBuffer.frameCount -= outFrames;
5966 mOutBuffer.i16 += outFrames * channelCount;
5967
5968 if (pInBuffer->frameCount == 0) {
5969 if (mBufferQueue.size()) {
5970 mBufferQueue.removeAt(0);
5971 delete [] pInBuffer->mBuffer;
5972 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005973 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 } else {
5975 break;
5976 }
5977 }
5978 }
5979
5980 // If we could not write all frames, allocate a buffer and queue it for next time.
5981 if (inBuffer.frameCount) {
5982 sp<ThreadBase> thread = mThread.promote();
5983 if (thread != 0 && !thread->standby()) {
5984 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5985 pInBuffer = new Buffer;
5986 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5987 pInBuffer->frameCount = inBuffer.frameCount;
5988 pInBuffer->i16 = pInBuffer->mBuffer;
5989 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5990 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005991 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005993 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 }
5995 }
5996 }
5997
5998 // Calling write() with a 0 length buffer, means that no more data will be written:
5999 // If no more buffers are pending, fill output track buffer to make sure it is started
6000 // by output mixer.
6001 if (frames == 0 && mBufferQueue.size() == 0) {
6002 if (mCblk->user < mCblk->frameCount) {
6003 frames = mCblk->frameCount - mCblk->user;
6004 pInBuffer = new Buffer;
6005 pInBuffer->mBuffer = new int16_t[frames * channelCount];
6006 pInBuffer->frameCount = frames;
6007 pInBuffer->i16 = pInBuffer->mBuffer;
6008 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
6009 mBufferQueue.add(pInBuffer);
6010 } else if (mActive) {
6011 stop();
6012 }
6013 }
6014
6015 return outputBufferFull;
6016}
6017
6018status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
6019{
6020 int active;
6021 status_t result;
6022 audio_track_cblk_t* cblk = mCblk;
6023 uint32_t framesReq = buffer->frameCount;
6024
Steve Block3856b092011-10-20 11:56:00 +01006025// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 buffer->frameCount = 0;
6027
6028 uint32_t framesAvail = cblk->framesAvailable();
6029
6030
6031 if (framesAvail == 0) {
6032 Mutex::Autolock _l(cblk->lock);
6033 goto start_loop_here;
6034 while (framesAvail == 0) {
6035 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006036 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006037 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006038 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 }
6040 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6041 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006042 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 }
6044 // read the server count again
6045 start_loop_here:
6046 framesAvail = cblk->framesAvailable_l();
6047 }
6048 }
6049
6050// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006051// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052// }
6053
6054 if (framesReq > framesAvail) {
6055 framesReq = framesAvail;
6056 }
6057
6058 uint32_t u = cblk->user;
6059 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6060
Marco Nelissena1472d92012-03-30 14:36:54 -07006061 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 framesReq = bufferEnd - u;
6063 }
6064
6065 buffer->frameCount = framesReq;
6066 buffer->raw = (void *)cblk->buffer(u);
6067 return NO_ERROR;
6068}
6069
6070
6071void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6072{
6073 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074
6075 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006076 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 delete [] pBuffer->mBuffer;
6078 delete pBuffer;
6079 }
6080 mBufferQueue.clear();
6081}
6082
6083// ----------------------------------------------------------------------------
6084
6085AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6086 : RefBase(),
6087 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006088 // 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 -07006089 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006090 mPid(pid),
6091 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092{
6093 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6094}
6095
6096// Client destructor must be called with AudioFlinger::mLock held
6097AudioFlinger::Client::~Client()
6098{
6099 mAudioFlinger->removeClient_l(mPid);
6100}
6101
Glenn Kasten435dbe62012-01-30 10:15:48 -08006102sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103{
6104 return mMemoryDealer;
6105}
6106
John Grossman4ff14ba2012-02-08 16:37:41 -08006107// Reserve one of the limited slots for a timed audio track associated
6108// with this client
6109bool AudioFlinger::Client::reserveTimedTrack()
6110{
6111 const int kMaxTimedTracksPerClient = 4;
6112
6113 Mutex::Autolock _l(mTimedTrackLock);
6114
6115 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6116 ALOGW("can not create timed track - pid %d has exceeded the limit",
6117 mPid);
6118 return false;
6119 }
6120
6121 mTimedTrackCount++;
6122 return true;
6123}
6124
6125// Release a slot for a timed audio track
6126void AudioFlinger::Client::releaseTimedTrack()
6127{
6128 Mutex::Autolock _l(mTimedTrackLock);
6129 mTimedTrackCount--;
6130}
6131
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132// ----------------------------------------------------------------------------
6133
6134AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6135 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006136 sp<IBinder> binder)
6137 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138{
6139}
6140
6141AudioFlinger::NotificationClient::~NotificationClient()
6142{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143}
6144
6145void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6146{
6147 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006148 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149}
6150
6151// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006152#ifdef QCOM_HARDWARE
6153AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6154 int output, AudioSessionDescriptor *outputDesc,
6155 IDirectTrackClient* client, audio_output_flags_t outflag)
6156 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6157 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6158{
6159 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6160 createEffectThread();
6161
6162 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6163 mAudioFlinger->registerClient(mAudioFlingerClient);
6164
6165 allocateBufPool();
6166 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08006167 outputDesc->mVolumeScale = 1.0;
vivek mehta2192bc92012-12-04 11:46:08 -08006168 mDeathRecipient = new PMDeathRecipient(this);
6169 acquireWakeLock();
6170}
6171
6172AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6173 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6174 requestAndWaitForEffectsThreadExit();
6175 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6176 mAudioFlinger->deleteEffectSession();
6177 deallocateBufPool();
6178 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006179 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006180 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006181
Mingming Yin9b3dd172013-01-10 18:42:38 -08006182 {
6183 Mutex::Autolock _l(pmLock);
6184 if (mPowerManager != 0) {
6185 sp<IBinder> binder = mPowerManager->asBinder();
6186 binder->unlinkToDeath(mDeathRecipient);
6187 }
vivek mehta2192bc92012-12-04 11:46:08 -08006188 }
vivek mehta2192bc92012-12-04 11:46:08 -08006189}
6190
6191status_t AudioFlinger::DirectAudioTrack::start() {
6192 if(mIsPaused) {
6193 mIsPaused = false;
6194 mOutputDesc->stream->start(mOutputDesc->stream);
6195 }
6196 mOutputDesc->mActive = true;
6197 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6198 return NO_ERROR;
6199}
6200
6201void AudioFlinger::DirectAudioTrack::stop() {
6202 mOutputDesc->mActive = false;
6203 mOutputDesc->stream->stop(mOutputDesc->stream);
6204 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6205}
6206
6207void AudioFlinger::DirectAudioTrack::pause() {
6208 if(!mIsPaused) {
6209 mIsPaused = true;
6210 mOutputDesc->stream->pause(mOutputDesc->stream);
6211 mOutputDesc->mActive = false;
6212 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6213 }
6214}
6215
6216ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6217 ALOGV("Writing to AudioSessionOut");
6218 int isAvail = 0;
6219 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6220 if (!isAvail) {
6221 return 0;
6222 }
6223
6224 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6225 mEffectLock.lock();
6226 List<BufferInfo>::iterator it = mEffectsPool.begin();
6227 BufferInfo buf = *it;
6228 mEffectsPool.erase(it);
6229 memcpy((char *) buf.localBuf, (char *)buffer, size);
6230 buf.bytesToWrite = size;
6231 mEffectsPool.push_back(buf);
6232 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6233 mEffectLock.unlock();
6234 }
6235 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6236}
6237
6238void AudioFlinger::DirectAudioTrack::flush() {
6239 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6240 mEffectsPool.clear();
6241 mEffectsPool = mBufPool;
6242 }
6243 mOutputDesc->stream->flush(mOutputDesc->stream);
6244}
6245
6246void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6247}
6248
6249void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
Mingming Yin9b3dd172013-01-10 18:42:38 -08006250 mOutputDesc->mVolumeLeft = left;
6251 mOutputDesc->mVolumeRight = right;
Dorian Snyderf32d5702013-03-01 14:25:46 -08006252 mOutputDesc->stream->set_volume(mOutputDesc->stream,
6253 left * mOutputDesc->mVolumeScale,
6254 right* mOutputDesc->mVolumeScale);
vivek mehta2192bc92012-12-04 11:46:08 -08006255}
6256
6257int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6258 int64_t time;
6259 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6260 ALOGV("Timestamp %lld",time);
6261 return time;
6262}
6263
6264void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
6265 ALOGV("Notify Audio Track of EOS event");
6266 mClient->notify(DIRECT_TRACK_EOS);
6267}
6268
6269void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6270 void *dsp_buf = NULL;
6271 void *local_buf = NULL;
6272
6273 //1. get the ion buffer information
6274 struct buf_info* buf = NULL;
6275 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6276 ALOGV("get buffer info %p",buf);
6277 if (!buf) {
6278 ALOGV("buffer is NULL");
6279 return;
6280 }
6281 int nSize = buf->bufsize;
6282 int bufferCount = buf->nBufs;
6283
6284 //2. allocate the buffer pool, allocate local buffers
6285 for (int i = 0; i < bufferCount; i++) {
6286 dsp_buf = (void *)buf->buffers[i];
6287 local_buf = malloc(nSize);
6288 memset(local_buf, 0, nSize);
6289 // Store this information for internal mapping / maintanence
6290 BufferInfo buf(local_buf, dsp_buf, nSize);
6291 buf.bytesToWrite = 0;
6292 mBufPool.push_back(buf);
6293 mEffectsPool.push_back(buf);
6294
6295 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6296 }
6297 free(buf);
6298}
6299
6300void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6301
6302 //1. Deallocate the local memory
6303 //2. Remove all the buffers from bufpool
6304 while (!mBufPool.empty()) {
6305 List<BufferInfo>::iterator it = mBufPool.begin();
6306 BufferInfo &memBuffer = *it;
6307 // free the local buffer corresponding to mem buffer
6308 if (memBuffer.localBuf) {
6309 free(memBuffer.localBuf);
6310 memBuffer.localBuf = NULL;
6311 }
6312 ALOGV("Removing from bufpool");
6313 mBufPool.erase(it);
6314 }
6315}
6316
6317status_t AudioFlinger::DirectAudioTrack::onTransact(
6318 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6319{
6320 return BnDirectTrack::onTransact(code, data, reply, flags);
6321}
6322
6323void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6324 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6325 return NULL;
6326}
6327
6328void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6329 while(1) {
6330 mEffectLock.lock();
6331 if (!mEffectConfigChanged && !mKillEffectsThread) {
6332 mEffectCv.wait(mEffectLock);
6333 }
6334
6335 if(mKillEffectsThread) {
6336 mEffectLock.unlock();
6337 break;
6338 }
6339
6340 if (mEffectConfigChanged) {
6341 mEffectConfigChanged = false;
6342 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6343 it != mEffectsPool.end(); it++) {
6344 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6345 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6346 (int16_t *)it->localBuf,
6347 (int16_t *)it->dspBuf,
6348 it->bytesToWrite);
6349 if (mEffectConfigChanged) {
6350 break;
6351 }
6352 }
6353
6354 }
6355 mEffectLock.unlock();
6356 }
6357 ALOGV("Effects thread is dead");
6358 mEffectsThreadAlive = false;
6359}
6360
6361void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6362 if (!mEffectsThreadAlive)
6363 return;
6364 mKillEffectsThread = true;
6365 mEffectCv.signal();
6366 pthread_join(mEffectsThread,NULL);
6367 ALOGV("effects thread killed");
6368}
6369
6370void AudioFlinger::DirectAudioTrack::createEffectThread() {
6371 //Create the effects thread
6372 pthread_attr_t attr;
6373 pthread_attr_init(&attr);
6374 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6375 mEffectsThreadAlive = true;
6376 ALOGV("Creating Effects Thread");
6377 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6378}
6379AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6380{
6381 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6382 pBaseClass = (DirectAudioTrack*)obj;
6383}
6384
6385void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6386 pBaseClass->mAudioFlinger.clear();
6387 ALOGW("AudioFlinger server died!");
6388}
6389
6390void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6391 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6392 ALOGV("ioConfigChanged() event %d", event);
6393 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6394 ALOGV("Received notification for change in effect module");
6395 // Seek to current media time - flush the decoded buffers with the driver
6396 pBaseClass->mEffectConfigChanged = true;
6397 // Signal effects thread to re-apply effects
6398 ALOGV("Signalling Effects Thread");
6399 pBaseClass->mEffectCv.signal();
6400
6401 }
6402 ALOGV("ioConfigChanged Out");
6403}
6404
6405void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6406{
6407 Mutex::Autolock _l(pmLock);
6408
6409 if (mPowerManager == 0) {
6410 // use checkService() to avoid blocking if power service is not up yet
6411 sp<IBinder> binder =
6412 defaultServiceManager()->checkService(String16("power"));
6413 if (binder == 0) {
6414 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6415 } else {
6416 mPowerManager = interface_cast<IPowerManager>(binder);
6417 binder->linkToDeath(mDeathRecipient);
6418 }
6419 }
6420 if (mPowerManager != 0 && mWakeLockToken == 0) {
6421 sp<IBinder> binder = new BBinder();
6422 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6423 binder,
6424 String16(lockName));
6425 if (status == NO_ERROR) {
6426 mWakeLockToken = binder;
6427 }
6428 ALOGV("acquireWakeLock() status %d", status);
6429 }
6430}
6431
6432void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6433{
6434 Mutex::Autolock _l(pmLock);
6435
6436 if (mWakeLockToken != 0) {
6437 ALOGV("releaseWakeLock()");
6438 if (mPowerManager != 0) {
6439 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6440 }
6441 mWakeLockToken.clear();
6442 }
6443}
6444
6445void AudioFlinger::DirectAudioTrack::clearPowerManager()
6446{
vivek mehta2192bc92012-12-04 11:46:08 -08006447 releaseWakeLock();
Mingming Yin9b3dd172013-01-10 18:42:38 -08006448 Mutex::Autolock _l(pmLock);
vivek mehta2192bc92012-12-04 11:46:08 -08006449 mPowerManager.clear();
6450}
6451
6452void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6453{
6454 parentClass->clearPowerManager();
6455 ALOGW("power manager service died !!!");
6456}
6457#endif
6458
6459// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460
6461AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6462 : BnAudioTrack(),
6463 mTrack(track)
6464{
6465}
6466
6467AudioFlinger::TrackHandle::~TrackHandle() {
6468 // just stop the track on deletion, associated resources
6469 // will be freed from the main thread once all pending buffers have
6470 // been played. Unless it's not in the active track list, in which
6471 // case we free everything now...
6472 mTrack->destroy();
6473}
6474
Glenn Kasten90716c52012-01-26 13:40:12 -08006475sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6476 return mTrack->getCblk();
6477}
6478
Glenn Kasten3acbd052012-02-28 10:39:56 -08006479status_t AudioFlinger::TrackHandle::start() {
6480 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481}
6482
6483void AudioFlinger::TrackHandle::stop() {
6484 mTrack->stop();
6485}
6486
6487void AudioFlinger::TrackHandle::flush() {
6488 mTrack->flush();
6489}
6490
6491void AudioFlinger::TrackHandle::mute(bool e) {
6492 mTrack->mute(e);
6493}
6494
6495void AudioFlinger::TrackHandle::pause() {
6496 mTrack->pause();
6497}
6498
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6500{
6501 return mTrack->attachAuxEffect(EffectId);
6502}
6503
John Grossman4ff14ba2012-02-08 16:37:41 -08006504status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6505 sp<IMemory>* buffer) {
6506 if (!mTrack->isTimedTrack())
6507 return INVALID_OPERATION;
6508
6509 PlaybackThread::TimedTrack* tt =
6510 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6511 return tt->allocateTimedBuffer(size, buffer);
6512}
6513
6514status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6515 int64_t pts) {
6516 if (!mTrack->isTimedTrack())
6517 return INVALID_OPERATION;
6518
6519 PlaybackThread::TimedTrack* tt =
6520 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6521 return tt->queueTimedBuffer(buffer, pts);
6522}
6523
6524status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6525 const LinearTransform& xform, int target) {
6526
6527 if (!mTrack->isTimedTrack())
6528 return INVALID_OPERATION;
6529
6530 PlaybackThread::TimedTrack* tt =
6531 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6532 return tt->setMediaTimeTransform(
6533 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6534}
6535
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536status_t AudioFlinger::TrackHandle::onTransact(
6537 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6538{
6539 return BnAudioTrack::onTransact(code, data, reply, flags);
6540}
6541
6542// ----------------------------------------------------------------------------
6543
6544sp<IAudioRecord> AudioFlinger::openRecord(
6545 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006546 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006548 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006549 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006551 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006552 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 int *sessionId,
6554 status_t *status)
6555{
6556 sp<RecordThread::RecordTrack> recordTrack;
6557 sp<RecordHandle> recordHandle;
6558 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 status_t lStatus;
6560 RecordThread *thread;
6561 size_t inFrameCount;
6562 int lSessionId;
6563
6564 // check calling permissions
6565 if (!recordingAllowed()) {
6566 lStatus = PERMISSION_DENIED;
6567 goto Exit;
6568 }
6569
6570 // add client to list
6571 { // scope for mLock
6572 Mutex::Autolock _l(mLock);
6573 thread = checkRecordThread_l(input);
6574 if (thread == NULL) {
6575 lStatus = BAD_VALUE;
6576 goto Exit;
6577 }
6578
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006579 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580
6581 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006582 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 lSessionId = *sessionId;
6584 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006585 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 if (sessionId != NULL) {
6587 *sessionId = lSessionId;
6588 }
6589 }
6590 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006591 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6592 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006594 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6596 // destructor is called by the TrackBase destructor with mLock held
6597 client.clear();
6598 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 goto Exit;
6600 }
6601
6602 // return to handle to client
6603 recordHandle = new RecordHandle(recordTrack);
6604 lStatus = NO_ERROR;
6605
6606Exit:
6607 if (status) {
6608 *status = lStatus;
6609 }
6610 return recordHandle;
6611}
6612
6613// ----------------------------------------------------------------------------
6614
6615AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6616 : BnAudioRecord(),
6617 mRecordTrack(recordTrack)
6618{
6619}
6620
6621AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006622 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006623 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624}
6625
Glenn Kasten90716c52012-01-26 13:40:12 -08006626sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6627 return mRecordTrack->getCblk();
6628}
6629
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006630status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006631 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006632 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633}
6634
6635void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006636 stop_nonvirtual();
6637}
6638
6639void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006640 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641 mRecordTrack->stop();
6642}
6643
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644status_t AudioFlinger::RecordHandle::onTransact(
6645 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6646{
6647 return BnAudioRecord::onTransact(code, data, reply, flags);
6648}
6649
6650// ----------------------------------------------------------------------------
6651
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006652AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6653 AudioStreamIn *input,
6654 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006655 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006656 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006657 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006658 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006659 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006660 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006661 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006662 mReqSampleRate(sampleRate)
6663 // mBytesRead is only meaningful while active, and so is cleared in start()
6664 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665{
Glenn Kasten480b4682012-02-28 12:30:08 -08006666 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006667
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 readInputParameters();
6669}
6670
6671
6672AudioFlinger::RecordThread::~RecordThread()
6673{
6674 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006675 delete mResampler;
6676 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677}
6678
6679void AudioFlinger::RecordThread::onFirstRef()
6680{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006681 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682}
6683
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006684status_t AudioFlinger::RecordThread::readyToRun()
6685{
6686 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006687 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006688 return status;
6689}
6690
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691bool AudioFlinger::RecordThread::threadLoop()
6692{
6693 AudioBufferProvider::Buffer buffer;
6694 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006695 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696
Eric Laurent44d98482010-09-30 16:12:31 -07006697 nsecs_t lastWarning = 0;
6698
Glenn Kastene4e2a372012-07-23 12:55:09 -07006699 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006700 acquireWakeLock();
6701
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006702 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006703 bool readOnce = false;
6704
Mathias Agopian65ab4712010-07-14 17:59:35 -07006705 // start recording
6706 while (!exitPending()) {
6707
6708 processConfigEvents();
6709
6710 { // scope for mLock
6711 Mutex::Autolock _l(mLock);
6712 checkForNewParameters_l();
6713 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006714 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715
6716 if (exitPending()) break;
6717
Eric Laurentfeb0db62011-07-22 09:04:31 -07006718 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006719 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 // go to sleep
6721 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006722 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006723 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724 continue;
6725 }
6726 if (mActiveTrack != 0) {
6727 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006728 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 mActiveTrack.clear();
6730 mStartStopCond.broadcast();
6731 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6732 if (mReqChannelCount != mActiveTrack->channelCount()) {
6733 mActiveTrack.clear();
6734 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006735 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 // record start succeeds only if first read from audio input
6737 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006738 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006739 mActiveTrack->mState = TrackBase::ACTIVE;
6740 } else {
6741 mActiveTrack.clear();
6742 }
6743 mStartStopCond.broadcast();
6744 }
6745 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006746 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6747 removeTrack_l(mActiveTrack);
6748 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749 }
6750 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006751 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752 }
6753
6754 if (mActiveTrack != 0) {
6755 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6756 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006757 unlockEffectChains(effectChains);
6758 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 continue;
6760 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006761 for (size_t i = 0; i < effectChains.size(); i ++) {
6762 effectChains[i]->process_l();
6763 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006764
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006766 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006767 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006769 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 // no resampling
6771 while (framesOut) {
6772 size_t framesIn = mFrameCount - mRsmpInIndex;
6773 if (framesIn) {
6774 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6775 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6776 if (framesIn > framesOut)
6777 framesIn = framesOut;
6778 mRsmpInIndex += framesIn;
6779 framesOut -= framesIn;
6780 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006781 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782 memcpy(dst, src, framesIn * mFrameSize);
6783 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006785 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6786 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006788 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6789 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 }
6791 }
6792 }
6793 if (framesOut && mFrameCount == mRsmpInIndex) {
6794 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006795 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006796 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 framesOut = 0;
6798 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006799 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800 mRsmpInIndex = 0;
6801 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006802 if (mBytesRead <= 0) {
6803 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6804 {
6805 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 // Force input into standby so that it tries to
6807 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006808 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006809 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 }
6811 mRsmpInIndex = mFrameCount;
6812 framesOut = 0;
6813 buffer.frameCount = 0;
6814 }
6815 }
6816 }
6817 } else {
6818 // resampling
6819
6820 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6821 // alter output frame count as if we were expecting stereo samples
6822 if (mChannelCount == 1 && mReqChannelCount == 1) {
6823 framesOut >>= 1;
6824 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006825 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6827 // are 32 bit aligned which should be always true.
6828 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006829 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006831 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6832 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006834 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 }
6836
6837 }
Eric Laurenta011e352012-03-29 15:51:43 -07006838 if (mFramestoDrop == 0) {
6839 mActiveTrack->releaseBuffer(&buffer);
6840 } else {
6841 if (mFramestoDrop > 0) {
6842 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006843 if (mFramestoDrop <= 0) {
6844 clearSyncStartEvent();
6845 }
6846 } else {
6847 mFramestoDrop += buffer.frameCount;
6848 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6849 mSyncStartEvent->isCancelled()) {
6850 ALOGW("Synced record %s, session %d, trigger session %d",
6851 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6852 mActiveTrack->sessionId(),
6853 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6854 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006855 }
6856 }
6857 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006858 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 }
6860 // client isn't retrieving buffers fast enough
6861 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006862 if (!mActiveTrack->setOverflow()) {
6863 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006864 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006865 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006866 lastWarning = now;
6867 }
6868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 // Release the processor for a while before asking for a new buffer.
6870 // This will give the application more chance to read from the buffer and
6871 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006872 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873 }
6874 }
Eric Laurentec437d82011-07-26 20:54:46 -07006875 // enable changes in effect chain
6876 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 }
6879
Glenn Kastene4e2a372012-07-23 12:55:09 -07006880 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881
Glenn Kasten33e6e352012-07-16 15:56:57 -07006882 {
6883 Mutex::Autolock _l(mLock);
6884 mActiveTrack.clear();
6885 mStartStopCond.broadcast();
6886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887
Eric Laurentfeb0db62011-07-22 09:04:31 -07006888 releaseWakeLock();
6889
Steve Block3856b092011-10-20 11:56:00 +01006890 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 return false;
6892}
6893
Glenn Kastene4e2a372012-07-23 12:55:09 -07006894void AudioFlinger::RecordThread::standby()
6895{
6896 if (!mStandby) {
6897 inputStandBy();
6898 mStandby = true;
6899 }
6900}
6901
6902void AudioFlinger::RecordThread::inputStandBy()
6903{
6904 mInput->stream->common.standby(&mInput->stream->common);
6905}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006906
6907sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6908 const sp<AudioFlinger::Client>& client,
6909 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006910 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006911 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006912 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006913 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006914 IAudioFlinger::track_flags_t flags,
6915 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006916 status_t *status)
6917{
6918 sp<RecordTrack> track;
6919 status_t lStatus;
6920
6921 lStatus = initCheck();
6922 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006923 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006924 goto Exit;
6925 }
6926
Glenn Kasten1879fff2012-07-11 15:36:59 -07006927 // FIXME use flags and tid similar to createTrack_l()
6928
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006929 { // scope for mLock
6930 Mutex::Autolock _l(mLock);
6931
6932 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006933 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006934
Glenn Kasten7378ca52012-01-20 13:44:40 -08006935 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006936 lStatus = NO_MEMORY;
6937 goto Exit;
6938 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006939 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006940
Eric Laurent59bd0da2011-08-01 09:52:20 -07006941 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006942 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006943 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006944 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6945 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006946 }
6947 lStatus = NO_ERROR;
6948
6949Exit:
6950 if (status) {
6951 *status = lStatus;
6952 }
6953 return track;
6954}
6955
Eric Laurenta011e352012-03-29 15:51:43 -07006956status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006957 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006958 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959{
Glenn Kasten58912562012-04-03 10:45:00 -07006960 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006961 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006963
6964 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006965 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006966 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6967 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6968 triggerSession,
6969 recordTrack->sessionId(),
6970 syncStartEventCallback,
6971 this);
Eric Laurent29864602012-05-08 18:57:51 -07006972 // Sync event can be cancelled by the trigger session if the track is not in a
6973 // compatible state in which case we start record immediately
6974 if (mSyncStartEvent->isCancelled()) {
6975 clearSyncStartEvent();
6976 } else {
6977 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6978 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6979 }
Eric Laurenta011e352012-03-29 15:51:43 -07006980 }
6981
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006983 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 if (mActiveTrack != 0) {
6985 if (recordTrack != mActiveTrack.get()) {
6986 status = -EBUSY;
6987 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6988 mActiveTrack->mState = TrackBase::ACTIVE;
6989 }
6990 return status;
6991 }
6992
6993 recordTrack->mState = TrackBase::IDLE;
6994 mActiveTrack = recordTrack;
6995 mLock.unlock();
6996 status_t status = AudioSystem::startInput(mId);
6997 mLock.lock();
6998 if (status != NO_ERROR) {
6999 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07007000 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 return status;
7002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 mRsmpInIndex = mFrameCount;
7004 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08007005 if (mResampler != NULL) {
7006 mResampler->reset();
7007 }
7008 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01007010 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07007011 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08007013 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 mActiveTrack.clear();
7015 status = INVALID_OPERATION;
7016 goto startError;
7017 }
7018 mStartStopCond.wait(mLock);
7019 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007020 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 status = BAD_VALUE;
7022 goto startError;
7023 }
Steve Block3856b092011-10-20 11:56:00 +01007024 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 return status;
7026 }
7027startError:
7028 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07007029 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 return status;
7031}
7032
Eric Laurenta011e352012-03-29 15:51:43 -07007033void AudioFlinger::RecordThread::clearSyncStartEvent()
7034{
7035 if (mSyncStartEvent != 0) {
7036 mSyncStartEvent->cancel();
7037 }
7038 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007039 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007040}
7041
7042void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7043{
7044 sp<SyncEvent> strongEvent = event.promote();
7045
7046 if (strongEvent != 0) {
7047 RecordThread *me = (RecordThread *)strongEvent->cookie();
7048 me->handleSyncStartEvent(strongEvent);
7049 }
7050}
7051
7052void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7053{
Eric Laurent29864602012-05-08 18:57:51 -07007054 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007055 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7056 // from audio HAL
7057 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007058 }
7059}
7060
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007061bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007062 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007063 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7064 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007066 recordTrack->mState = TrackBase::PAUSING;
7067 // do not wait for mStartStopCond if exiting
7068 if (exitPending()) {
7069 return true;
7070 }
7071 mStartStopCond.wait(mLock);
7072 // if we have been restarted, recordTrack == mActiveTrack.get() here
7073 if (exitPending() || recordTrack != mActiveTrack.get()) {
7074 ALOGV("Record stopped OK");
7075 return true;
7076 }
7077 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078}
7079
Glenn Kasten106e8a42012-08-02 13:37:12 -07007080bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007081{
7082 return false;
7083}
7084
7085status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7086{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007087#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 -07007088 if (!isValidSyncEvent(event)) {
7089 return BAD_VALUE;
7090 }
7091
Glenn Kasten510a3d62012-07-16 14:24:34 -07007092 int eventSession = event->triggerSession();
7093 status_t ret = NAME_NOT_FOUND;
7094
Eric Laurenta011e352012-03-29 15:51:43 -07007095 Mutex::Autolock _l(mLock);
7096
Glenn Kasten510a3d62012-07-16 14:24:34 -07007097 for (size_t i = 0; i < mTracks.size(); i++) {
7098 sp<RecordTrack> track = mTracks[i];
7099 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007100 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007101 ret = NO_ERROR;
7102 }
Eric Laurenta011e352012-03-29 15:51:43 -07007103 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007104 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007105#else
7106 return BAD_VALUE;
7107#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007108}
7109
7110void AudioFlinger::RecordThread::RecordTrack::destroy()
7111{
7112 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7113 sp<RecordTrack> keep(this);
7114 {
7115 sp<ThreadBase> thread = mThread.promote();
7116 if (thread != 0) {
7117 if (mState == ACTIVE || mState == RESUMING) {
7118 AudioSystem::stopInput(thread->id());
7119 }
7120 AudioSystem::releaseInput(thread->id());
7121 Mutex::Autolock _l(thread->mLock);
7122 RecordThread *recordThread = (RecordThread *) thread.get();
7123 recordThread->destroyTrack_l(this);
7124 }
7125 }
7126}
7127
7128// destroyTrack_l() must be called with ThreadBase::mLock held
7129void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7130{
7131 track->mState = TrackBase::TERMINATED;
7132 // active tracks are removed by threadLoop()
7133 if (mActiveTrack != track) {
7134 removeTrack_l(track);
7135 }
7136}
7137
7138void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7139{
7140 mTracks.remove(track);
7141 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007142}
7143
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007144void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007145{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007146 dumpInternals(fd, args);
7147 dumpTracks(fd, args);
7148 dumpEffectChains(fd, args);
7149}
7150
7151void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7152{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 const size_t SIZE = 256;
7154 char buffer[SIZE];
7155 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156
7157 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7158 result.append(buffer);
7159
7160 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7162 result.append(buffer);
7163 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7164 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007165 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166 result.append(buffer);
7167 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7168 result.append(buffer);
7169 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7170 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007172 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007174
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175 write(fd, result.string(), result.size());
7176
7177 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007178}
7179
7180void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7181{
7182 const size_t SIZE = 256;
7183 char buffer[SIZE];
7184 String8 result;
7185
7186 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7187 result.append(buffer);
7188 RecordTrack::appendDumpHeader(result);
7189 for (size_t i = 0; i < mTracks.size(); ++i) {
7190 sp<RecordTrack> track = mTracks[i];
7191 if (track != 0) {
7192 track->dump(buffer, SIZE);
7193 result.append(buffer);
7194 }
7195 }
7196
7197 if (mActiveTrack != 0) {
7198 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7199 result.append(buffer);
7200 RecordTrack::appendDumpHeader(result);
7201 mActiveTrack->dump(buffer, SIZE);
7202 result.append(buffer);
7203
7204 }
7205 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206}
7207
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007208// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007209status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007210{
7211 size_t framesReq = buffer->frameCount;
7212 size_t framesReady = mFrameCount - mRsmpInIndex;
7213 int channelCount;
7214
7215 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007216 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007217 if (mBytesRead <= 0) {
7218 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7219 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007220 // Force input into standby so that it tries to
7221 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007222 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007223 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007225 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 buffer->frameCount = 0;
7227 return NOT_ENOUGH_DATA;
7228 }
7229 mRsmpInIndex = 0;
7230 framesReady = mFrameCount;
7231 }
7232
7233 if (framesReq > framesReady) {
7234 framesReq = framesReady;
7235 }
7236
7237 if (mChannelCount == 1 && mReqChannelCount == 2) {
7238 channelCount = 1;
7239 } else {
7240 channelCount = 2;
7241 }
7242 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7243 buffer->frameCount = framesReq;
7244 return NO_ERROR;
7245}
7246
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007247// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7249{
7250 mRsmpInIndex += buffer->frameCount;
7251 buffer->frameCount = 0;
7252}
7253
7254bool AudioFlinger::RecordThread::checkForNewParameters_l()
7255{
7256 bool reconfig = false;
7257
7258 while (!mNewParameters.isEmpty()) {
7259 status_t status = NO_ERROR;
7260 String8 keyValuePair = mNewParameters[0];
7261 AudioParameter param = AudioParameter(keyValuePair);
7262 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007263 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 int reqSamplingRate = mReqSampleRate;
7265 int reqChannelCount = mReqChannelCount;
7266
7267 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7268 reqSamplingRate = value;
7269 reconfig = true;
7270 }
7271 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007272 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 reconfig = true;
7274 }
7275 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007276 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 reconfig = true;
7278 }
7279 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7280 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007281 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282 // if frame count is changed after track creation
7283 if (mActiveTrack != 0) {
7284 status = INVALID_OPERATION;
7285 } else {
7286 reconfig = true;
7287 }
7288 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007289 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7290 // forward device change to effects that have requested to be
7291 // aware of attached audio device.
7292 for (size_t i = 0; i < mEffectChains.size(); i++) {
7293 mEffectChains[i]->setDevice_l(value);
7294 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007295
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296 // store input device and output device but do not forward output device to audio HAL.
7297 // Note that status is ignored by the caller for output device
7298 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007299 if (audio_is_output_devices(value)) {
7300 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301 status = BAD_VALUE;
7302 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007303 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007304 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007305 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007306 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7307 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007308 for (size_t i = 0; i < mTracks.size(); i++) {
7309 sp<RecordTrack> track = mTracks[i];
7310 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7311 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7312 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007313 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007314 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007315 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007316 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7317 mAudioSource != (audio_source_t)value) {
7318 // forward device change to effects that have requested to be
7319 // aware of attached audio device.
7320 for (size_t i = 0; i < mEffectChains.size(); i++) {
7321 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7322 }
7323 mAudioSource = (audio_source_t)value;
7324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007326 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007328 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007329 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7330 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 }
7332 if (reconfig) {
7333 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007334 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007335 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007336 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007337 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007338 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 status = NO_ERROR;
7340 }
7341 if (status == NO_ERROR) {
7342 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007343 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344 }
7345 }
7346 }
7347
7348 mNewParameters.removeAt(0);
7349
7350 mParamStatus = status;
7351 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007352 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7353 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007354 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 }
7356 return reconfig;
7357}
7358
7359String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7360{
Dima Zavinfce7a472011-04-19 22:30:36 -07007361 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007362 String8 out_s8 = String8();
7363
7364 Mutex::Autolock _l(mLock);
7365 if (initCheck() != NO_ERROR) {
7366 return out_s8;
7367 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007368
Dima Zavin799a70e2011-04-18 16:57:27 -07007369 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007370 out_s8 = String8(s);
7371 free(s);
7372 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373}
7374
7375void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7376 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007377 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378
7379 switch (event) {
7380 case AudioSystem::INPUT_OPENED:
7381 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007382 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 desc.samplingRate = mSampleRate;
7384 desc.format = mFormat;
7385 desc.frameCount = mFrameCount;
7386 desc.latency = 0;
7387 param2 = &desc;
7388 break;
7389
7390 case AudioSystem::INPUT_CLOSED:
7391 default:
7392 break;
7393 }
7394 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7395}
7396
7397void AudioFlinger::RecordThread::readInputParameters()
7398{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007399 delete mRsmpInBuffer;
7400 // mRsmpInBuffer is always assigned a new[] below
7401 delete mRsmpOutBuffer;
7402 mRsmpOutBuffer = NULL;
7403 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007404 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405
Dima Zavin799a70e2011-04-18 16:57:27 -07007406 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007407 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007408 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007409 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007410 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007411 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007413 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7415
Glenn Kasten53d76db2012-03-08 12:32:47 -08007416 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 {
7418 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007419 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7420 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 if (mChannelCount == 1 && mReqChannelCount == 2) {
7422 channelCount = 1;
7423 } else {
7424 channelCount = 2;
7425 }
7426 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7427 mResampler->setSampleRate(mSampleRate);
7428 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7429 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7430
7431 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7432 if (mChannelCount == 1 && mReqChannelCount == 1) {
7433 mFrameCount >>= 1;
7434 }
7435
7436 }
7437 mRsmpInIndex = mFrameCount;
7438}
7439
7440unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7441{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007442 Mutex::Autolock _l(mLock);
7443 if (initCheck() != NO_ERROR) {
7444 return 0;
7445 }
7446
Dima Zavin799a70e2011-04-18 16:57:27 -07007447 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448}
7449
Glenn Kasten106e8a42012-08-02 13:37:12 -07007450uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007451{
7452 Mutex::Autolock _l(mLock);
7453 uint32_t result = 0;
7454 if (getEffectChain_l(sessionId) != 0) {
7455 result = EFFECT_SESSION;
7456 }
7457
Glenn Kasten510a3d62012-07-16 14:24:34 -07007458 for (size_t i = 0; i < mTracks.size(); ++i) {
7459 if (sessionId == mTracks[i]->sessionId()) {
7460 result |= TRACK_SESSION;
7461 break;
7462 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007463 }
7464
7465 return result;
7466}
7467
Glenn Kasten106e8a42012-08-02 13:37:12 -07007468KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007469{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007470 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007471 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007472 for (size_t j = 0; j < mTracks.size(); ++j) {
7473 sp<RecordThread::RecordTrack> track = mTracks[j];
7474 int sessionId = track->sessionId();
7475 if (ids.indexOfKey(sessionId) < 0) {
7476 ids.add(sessionId, true);
7477 }
7478 }
7479 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007480}
7481
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007482AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7483{
7484 Mutex::Autolock _l(mLock);
7485 AudioStreamIn *input = mInput;
7486 mInput = NULL;
7487 return input;
7488}
7489
7490// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007491audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007492{
7493 if (mInput == NULL) {
7494 return NULL;
7495 }
7496 return &mInput->stream->common;
7497}
7498
7499
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500// ----------------------------------------------------------------------------
7501
Eric Laurenta4c5a552012-03-29 10:12:40 -07007502audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7503{
7504 if (!settingsAllowed()) {
7505 return 0;
7506 }
7507 Mutex::Autolock _l(mLock);
7508 return loadHwModule_l(name);
7509}
7510
7511// loadHwModule_l() must be called with AudioFlinger::mLock held
7512audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7513{
7514 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7515 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7516 ALOGW("loadHwModule() module %s already loaded", name);
7517 return mAudioHwDevs.keyAt(i);
7518 }
7519 }
7520
Eric Laurenta4c5a552012-03-29 10:12:40 -07007521 audio_hw_device_t *dev;
7522
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007523 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007524 if (rc) {
7525 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7526 return 0;
7527 }
7528
7529 mHardwareStatus = AUDIO_HW_INIT;
7530 rc = dev->init_check(dev);
7531 mHardwareStatus = AUDIO_HW_IDLE;
7532 if (rc) {
7533 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7534 return 0;
7535 }
7536
John Grossmanee578c02012-07-23 17:05:46 -07007537 // Check and cache this HAL's level of support for master mute and master
7538 // volume. If this is the first HAL opened, and it supports the get
7539 // methods, use the initial values provided by the HAL as the current
7540 // master mute and volume settings.
7541
7542 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7543 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007544 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007545
madmack2f8d3672013-01-14 21:19:20 -05007546#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007547 if (0 == mAudioHwDevs.size()) {
7548 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7549 if (NULL != dev->get_master_volume) {
7550 float mv;
7551 if (OK == dev->get_master_volume(dev, &mv)) {
7552 mMasterVolume = mv;
7553 }
7554 }
7555
7556 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7557 if (NULL != dev->get_master_mute) {
7558 bool mm;
7559 if (OK == dev->get_master_mute(dev, &mm)) {
7560 mMasterMute = mm;
7561 }
7562 }
7563 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007564#endif
John Grossmanee578c02012-07-23 17:05:46 -07007565
Eric Laurenta4c5a552012-03-29 10:12:40 -07007566 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007567 if ((NULL != dev->set_master_volume) &&
7568 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7569 flags = static_cast<AudioHwDevice::Flags>(flags |
7570 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7571 }
7572
madmack2f8d3672013-01-14 21:19:20 -05007573#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007574 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7575 if ((NULL != dev->set_master_mute) &&
7576 (OK == dev->set_master_mute(dev, mMasterMute))) {
7577 flags = static_cast<AudioHwDevice::Flags>(flags |
7578 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7579 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007580#endif
John Grossmanee578c02012-07-23 17:05:46 -07007581
Eric Laurenta4c5a552012-03-29 10:12:40 -07007582 mHardwareStatus = AUDIO_HW_IDLE;
7583 }
7584
7585 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007586 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007587
7588 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007589 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007590
7591 return handle;
7592
7593}
7594
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007595// ----------------------------------------------------------------------------
7596
7597int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7598{
7599 Mutex::Autolock _l(mLock);
7600 PlaybackThread *thread = primaryPlaybackThread_l();
7601 return thread != NULL ? thread->sampleRate() : 0;
7602}
7603
7604int32_t AudioFlinger::getPrimaryOutputFrameCount()
7605{
7606 Mutex::Autolock _l(mLock);
7607 PlaybackThread *thread = primaryPlaybackThread_l();
7608 return thread != NULL ? thread->frameCountHAL() : 0;
7609}
7610
7611// ----------------------------------------------------------------------------
7612
Eric Laurenta4c5a552012-03-29 10:12:40 -07007613audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7614 audio_devices_t *pDevices,
7615 uint32_t *pSamplingRate,
7616 audio_format_t *pFormat,
7617 audio_channel_mask_t *pChannelMask,
7618 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007619 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620{
7621 status_t status;
7622 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007623 struct audio_config config = {
7624 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7625 channel_mask: pChannelMask ? *pChannelMask : 0,
7626 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7627 };
7628 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007629 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630
Eric Laurenta4c5a552012-03-29 10:12:40 -07007631 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7632 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007633 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007634 config.sample_rate,
7635 config.format,
7636 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007637 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638
7639 if (pDevices == NULL || *pDevices == 0) {
7640 return 0;
7641 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007642
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 Mutex::Autolock _l(mLock);
7644
Eric Laurenta4c5a552012-03-29 10:12:40 -07007645 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007646 if (outHwDev == NULL)
7647 return 0;
7648
John Grossmanee578c02012-07-23 17:05:46 -07007649 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007650 audio_io_handle_t id = nextUniqueId();
7651
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007652 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007653
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007654#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007655 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007656 id,
7657 *pDevices,
7658 (audio_output_flags_t)flags,
7659 &config,
7660 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007661#else
7662 status = hwDevHal->open_output_stream(hwDevHal,
7663 *pDevices,
7664 (int *)&config.format,
7665 &config.channel_mask,
7666 &config.sample_rate,
7667 &outStream);
7668 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7669 flags = (audio_output_flags_t)newflags;
7670#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007671
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007672 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007674 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007675 config.sample_rate,
7676 config.format,
7677 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 status);
7679
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007680 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007681 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007682#ifdef QCOM_HARDWARE
7683 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7684 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7685 desc->mActive = true;
7686 //TODO: no stream type
7687 //desc->mStreamType = streamType;
7688 desc->mVolumeLeft = 1.0;
7689 desc->mVolumeRight = 1.0;
7690 desc->device = *pDevices;
7691 mDirectAudioTracks.add(id, desc);
7692 } else
7693#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007694 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007695 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7696 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007698 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699 } else {
7700 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007701 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702 }
vivek mehta2192bc92012-12-04 11:46:08 -08007703#ifdef QCOM_HARDWARE
7704 if (thread != NULL)
7705#endif
7706 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707
Dorian Snyderf32d5702013-03-01 14:25:46 -08007708#ifdef QCOM_HARDWARE
7709 // if the device is a A2DP, then this is an A2DP Output
7710 if ( true == audio_is_a2dp_device((audio_devices_t) *pDevices) )
7711 {
7712 mA2DPHandle = id;
7713 ALOGV("A2DP device activated. The handle is set to %d", mA2DPHandle);
7714 }
7715#endif
7716
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007717 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7718 if (pFormat != NULL) *pFormat = config.format;
7719 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007720#ifdef QCOM_HARDWARE
7721 if (thread != NULL) {
7722#endif
7723 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7724 // notify client processes of the new output creation
7725 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7726#ifdef QCOM_HARDWARE
7727 }
7728 else {
7729 *pLatencyMs = 0;
7730 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7731 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7732 *pLatencyMs = desc->stream->get_latency(desc->stream);
7733 }
7734 }
7735#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007736 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007737 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007738 ALOGI("Using module %d has the primary audio interface", module);
7739 mPrimaryHardwareDev = outHwDev;
7740
7741 AutoMutex lock(mHardwareLock);
7742 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007743 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007744 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007745 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746 return id;
7747 }
7748
7749 return 0;
7750}
7751
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007752audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7753 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754{
7755 Mutex::Autolock _l(mLock);
7756 MixerThread *thread1 = checkMixerThread_l(output1);
7757 MixerThread *thread2 = checkMixerThread_l(output2);
7758
7759 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007760 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761 return 0;
7762 }
7763
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007764 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7766 thread->addOutputTrack(thread2);
7767 mPlaybackThreads.add(id, thread);
7768 // notify client processes of the new output creation
7769 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7770 return id;
7771}
7772
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007773status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774{
Glenn Kastend96c5722012-04-25 13:44:49 -07007775 return closeOutput_nonvirtual(output);
7776}
7777
7778status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7779{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 // keep strong reference on the playback thread so that
7781 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007782#ifdef QCOM_HARDWARE
7783 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7784 if (desc) {
7785 ALOGV("Closing DirectTrack output %d", output);
7786 desc->mActive = false;
7787 desc->stream->common.standby(&desc->stream->common);
7788 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7789 desc->trackRefPtr = NULL;
7790 mDirectAudioTracks.removeItem(output);
7791 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7792 delete desc;
7793 return NO_ERROR;
7794 }
7795#endif
7796
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007797 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 {
7799 Mutex::Autolock _l(mLock);
7800 thread = checkPlaybackThread_l(output);
7801 if (thread == NULL) {
7802 return BAD_VALUE;
7803 }
7804
Steve Block3856b092011-10-20 11:56:00 +01007805 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007807 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007808 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007809 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7811 dupThread->removeOutputTrack((MixerThread *)thread.get());
7812 }
7813 }
7814 }
Glenn Kastena1117922012-01-26 10:53:32 -08007815 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 mPlaybackThreads.removeItem(output);
Dorian Snyderf32d5702013-03-01 14:25:46 -08007817#ifdef QCOM_HARDWARE
7818 if (mA2DPHandle == output)
7819 {
7820 mA2DPHandle = -1;
7821 ALOGV("A2DP OutputClosed Notifying Client");
7822 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
7823 }
7824#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 }
7826 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007827 // The thread entity (active unit of execution) is no longer running here,
7828 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007830 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007831 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007832 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007833 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007834 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007835 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836 }
7837 return NO_ERROR;
7838}
7839
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007840status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841{
7842 Mutex::Autolock _l(mLock);
7843 PlaybackThread *thread = checkPlaybackThread_l(output);
7844
7845 if (thread == NULL) {
7846 return BAD_VALUE;
7847 }
7848
Steve Block3856b092011-10-20 11:56:00 +01007849 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007850 thread->suspend();
7851
7852 return NO_ERROR;
7853}
7854
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007855status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856{
7857 Mutex::Autolock _l(mLock);
7858 PlaybackThread *thread = checkPlaybackThread_l(output);
7859
7860 if (thread == NULL) {
7861 return BAD_VALUE;
7862 }
7863
Steve Block3856b092011-10-20 11:56:00 +01007864 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865
7866 thread->restore();
7867
7868 return NO_ERROR;
7869}
7870
Eric Laurenta4c5a552012-03-29 10:12:40 -07007871audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7872 audio_devices_t *pDevices,
7873 uint32_t *pSamplingRate,
7874 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007875 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876{
7877 status_t status;
7878 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007879 struct audio_config config = {
7880 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7881 channel_mask: pChannelMask ? *pChannelMask : 0,
7882 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7883 };
7884 uint32_t reqSamplingRate = config.sample_rate;
7885 audio_format_t reqFormat = config.format;
7886 audio_channel_mask_t reqChannels = config.channel_mask;
7887 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007888 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889
7890 if (pDevices == NULL || *pDevices == 0) {
7891 return 0;
7892 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007893
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 Mutex::Autolock _l(mLock);
7895
Eric Laurenta4c5a552012-03-29 10:12:40 -07007896 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007897 if (inHwDev == NULL)
7898 return 0;
7899
John Grossmanee578c02012-07-23 17:05:46 -07007900 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007901 audio_io_handle_t id = nextUniqueId();
7902
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007903#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007904 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007905 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007906#else
7907 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7908 (int *)&config.format,
7909 &config.channel_mask,
7910 &config.sample_rate, (audio_in_acoustics_t)0,
7911 &inStream);
7912#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007913 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007914 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007915 config.sample_rate,
7916 config.format,
7917 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 status);
7919
7920 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7921 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7922 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007923 if (status == BAD_VALUE &&
7924 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7925 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007926 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007927 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007928 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007929#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007930 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007931#else
7932 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7933 (int *)&config.format,
7934 &config.channel_mask,
7935 &config.sample_rate, (audio_in_acoustics_t)0,
7936 &inStream);
7937#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 }
7939
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007940 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007941 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7942
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007943 // Start record thread
7944 // RecorThread require both input and output device indication to forward to audio
7945 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007946 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007947 thread = new RecordThread(this,
7948 input,
7949 reqSamplingRate,
7950 reqChannels,
7951 id,
7952 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007953 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007954 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007955 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007956 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007957 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007958
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 // notify client processes of the new input creation
7960 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7961 return id;
7962 }
7963
7964 return 0;
7965}
7966
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007967status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968{
Glenn Kastend96c5722012-04-25 13:44:49 -07007969 return closeInput_nonvirtual(input);
7970}
7971
7972status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7973{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007974 // keep strong reference on the record thread so that
7975 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007976 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977 {
7978 Mutex::Autolock _l(mLock);
7979 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007980 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981 return BAD_VALUE;
7982 }
7983
Steve Block3856b092011-10-20 11:56:00 +01007984 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007985 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986 mRecordThreads.removeItem(input);
7987 }
7988 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007989 // The thread entity (active unit of execution) is no longer running here,
7990 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007992 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007993 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007994 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007995 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007996 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997
7998 return NO_ERROR;
7999}
8000
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008001status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008002{
8003 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008004 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005
8006 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8007 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07008008 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07008009 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08008010#ifdef QCOM_HARDWARE
8011 if ( mA2DPHandle == output ) {
8012 ALOGV("A2DP Activated and hence notifying the client");
8013 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &output);
8014 }
8015#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016
8017 return NO_ERROR;
8018}
8019
8020
8021int AudioFlinger::newAudioSessionId()
8022{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008023 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024}
8025
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008026void AudioFlinger::acquireAudioSessionId(int audioSession)
8027{
8028 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008029 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008030 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008031 size_t num = mAudioSessionRefs.size();
8032 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008033 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008034 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8035 ref->mCnt++;
8036 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008037 return;
8038 }
8039 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08008040 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
8041 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008042}
8043
8044void AudioFlinger::releaseAudioSessionId(int audioSession)
8045{
8046 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008047 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008048 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008049 size_t num = mAudioSessionRefs.size();
8050 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008051 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008052 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8053 ref->mCnt--;
8054 ALOGV(" decremented refcount to %d", ref->mCnt);
8055 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008056 mAudioSessionRefs.removeAt(i);
8057 delete ref;
8058 purgeStaleEffects_l();
8059 }
8060 return;
8061 }
8062 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008063 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008064}
8065
8066void AudioFlinger::purgeStaleEffects_l() {
8067
Steve Block3856b092011-10-20 11:56:00 +01008068 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008069
8070 Vector< sp<EffectChain> > chains;
8071
8072 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8073 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8074 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8075 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008076 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8077 chains.push(ec);
8078 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008079 }
8080 }
8081 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8082 sp<RecordThread> t = mRecordThreads.valueAt(i);
8083 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8084 sp<EffectChain> ec = t->mEffectChains[j];
8085 chains.push(ec);
8086 }
8087 }
8088
8089 for (size_t i = 0; i < chains.size(); i++) {
8090 sp<EffectChain> ec = chains[i];
8091 int sessionid = ec->sessionId();
8092 sp<ThreadBase> t = ec->mThread.promote();
8093 if (t == 0) {
8094 continue;
8095 }
8096 size_t numsessionrefs = mAudioSessionRefs.size();
8097 bool found = false;
8098 for (size_t k = 0; k < numsessionrefs; k++) {
8099 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008100 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008101 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008102 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008103 found = true;
8104 break;
8105 }
8106 }
8107 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008108 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008109 // remove all effects from the chain
8110 while (ec->mEffects.size()) {
8111 sp<EffectModule> effect = ec->mEffects[0];
8112 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008113 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008114 if (effect->purgeHandles()) {
8115 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008116 }
8117 AudioSystem::unregisterEffect(effect->id());
8118 }
8119 }
8120 }
8121 return;
8122}
8123
Mathias Agopian65ab4712010-07-14 17:59:35 -07008124// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008125AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008126{
Glenn Kastena1117922012-01-26 10:53:32 -08008127 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128}
8129
8130// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008131AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132{
8133 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008134 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135}
8136
8137// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008138AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139{
Glenn Kastena1117922012-01-26 10:53:32 -08008140 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141}
8142
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008143uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008145 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008146}
8147
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008148AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008149{
8150 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8151 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008152 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008153 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008154 return thread;
8155 }
8156 }
8157 return NULL;
8158}
8159
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008160audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008161{
8162 PlaybackThread *thread = primaryPlaybackThread_l();
8163
8164 if (thread == NULL) {
8165 return 0;
8166 }
8167
Eric Laurentf1c04f92012-08-28 14:26:53 -07008168 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008169}
8170
Eric Laurenta011e352012-03-29 15:51:43 -07008171sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8172 int triggerSession,
8173 int listenerSession,
8174 sync_event_callback_t callBack,
8175 void *cookie)
8176{
8177 Mutex::Autolock _l(mLock);
8178
8179 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8180 status_t playStatus = NAME_NOT_FOUND;
8181 status_t recStatus = NAME_NOT_FOUND;
8182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8183 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8184 if (playStatus == NO_ERROR) {
8185 return event;
8186 }
8187 }
8188 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8189 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8190 if (recStatus == NO_ERROR) {
8191 return event;
8192 }
8193 }
8194 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8195 mPendingSyncEvents.add(event);
8196 } else {
8197 ALOGV("createSyncEvent() invalid event %d", event->type());
8198 event.clear();
8199 }
8200 return event;
8201}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008202
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203// ----------------------------------------------------------------------------
8204// Effect management
8205// ----------------------------------------------------------------------------
8206
8207
Glenn Kastenf587ba52012-01-26 16:25:10 -08008208status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209{
8210 Mutex::Autolock _l(mLock);
8211 return EffectQueryNumberEffects(numEffects);
8212}
8213
Glenn Kastenf587ba52012-01-26 16:25:10 -08008214status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215{
8216 Mutex::Autolock _l(mLock);
8217 return EffectQueryEffect(index, descriptor);
8218}
8219
Glenn Kasten5e92a782012-01-30 07:40:52 -08008220status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008221 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008222{
8223 Mutex::Autolock _l(mLock);
8224 return EffectGetDescriptor(pUuid, descriptor);
8225}
8226
8227
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8229 effect_descriptor_t *pDesc,
8230 const sp<IEffectClient>& effectClient,
8231 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008232 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008233 int sessionId,
8234 status_t *status,
8235 int *id,
8236 int *enabled)
8237{
8238 status_t lStatus = NO_ERROR;
8239 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008240 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008241
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008242 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008243 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008244
8245 if (pDesc == NULL) {
8246 lStatus = BAD_VALUE;
8247 goto Exit;
8248 }
8249
Eric Laurent84e9a102010-09-23 16:10:16 -07008250 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008251 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008252 lStatus = PERMISSION_DENIED;
8253 goto Exit;
8254 }
8255
Dima Zavinfce7a472011-04-19 22:30:36 -07008256 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008257 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008258 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008259 lStatus = PERMISSION_DENIED;
8260 goto Exit;
8261 }
8262
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008263 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008264 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008265 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008266 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008267 lStatus = BAD_VALUE;
8268 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008269 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008270 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008271 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008272 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008273 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008274 }
8275 }
8276
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277 {
8278 Mutex::Autolock _l(mLock);
8279
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280
8281 if (!EffectIsNullUuid(&pDesc->uuid)) {
8282 // if uuid is specified, request effect descriptor
8283 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8284 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008285 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286 goto Exit;
8287 }
8288 } else {
8289 // if uuid is not specified, look for an available implementation
8290 // of the required type in effect factory
8291 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008292 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 lStatus = BAD_VALUE;
8294 goto Exit;
8295 }
8296 uint32_t numEffects = 0;
8297 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008298 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008299 bool found = false;
8300
8301 lStatus = EffectQueryNumberEffects(&numEffects);
8302 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008303 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 goto Exit;
8305 }
8306 for (uint32_t i = 0; i < numEffects; i++) {
8307 lStatus = EffectQueryEffect(i, &desc);
8308 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008309 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310 continue;
8311 }
8312 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8313 // If matching type found save effect descriptor. If the session is
8314 // 0 and the effect is not auxiliary, continue enumeration in case
8315 // an auxiliary version of this effect type is available
8316 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008317 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008318 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8320 break;
8321 }
8322 }
8323 }
8324 if (!found) {
8325 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008326 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008327 goto Exit;
8328 }
8329 // For same effect type, chose auxiliary version over insert version if
8330 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008331 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008332 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008333 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008334 }
8335 }
8336
8337 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008338 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8340 lStatus = INVALID_OPERATION;
8341 goto Exit;
8342 }
8343
Eric Laurent59255e42011-07-27 19:49:51 -07008344 // check recording permission for visualizer
8345 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8346 !recordingAllowed()) {
8347 lStatus = PERMISSION_DENIED;
8348 goto Exit;
8349 }
8350
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008352 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008353
8354 // If output is not specified try to find a matching audio session ID in one of the
8355 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008356 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8357 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008358 // Note: io is never 0 when creating an effect on an input
8359 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008360 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008361 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8362 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008363 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008364 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008366 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008367 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008368 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8369 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8370 io = mRecordThreads.keyAt(i);
8371 break;
8372 }
8373 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008374 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008375 // If no output thread contains the requested session ID, default to
8376 // first output. The effect chain will be moved to the correct output
8377 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008378 if (io == 0 && mPlaybackThreads.size()) {
8379 io = mPlaybackThreads.keyAt(0);
8380 }
Steve Block3856b092011-10-20 11:56:00 +01008381 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008382 }
8383 ThreadBase *thread = checkRecordThread_l(io);
8384 if (thread == NULL) {
8385 thread = checkPlaybackThread_l(io);
8386 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008387 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008388 lStatus = BAD_VALUE;
8389 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008391 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008392
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008393 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008395 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008396 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8397 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008398 if (handle != 0 && id != NULL) {
8399 *id = handle->id();
8400 }
8401 }
8402
8403Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008404 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 *status = lStatus;
8406 }
8407 return handle;
8408}
8409
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008410status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8411 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008412{
Steve Block3856b092011-10-20 11:56:00 +01008413 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008414 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008415 Mutex::Autolock _l(mLock);
8416 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008417 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008418 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 }
Eric Laurentde070132010-07-13 04:45:46 -07008420 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8421 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008422 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008423 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424 }
Eric Laurentde070132010-07-13 04:45:46 -07008425 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8426 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008427 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008428 return BAD_VALUE;
8429 }
8430
8431 Mutex::Autolock _dl(dstThread->mLock);
8432 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008433 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008434
Mathias Agopian65ab4712010-07-14 17:59:35 -07008435 return NO_ERROR;
8436}
8437
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008438// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008439status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008440 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008441 AudioFlinger::PlaybackThread *dstThread,
8442 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008443{
Steve Block3856b092011-10-20 11:56:00 +01008444 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008445 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008446
Eric Laurent59255e42011-07-27 19:49:51 -07008447 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008448 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008449 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008450 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008451 return INVALID_OPERATION;
8452 }
8453
Eric Laurent39e94f82010-07-28 01:32:47 -07008454 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008455 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008456 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008457 // removed.
8458 srcThread->removeEffectChain_l(chain);
8459
8460 // transfer all effects one by one so that new effect chain is created on new thread with
8461 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008462 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008463 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008464 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008465 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8466 while (effect != 0) {
8467 srcThread->removeEffect_l(effect);
8468 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008469 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8470 if (effect->state() == EffectModule::ACTIVE ||
8471 effect->state() == EffectModule::STOPPING) {
8472 effect->start();
8473 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008474 // if the move request is not received from audio policy manager, the effect must be
8475 // re-registered with the new strategy and output
8476 if (dstChain == 0) {
8477 dstChain = effect->chain().promote();
8478 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008479 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008480 srcThread->addEffect_l(effect);
8481 return NO_INIT;
8482 }
8483 strategy = dstChain->strategy();
8484 }
8485 if (reRegister) {
8486 AudioSystem::unregisterEffect(effect->id());
8487 AudioSystem::registerEffect(&effect->desc(),
8488 dstOutput,
8489 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008490 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008491 effect->id());
8492 }
Eric Laurentde070132010-07-13 04:45:46 -07008493 effect = chain->getEffectFromId_l(0);
8494 }
8495
8496 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497}
8498
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008499
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008501sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008502 const sp<AudioFlinger::Client>& client,
8503 const sp<IEffectClient>& effectClient,
8504 int32_t priority,
8505 int sessionId,
8506 effect_descriptor_t *desc,
8507 int *enabled,
8508 status_t *status
8509 )
8510{
8511 sp<EffectModule> effect;
8512 sp<EffectHandle> handle;
8513 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008514 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008515 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516 bool effectCreated = false;
8517 bool effectRegistered = false;
8518
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008519 lStatus = initCheck();
8520 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008521 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 goto Exit;
8523 }
8524
8525 // Do not allow effects with session ID 0 on direct output or duplicating threads
8526 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008527 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008528 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008529 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 lStatus = BAD_VALUE;
8531 goto Exit;
8532 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008533 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008534 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008535 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008536 desc->name, desc->flags, mType);
8537 lStatus = BAD_VALUE;
8538 goto Exit;
8539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008540
Steve Block3856b092011-10-20 11:56:00 +01008541 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008542
8543 { // scope for mLock
8544 Mutex::Autolock _l(mLock);
8545
8546 // check for existing effect chain with the requested audio session
8547 chain = getEffectChain_l(sessionId);
8548 if (chain == 0) {
8549 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008550 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 chain = new EffectChain(this, sessionId);
8552 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008553 chain->setStrategy(getStrategyForSession_l(sessionId));
8554 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008555#ifdef QCOM_HARDWARE
8556 if(sessionId == mAudioFlinger->mLPASessionId) {
8557 // Clear reference to previous effect chain if any
8558 if(mAudioFlinger->mLPAEffectChain.get()) {
8559 mAudioFlinger->mLPAEffectChain.clear();
8560 }
8561 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8562 mAudioFlinger->mLPAEffectChain = chain;
8563 chain->setLPAFlag(true);
8564 // For LPA, the volume will be applied in DSP. No need for volume
8565 // control in the Effect chain, so setting it to unity.
8566 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8567 chain->setVolume_l(&volume,&volume);
8568 }
8569#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008570 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008571 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008572 }
8573
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008574 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575
8576 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008577 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008579 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008580 if (lStatus != NO_ERROR) {
8581 goto Exit;
8582 }
8583 effectRegistered = true;
8584 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008585 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586 lStatus = effect->status();
8587 if (lStatus != NO_ERROR) {
8588 goto Exit;
8589 }
Eric Laurentcab11242010-07-15 12:50:15 -07008590 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008591 if (lStatus != NO_ERROR) {
8592 goto Exit;
8593 }
8594 effectCreated = true;
8595
Eric Laurentf1c04f92012-08-28 14:26:53 -07008596 effect->setDevice(mOutDevice);
8597 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008598 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008599 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008600#ifdef QCOM_HARDWARE
8601 if(chain == mAudioFlinger->mLPAEffectChain) {
8602 effect->setLPAFlag(true);
8603 }
8604#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008605 }
8606 // create effect handle and connect it to effect module
8607 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008608 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008609 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610 *enabled = (int)effect->isEnabled();
8611 }
8612 }
8613
8614Exit:
8615 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008616 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008617 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008618 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008619 }
8620 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008621 AudioSystem::unregisterEffect(effect->id());
8622 }
8623 if (chainCreated) {
8624 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 }
8626 handle.clear();
8627 }
8628
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008629 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008630 *status = lStatus;
8631 }
8632 return handle;
8633}
8634
Eric Laurent717e1282012-06-29 16:36:52 -07008635sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8636{
8637 Mutex::Autolock _l(mLock);
8638 return getEffect_l(sessionId, effectId);
8639}
8640
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008641sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8642{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008643 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008644 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008645}
8646
Eric Laurentde070132010-07-13 04:45:46 -07008647// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8648// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008649status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008650{
8651 // check for existing effect chain with the requested audio session
8652 int sessionId = effect->sessionId();
8653 sp<EffectChain> chain = getEffectChain_l(sessionId);
8654 bool chainCreated = false;
8655
8656 if (chain == 0) {
8657 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008658 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008659 chain = new EffectChain(this, sessionId);
8660 addEffectChain_l(chain);
8661 chain->setStrategy(getStrategyForSession_l(sessionId));
8662 chainCreated = true;
8663 }
Steve Block3856b092011-10-20 11:56:00 +01008664 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008665
8666 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008667 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008668 this, effect->desc().name, chain.get());
8669 return BAD_VALUE;
8670 }
8671
8672 status_t status = chain->addEffect_l(effect);
8673 if (status != NO_ERROR) {
8674 if (chainCreated) {
8675 removeEffectChain_l(chain);
8676 }
8677 return status;
8678 }
8679
Eric Laurentf1c04f92012-08-28 14:26:53 -07008680 effect->setDevice(mOutDevice);
8681 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008682 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008683 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008684 return NO_ERROR;
8685}
8686
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008687void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008688
Steve Block3856b092011-10-20 11:56:00 +01008689 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008691 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8692 detachAuxEffect_l(effect->id());
8693 }
8694
8695 sp<EffectChain> chain = effect->chain().promote();
8696 if (chain != 0) {
8697 // remove effect chain if removing last effect
8698 if (chain->removeEffect_l(effect) == 0) {
8699 removeEffectChain_l(chain);
8700 }
8701 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008702 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008703 }
8704}
8705
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008706void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008707 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008708{
8709 effectChains = mEffectChains;
8710 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008711#ifdef QCOM_HARDWARE
8712 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8713#endif
8714 mEffectChains[i]->lock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008715 }
8716}
8717
8718void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008719 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008720{
8721 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008722#ifdef QCOM_HARDWARE
8723 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
8724#endif
8725 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008726 }
8727}
8728
8729sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8730{
8731 Mutex::Autolock _l(mLock);
8732 return getEffectChain_l(sessionId);
8733}
8734
Glenn Kasten106e8a42012-08-02 13:37:12 -07008735sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008736{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008737 size_t size = mEffectChains.size();
8738 for (size_t i = 0; i < size; i++) {
8739 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008740 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008741 }
8742 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008743 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008744}
8745
Glenn Kastenf78aee72012-01-04 11:00:47 -08008746void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008747{
8748 Mutex::Autolock _l(mLock);
8749 size_t size = mEffectChains.size();
8750 for (size_t i = 0; i < size; i++) {
8751 mEffectChains[i]->setMode_l(mode);
8752 }
8753}
8754
8755void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008756 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008757 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008758
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008760 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761 // delete the effect module if removing last handle on it
8762 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008763 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008764 removeEffect_l(effect);
8765 AudioSystem::unregisterEffect(effect->id());
8766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767 }
8768}
8769
8770status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8771{
8772 int session = chain->sessionId();
8773 int16_t *buffer = mMixBuffer;
8774 bool ownsBuffer = false;
8775
Steve Block3856b092011-10-20 11:56:00 +01008776 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008777 if (session > 0) {
8778 // Only one effect chain can be present in direct output thread and it uses
8779 // the mix buffer as input
8780 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008781 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008782 buffer = new int16_t[numSamples];
8783 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008784 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785 ownsBuffer = true;
8786 }
8787
8788 // Attach all tracks with same session ID to this chain.
8789 for (size_t i = 0; i < mTracks.size(); ++i) {
8790 sp<Track> track = mTracks[i];
8791 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008792 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008793 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008794 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008795 }
8796 }
8797
8798 // indicate all active tracks in the chain
8799 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8800 sp<Track> track = mActiveTracks[i].promote();
8801 if (track == 0) continue;
8802 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008803 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008804 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008805 }
8806 }
8807 }
8808
8809 chain->setInBuffer(buffer, ownsBuffer);
8810 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008811 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008812 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008813 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8814 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008815 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008816 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8817 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008818 // Effect chain for other sessions are inserted at beginning of effect
8819 // chains list to be processed before output mix effects. Relative order between other
8820 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 size_t size = mEffectChains.size();
8822 size_t i = 0;
8823 for (i = 0; i < size; i++) {
8824 if (mEffectChains[i]->sessionId() < session) break;
8825 }
8826 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008827 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008828
8829 return NO_ERROR;
8830}
8831
8832size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8833{
8834 int session = chain->sessionId();
8835
Steve Block3856b092011-10-20 11:56:00 +01008836 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008837
8838 for (size_t i = 0; i < mEffectChains.size(); i++) {
8839 if (chain == mEffectChains[i]) {
8840 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008841 // detach all active tracks from the chain
8842 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8843 sp<Track> track = mActiveTracks[i].promote();
8844 if (track == 0) continue;
8845 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008846 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008847 chain.get(), session);
8848 chain->decActiveTrackCnt();
8849 }
8850 }
8851
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852 // detach all tracks with same session ID from this chain
8853 for (size_t i = 0; i < mTracks.size(); ++i) {
8854 sp<Track> track = mTracks[i];
8855 if (session == track->sessionId()) {
8856 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008857 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008858 }
8859 }
Eric Laurentde070132010-07-13 04:45:46 -07008860 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008861 }
8862 }
8863 return mEffectChains.size();
8864}
8865
Eric Laurentde070132010-07-13 04:45:46 -07008866status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8867 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868{
8869 Mutex::Autolock _l(mLock);
8870 return attachAuxEffect_l(track, EffectId);
8871}
8872
Eric Laurentde070132010-07-13 04:45:46 -07008873status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8874 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008875{
8876 status_t status = NO_ERROR;
8877
8878 if (EffectId == 0) {
8879 track->setAuxBuffer(0, NULL);
8880 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008881 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8882 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 if (effect != 0) {
8884 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8885 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8886 } else {
8887 status = INVALID_OPERATION;
8888 }
8889 } else {
8890 status = BAD_VALUE;
8891 }
8892 }
8893 return status;
8894}
8895
8896void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8897{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008898 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899 sp<Track> track = mTracks[i];
8900 if (track->auxEffectId() == effectId) {
8901 attachAuxEffect_l(track, 0);
8902 }
8903 }
8904}
8905
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008906status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8907{
8908 // only one chain per input thread
8909 if (mEffectChains.size() != 0) {
8910 return INVALID_OPERATION;
8911 }
Steve Block3856b092011-10-20 11:56:00 +01008912 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008913
8914 chain->setInBuffer(NULL);
8915 chain->setOutBuffer(NULL);
8916
Eric Laurent59255e42011-07-27 19:49:51 -07008917 checkSuspendOnAddEffectChain_l(chain);
8918
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008919 mEffectChains.add(chain);
8920
8921 return NO_ERROR;
8922}
8923
8924size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8925{
Steve Block3856b092011-10-20 11:56:00 +01008926 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008927 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008928 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8929 chain.get(), mEffectChains.size(), this);
8930 if (mEffectChains.size() == 1) {
8931 mEffectChains.removeAt(0);
8932 }
8933 return 0;
8934}
8935
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936// ----------------------------------------------------------------------------
8937// EffectModule implementation
8938// ----------------------------------------------------------------------------
8939
8940#undef LOG_TAG
8941#define LOG_TAG "AudioFlinger::EffectModule"
8942
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008943AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008944 const wp<AudioFlinger::EffectChain>& chain,
8945 effect_descriptor_t *desc,
8946 int id,
8947 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008948 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8949 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008950 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008951 // mConfig is set by configure() and not used before then
8952 mEffectInterface(NULL),
8953 mStatus(NO_INIT), mState(IDLE),
8954 // mMaxDisableWaitCnt is set by configure() and not used before then
8955 // mDisableWaitCnt is set by process() and updateState() and not used before then
8956 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08008957#ifdef QCOM_HARDWARE
8958 ,mIsForLPA(false)
8959#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008960{
Steve Block3856b092011-10-20 11:56:00 +01008961 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963
8964 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008965 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008966
8967 if (mStatus != NO_ERROR) {
8968 return;
8969 }
8970 lStatus = init();
8971 if (lStatus < 0) {
8972 mStatus = lStatus;
8973 goto Error;
8974 }
8975
Steve Block3856b092011-10-20 11:56:00 +01008976 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 return;
8978Error:
8979 EffectRelease(mEffectInterface);
8980 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008981 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982}
8983
8984AudioFlinger::EffectModule::~EffectModule()
8985{
Steve Block3856b092011-10-20 11:56:00 +01008986 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008987 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008988 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8989 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8990 sp<ThreadBase> thread = mThread.promote();
8991 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008992 audio_stream_t *stream = thread->stream();
8993 if (stream != NULL) {
8994 stream->remove_audio_effect(stream, mEffectInterface);
8995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008996 }
8997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008998 // release effect engine
8999 EffectRelease(mEffectInterface);
9000 }
9001}
9002
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009003status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009004{
9005 status_t status;
9006
9007 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 int priority = handle->priority();
9009 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009010 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009011 size_t i;
9012 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009013 EffectHandle *h = mHandles[i];
9014 if (h == NULL || h->destroyed_l()) continue;
9015 // first non destroyed handle is considered in control
9016 if (controlHandle == NULL)
9017 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018 if (h->priority() <= priority) break;
9019 }
9020 // if inserted in first place, move effect control from previous owner to this handle
9021 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07009022 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009023 if (controlHandle != NULL) {
9024 enabled = controlHandle->enabled();
9025 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009026 }
Eric Laurent59255e42011-07-27 19:49:51 -07009027 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028 status = NO_ERROR;
9029 } else {
9030 status = ALREADY_EXISTS;
9031 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009032 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009033 mHandles.insertAt(handle, i);
9034 return status;
9035}
9036
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009037size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038{
9039 Mutex::Autolock _l(mLock);
9040 size_t size = mHandles.size();
9041 size_t i;
9042 for (i = 0; i < size; i++) {
9043 if (mHandles[i] == handle) break;
9044 }
9045 if (i == size) {
9046 return size;
9047 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009048 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07009049
Mathias Agopian65ab4712010-07-14 17:59:35 -07009050 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009052 if (i == 0) {
9053 EffectHandle *h = controlHandle_l();
9054 if (h != NULL) {
9055 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056 }
9057 }
9058
Eric Laurentec437d82011-07-26 20:54:46 -07009059 // Prevent calls to process() and other functions on effect interface from now on.
9060 // The effect engine will be released by the destructor when the last strong reference on
9061 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009062 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009063 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009064 }
9065
Eric Laurente65c8912012-07-20 15:57:23 -07009066 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009067}
9068
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009069// must be called with EffectModule::mLock held
9070AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009071{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009072 // the first valid handle in the list has control over the module
9073 for (size_t i = 0; i < mHandles.size(); i++) {
9074 EffectHandle *h = mHandles[i];
9075 if (h != NULL && !h->destroyed_l()) {
9076 return h;
9077 }
9078 }
9079
9080 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009081}
9082
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009083size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009084{
vivek mehta2192bc92012-12-04 11:46:08 -08009085#ifdef QCOM_HARDWARE
9086 setEnabled(false);
9087#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009088 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089 // keep a strong reference on this EffectModule to avoid calling the
9090 // destructor before we exit
9091 sp<EffectModule> keep(this);
9092 {
9093 sp<ThreadBase> thread = mThread.promote();
9094 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009095 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009096 }
9097 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009098 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009099}
9100
9101void AudioFlinger::EffectModule::updateState() {
9102 Mutex::Autolock _l(mLock);
9103
9104 switch (mState) {
9105 case RESTART:
9106 reset_l();
9107 // FALL THROUGH
9108
9109 case STARTING:
9110 // clear auxiliary effect input buffer for next accumulation
9111 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9112 memset(mConfig.inputCfg.buffer.raw,
9113 0,
9114 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9115 }
9116 start_l();
9117 mState = ACTIVE;
9118 break;
9119 case STOPPING:
9120 stop_l();
9121 mDisableWaitCnt = mMaxDisableWaitCnt;
9122 mState = STOPPED;
9123 break;
9124 case STOPPED:
9125 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9126 // turn off sequence.
9127 if (--mDisableWaitCnt == 0) {
9128 reset_l();
9129 mState = IDLE;
9130 }
9131 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009132 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009133 break;
9134 }
9135}
9136
9137void AudioFlinger::EffectModule::process()
9138{
9139 Mutex::Autolock _l(mLock);
9140
Eric Laurentec437d82011-07-26 20:54:46 -07009141 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142 mConfig.inputCfg.buffer.raw == NULL ||
9143 mConfig.outputCfg.buffer.raw == NULL) {
9144 return;
9145 }
9146
Eric Laurent8f45bd72010-08-31 13:50:07 -07009147 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009148 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9149 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009150 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009151 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009152 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009153 }
9154
9155 // do the actual processing in the effect engine
9156 int ret = (*mEffectInterface)->process(mEffectInterface,
9157 &mConfig.inputCfg.buffer,
9158 &mConfig.outputCfg.buffer);
9159
9160 // force transition to IDLE state when engine is ready
9161 if (mState == STOPPED && ret == -ENODATA) {
9162 mDisableWaitCnt = 1;
9163 }
9164
9165 // clear auxiliary effect input buffer for next accumulation
9166 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009167 memset(mConfig.inputCfg.buffer.raw, 0,
9168 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009169 }
9170 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009171 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9172 // If an insert effect is idle and input buffer is different from output buffer,
9173 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009174 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009175 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009176 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9177 int16_t *in = mConfig.inputCfg.buffer.s16;
9178 int16_t *out = mConfig.outputCfg.buffer.s16;
9179 for (size_t i = 0; i < frameCnt; i++) {
9180 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009182 }
9183 }
9184}
9185
9186void AudioFlinger::EffectModule::reset_l()
9187{
9188 if (mEffectInterface == NULL) {
9189 return;
9190 }
9191 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9192}
9193
vivek mehta2192bc92012-12-04 11:46:08 -08009194#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009195status_t AudioFlinger::EffectModule::configure()
9196{
vivek mehta2192bc92012-12-04 11:46:08 -08009197#else
9198status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9199{
9200 uint32_t channels;
9201
9202 // Acquire lock here to make sure that any other thread does not delete
9203 // the effect handle and release the effect module.
9204 Mutex::Autolock _l(mLock);
9205#endif
9206
Mathias Agopian65ab4712010-07-14 17:59:35 -07009207 if (mEffectInterface == NULL) {
9208 return NO_INIT;
9209 }
9210
9211 sp<ThreadBase> thread = mThread.promote();
9212 if (thread == 0) {
9213 return DEAD_OBJECT;
9214 }
9215
9216 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009217 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009218#ifdef QCOM_HARDWARE
9219 mIsForLPA = isForLPA;
9220 if(isForLPA) {
9221 if (channelCount == 1) {
9222 channels = AUDIO_CHANNEL_OUT_MONO;
9223 } else {
9224 channels = AUDIO_CHANNEL_OUT_STEREO;
9225 }
9226 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9227 } else {
9228 if (thread->channelCount() == 1) {
9229 channels = AUDIO_CHANNEL_OUT_MONO;
9230 } else {
9231 channels = AUDIO_CHANNEL_OUT_STEREO;
9232 }
9233 }
9234#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235
9236 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009237 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009239 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009240 }
Glenn Kasten254af182012-07-03 14:59:05 -07009241 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009242 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9243 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009244#ifdef QCOM_HARDWARE
9245 if(isForLPA){
9246 mConfig.inputCfg.samplingRate = sampleRate;
9247 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9248 } else
9249#endif
9250 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009251 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9252 mConfig.inputCfg.bufferProvider.cookie = NULL;
9253 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9254 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9255 mConfig.outputCfg.bufferProvider.cookie = NULL;
9256 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9257 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9258 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9259 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009260 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009261 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009262 // - in other sessions:
9263 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9264 // other effect: overwrites output buffer: input buffer == output buffer
9265 // Auxiliary effect:
9266 // accumulates in output buffer: input buffer != output buffer
9267 // Therefore: accumulate <=> input buffer != output buffer
9268 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9269 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9270 } else {
9271 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9272 }
9273 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9274 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009275#ifdef QCOM_HARDWARE
9276 if(isForLPA) {
9277 mConfig.inputCfg.buffer.frameCount = frameCount;
9278 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9279 } else
9280#endif
9281 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9283
Steve Block3856b092011-10-20 11:56:00 +01009284 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009285 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9286
Mathias Agopian65ab4712010-07-14 17:59:35 -07009287 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009288 uint32_t size = sizeof(int);
9289 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009290 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009291 sizeof(effect_config_t),
9292 &mConfig,
9293 &size,
9294 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009295 if (status == 0) {
9296 status = cmdStatus;
9297 }
9298
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009299 if (status == 0 &&
9300 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9301 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9302 effect_param_t *p = (effect_param_t *)buf32;
9303
9304 p->psize = sizeof(uint32_t);
9305 p->vsize = sizeof(uint32_t);
9306 size = sizeof(int);
9307 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9308
9309 uint32_t latency = 0;
9310 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9311 if (pbt != NULL) {
9312 latency = pbt->latency_l();
9313 }
9314
9315 *((int32_t *)p->data + 1)= latency;
9316 (*mEffectInterface)->command(mEffectInterface,
9317 EFFECT_CMD_SET_PARAM,
9318 sizeof(effect_param_t) + 8,
9319 &buf32,
9320 &size,
9321 &cmdStatus);
9322 }
9323
Mathias Agopian65ab4712010-07-14 17:59:35 -07009324 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9325 (1000 * mConfig.outputCfg.buffer.frameCount);
9326
9327 return status;
9328}
9329
9330status_t AudioFlinger::EffectModule::init()
9331{
9332 Mutex::Autolock _l(mLock);
9333 if (mEffectInterface == NULL) {
9334 return NO_INIT;
9335 }
9336 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009337 uint32_t size = sizeof(status_t);
9338 status_t status = (*mEffectInterface)->command(mEffectInterface,
9339 EFFECT_CMD_INIT,
9340 0,
9341 NULL,
9342 &size,
9343 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009344 if (status == 0) {
9345 status = cmdStatus;
9346 }
9347 return status;
9348}
9349
Eric Laurentec35a142011-10-05 17:42:25 -07009350status_t AudioFlinger::EffectModule::start()
9351{
9352 Mutex::Autolock _l(mLock);
9353 return start_l();
9354}
9355
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356status_t AudioFlinger::EffectModule::start_l()
9357{
9358 if (mEffectInterface == NULL) {
9359 return NO_INIT;
9360 }
9361 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009362 uint32_t size = sizeof(status_t);
9363 status_t status = (*mEffectInterface)->command(mEffectInterface,
9364 EFFECT_CMD_ENABLE,
9365 0,
9366 NULL,
9367 &size,
9368 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009369 if (status == 0) {
9370 status = cmdStatus;
9371 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009372 if (status == 0 &&
9373 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9374 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9375 sp<ThreadBase> thread = mThread.promote();
9376 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009377 audio_stream_t *stream = thread->stream();
9378 if (stream != NULL) {
9379 stream->add_audio_effect(stream, mEffectInterface);
9380 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009381 }
9382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383 return status;
9384}
9385
Eric Laurentec437d82011-07-26 20:54:46 -07009386status_t AudioFlinger::EffectModule::stop()
9387{
9388 Mutex::Autolock _l(mLock);
9389 return stop_l();
9390}
9391
Mathias Agopian65ab4712010-07-14 17:59:35 -07009392status_t AudioFlinger::EffectModule::stop_l()
9393{
9394 if (mEffectInterface == NULL) {
9395 return NO_INIT;
9396 }
9397 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009398 uint32_t size = sizeof(status_t);
9399 status_t status = (*mEffectInterface)->command(mEffectInterface,
9400 EFFECT_CMD_DISABLE,
9401 0,
9402 NULL,
9403 &size,
9404 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009405 if (status == 0) {
9406 status = cmdStatus;
9407 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009408 if (status == 0 &&
9409 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9410 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9411 sp<ThreadBase> thread = mThread.promote();
9412 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009413 audio_stream_t *stream = thread->stream();
9414 if (stream != NULL) {
9415 stream->remove_audio_effect(stream, mEffectInterface);
9416 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009417 }
9418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009419 return status;
9420}
9421
Eric Laurent25f43952010-07-28 05:40:18 -07009422status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9423 uint32_t cmdSize,
9424 void *pCmdData,
9425 uint32_t *replySize,
9426 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009427{
9428 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009429// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009430
Eric Laurentec437d82011-07-26 20:54:46 -07009431 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009432 return NO_INIT;
9433 }
Eric Laurent25f43952010-07-28 05:40:18 -07009434 status_t status = (*mEffectInterface)->command(mEffectInterface,
9435 cmdCode,
9436 cmdSize,
9437 pCmdData,
9438 replySize,
9439 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009440 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009441 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009442 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009443 EffectHandle *h = mHandles[i];
9444 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009445 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9446 }
9447 }
9448 }
9449 return status;
9450}
9451
9452status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9453{
9454 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009455 return setEnabled_l(enabled);
9456}
9457
9458// must be called with EffectModule::mLock held
9459status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9460{
vivek mehta2192bc92012-12-04 11:46:08 -08009461#ifdef QCOM_HARDWARE
9462 bool effectStateChanged = false;
9463#endif
Steve Block3856b092011-10-20 11:56:00 +01009464 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009465
9466 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009467#ifdef QCOM_HARDWARE
9468 effectStateChanged = true;
9469#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009470 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9471 if (enabled && status != NO_ERROR) {
9472 return status;
9473 }
9474
Mathias Agopian65ab4712010-07-14 17:59:35 -07009475 switch (mState) {
9476 // going from disabled to enabled
9477 case IDLE:
9478 mState = STARTING;
9479 break;
9480 case STOPPED:
9481 mState = RESTART;
9482 break;
9483 case STOPPING:
9484 mState = ACTIVE;
9485 break;
9486
9487 // going from enabled to disabled
9488 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009489 mState = STOPPED;
9490 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009491 case STARTING:
9492 mState = IDLE;
9493 break;
9494 case ACTIVE:
9495 mState = STOPPING;
9496 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009497 case DESTROYED:
9498 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009499 }
9500 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009501 EffectHandle *h = mHandles[i];
9502 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009503 h->setEnabled(enabled);
9504 }
9505 }
9506 }
vivek mehta2192bc92012-12-04 11:46:08 -08009507#ifdef QCOM_HARDWARE
9508 /*
9509 Send notification event to LPA Player when an effect for
9510 LPA output is enabled or disabled.
9511 */
9512 if (effectStateChanged && mIsForLPA) {
9513 sp<ThreadBase> thread = mThread.promote();
9514 thread->effectConfigChanged();
9515 }
9516#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009517 return NO_ERROR;
9518}
9519
Glenn Kastenc59c0042012-02-02 14:06:11 -08009520bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009521{
9522 switch (mState) {
9523 case RESTART:
9524 case STARTING:
9525 case ACTIVE:
9526 return true;
9527 case IDLE:
9528 case STOPPING:
9529 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009530 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009531 default:
9532 return false;
9533 }
9534}
9535
Glenn Kastenc59c0042012-02-02 14:06:11 -08009536bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009537{
9538 switch (mState) {
9539 case RESTART:
9540 case ACTIVE:
9541 case STOPPING:
9542 case STOPPED:
9543 return true;
9544 case IDLE:
9545 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009546 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009547 default:
9548 return false;
9549 }
9550}
9551
Mathias Agopian65ab4712010-07-14 17:59:35 -07009552status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9553{
9554 Mutex::Autolock _l(mLock);
9555 status_t status = NO_ERROR;
9556
9557 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9558 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009559 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009560 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9561 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009562 status_t cmdStatus;
9563 uint32_t volume[2];
9564 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009565 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009566 volume[0] = *left;
9567 volume[1] = *right;
9568 if (controller) {
9569 pVolume = volume;
9570 }
Eric Laurent25f43952010-07-28 05:40:18 -07009571 status = (*mEffectInterface)->command(mEffectInterface,
9572 EFFECT_CMD_SET_VOLUME,
9573 size,
9574 volume,
9575 &size,
9576 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009577 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9578 *left = volume[0];
9579 *right = volume[1];
9580 }
9581 }
9582 return status;
9583}
9584
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009585status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009586{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009587 if (device == AUDIO_DEVICE_NONE) {
9588 return NO_ERROR;
9589 }
9590
Mathias Agopian65ab4712010-07-14 17:59:35 -07009591 Mutex::Autolock _l(mLock);
9592 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009593 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009594 status_t cmdStatus;
9595 uint32_t size = sizeof(status_t);
9596 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9597 EFFECT_CMD_SET_INPUT_DEVICE;
9598 status = (*mEffectInterface)->command(mEffectInterface,
9599 cmd,
9600 sizeof(uint32_t),
9601 &device,
9602 &size,
9603 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009604 }
9605 return status;
9606}
9607
Glenn Kastenf78aee72012-01-04 11:00:47 -08009608status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009609{
9610 Mutex::Autolock _l(mLock);
9611 status_t status = NO_ERROR;
9612 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009613 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009614 uint32_t size = sizeof(status_t);
9615 status = (*mEffectInterface)->command(mEffectInterface,
9616 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009617 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009618 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009619 &size,
9620 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009621 if (status == NO_ERROR) {
9622 status = cmdStatus;
9623 }
9624 }
9625 return status;
9626}
9627
Eric Laurent57b2dd12012-08-31 17:44:06 -07009628status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9629{
9630 Mutex::Autolock _l(mLock);
9631 status_t status = NO_ERROR;
9632 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9633 uint32_t size = 0;
9634 status = (*mEffectInterface)->command(mEffectInterface,
9635 EFFECT_CMD_SET_AUDIO_SOURCE,
9636 sizeof(audio_source_t),
9637 &source,
9638 &size,
9639 NULL);
9640 }
9641 return status;
9642}
9643
Eric Laurent59255e42011-07-27 19:49:51 -07009644void AudioFlinger::EffectModule::setSuspended(bool suspended)
9645{
9646 Mutex::Autolock _l(mLock);
9647 mSuspended = suspended;
9648}
Glenn Kastena3a85482012-01-04 11:01:11 -08009649
9650bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009651{
9652 Mutex::Autolock _l(mLock);
9653 return mSuspended;
9654}
9655
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009656bool AudioFlinger::EffectModule::purgeHandles()
9657{
9658 bool enabled = false;
9659 Mutex::Autolock _l(mLock);
9660 for (size_t i = 0; i < mHandles.size(); i++) {
9661 EffectHandle *handle = mHandles[i];
9662 if (handle != NULL && !handle->destroyed_l()) {
9663 handle->effect().clear();
9664 if (handle->hasControl()) {
9665 enabled = handle->enabled();
9666 }
9667 }
9668 }
9669 return enabled;
9670}
9671
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009672void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009673{
9674 const size_t SIZE = 256;
9675 char buffer[SIZE];
9676 String8 result;
9677
9678 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9679 result.append(buffer);
9680
9681 bool locked = tryLock(mLock);
9682 // failed to lock - AudioFlinger is probably deadlocked
9683 if (!locked) {
9684 result.append("\t\tCould not lock Fx mutex:\n");
9685 }
9686
9687 result.append("\t\tSession Status State Engine:\n");
9688 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9689 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9690 result.append(buffer);
9691
9692 result.append("\t\tDescriptor:\n");
9693 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9694 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9695 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9696 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9697 result.append(buffer);
9698 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9699 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9700 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9701 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9702 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009703 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009704 mDescriptor.apiVersion,
9705 mDescriptor.flags);
9706 result.append(buffer);
9707 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9708 mDescriptor.name);
9709 result.append(buffer);
9710 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9711 mDescriptor.implementor);
9712 result.append(buffer);
9713
9714 result.append("\t\t- Input configuration:\n");
9715 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9716 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9717 (uint32_t)mConfig.inputCfg.buffer.raw,
9718 mConfig.inputCfg.buffer.frameCount,
9719 mConfig.inputCfg.samplingRate,
9720 mConfig.inputCfg.channels,
9721 mConfig.inputCfg.format);
9722 result.append(buffer);
9723
9724 result.append("\t\t- Output configuration:\n");
9725 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9726 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9727 (uint32_t)mConfig.outputCfg.buffer.raw,
9728 mConfig.outputCfg.buffer.frameCount,
9729 mConfig.outputCfg.samplingRate,
9730 mConfig.outputCfg.channels,
9731 mConfig.outputCfg.format);
9732 result.append(buffer);
9733
9734 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9735 result.append(buffer);
9736 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9737 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009738 EffectHandle *handle = mHandles[i];
9739 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009740 handle->dump(buffer, SIZE);
9741 result.append(buffer);
9742 }
9743 }
9744
9745 result.append("\n");
9746
9747 write(fd, result.string(), result.length());
9748
9749 if (locked) {
9750 mLock.unlock();
9751 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009752}
9753
9754// ----------------------------------------------------------------------------
9755// EffectHandle implementation
9756// ----------------------------------------------------------------------------
9757
9758#undef LOG_TAG
9759#define LOG_TAG "AudioFlinger::EffectHandle"
9760
9761AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9762 const sp<AudioFlinger::Client>& client,
9763 const sp<IEffectClient>& effectClient,
9764 int32_t priority)
9765 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009766 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009767 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009768{
Steve Block3856b092011-10-20 11:56:00 +01009769 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009770
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009771 if (client == 0) {
9772 return;
9773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009774 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9775 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9776 if (mCblkMemory != 0) {
9777 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9778
Glenn Kastena0d68332012-01-27 16:47:15 -08009779 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009780 new(mCblk) effect_param_cblk_t();
9781 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009783 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009784 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009785 return;
9786 }
9787}
9788
9789AudioFlinger::EffectHandle::~EffectHandle()
9790{
Steve Block3856b092011-10-20 11:56:00 +01009791 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009792
9793 if (mEffect == 0) {
9794 mDestroyed = true;
9795 return;
9796 }
9797 mEffect->lock();
9798 mDestroyed = true;
9799 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009800 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009801}
9802
9803status_t AudioFlinger::EffectHandle::enable()
9804{
Steve Block3856b092011-10-20 11:56:00 +01009805 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009806 if (!mHasControl) return INVALID_OPERATION;
9807 if (mEffect == 0) return DEAD_OBJECT;
9808
Eric Laurentdb7c0792011-08-10 10:37:50 -07009809 if (mEnabled) {
9810 return NO_ERROR;
9811 }
9812
Eric Laurent59255e42011-07-27 19:49:51 -07009813 mEnabled = true;
9814
9815 sp<ThreadBase> thread = mEffect->thread().promote();
9816 if (thread != 0) {
9817 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9818 }
9819
9820 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9821 if (mEffect->suspended()) {
9822 return NO_ERROR;
9823 }
9824
Eric Laurentdb7c0792011-08-10 10:37:50 -07009825 status_t status = mEffect->setEnabled(true);
9826 if (status != NO_ERROR) {
9827 if (thread != 0) {
9828 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9829 }
9830 mEnabled = false;
9831 }
9832 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009833}
9834
9835status_t AudioFlinger::EffectHandle::disable()
9836{
Steve Block3856b092011-10-20 11:56:00 +01009837 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009838 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009839 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009840
Eric Laurentdb7c0792011-08-10 10:37:50 -07009841 if (!mEnabled) {
9842 return NO_ERROR;
9843 }
Eric Laurent59255e42011-07-27 19:49:51 -07009844 mEnabled = false;
9845
9846 if (mEffect->suspended()) {
9847 return NO_ERROR;
9848 }
9849
9850 status_t status = mEffect->setEnabled(false);
9851
9852 sp<ThreadBase> thread = mEffect->thread().promote();
9853 if (thread != 0) {
9854 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9855 }
9856
9857 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009858}
9859
9860void AudioFlinger::EffectHandle::disconnect()
9861{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009862 disconnect(true);
9863}
9864
Glenn Kasten58123c32012-02-03 10:32:24 -08009865void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009866{
Glenn Kasten58123c32012-02-03 10:32:24 -08009867 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009868 if (mEffect == 0) {
9869 return;
9870 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009871 // restore suspended effects if the disconnected handle was enabled and the last one.
9872 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009873 sp<ThreadBase> thread = mEffect->thread().promote();
9874 if (thread != 0) {
9875 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9876 }
Eric Laurent59255e42011-07-27 19:49:51 -07009877 }
9878
Mathias Agopian65ab4712010-07-14 17:59:35 -07009879 // release sp on module => module destructor can be called now
9880 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009881 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009882 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009883 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009884 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9885 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009886 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009887 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009888 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9889 mClient.clear();
9890 }
9891}
9892
Eric Laurent25f43952010-07-28 05:40:18 -07009893status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9894 uint32_t cmdSize,
9895 void *pCmdData,
9896 uint32_t *replySize,
9897 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009898{
Steve Block3856b092011-10-20 11:56:00 +01009899// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009900// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009901
9902 // only get parameter command is permitted for applications not controlling the effect
9903 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9904 return INVALID_OPERATION;
9905 }
9906 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009907 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009908
9909 // handle commands that are not forwarded transparently to effect engine
9910 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9911 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9912 // no risk to block the whole media server process or mixer threads is we are stuck here
9913 Mutex::Autolock _l(mCblk->lock);
9914 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9915 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9916 mCblk->serverIndex = 0;
9917 mCblk->clientIndex = 0;
9918 return BAD_VALUE;
9919 }
9920 status_t status = NO_ERROR;
9921 while (mCblk->serverIndex < mCblk->clientIndex) {
9922 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009923 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009924 int *p = (int *)(mBuffer + mCblk->serverIndex);
9925 int size = *p++;
9926 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009927 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009928 break;
9929 }
9930 effect_param_t *param = (effect_param_t *)p;
9931 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009932 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009933 mCblk->serverIndex += size;
9934 continue;
9935 }
Eric Laurent25f43952010-07-28 05:40:18 -07009936 uint32_t psize = sizeof(effect_param_t) +
9937 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9938 param->vsize;
9939 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9940 psize,
9941 p,
9942 &rsize,
9943 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009944 // stop at first error encountered
9945 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009946 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009947 *(int *)pReplyData = reply;
9948 break;
9949 } else if (reply != NO_ERROR) {
9950 *(int *)pReplyData = reply;
9951 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009952 }
9953 mCblk->serverIndex += size;
9954 }
9955 mCblk->serverIndex = 0;
9956 mCblk->clientIndex = 0;
9957 return status;
9958 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009959 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009960 return enable();
9961 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009962 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009963 return disable();
9964 }
9965
vivek mehta2192bc92012-12-04 11:46:08 -08009966#ifdef QCOM_HARDWARE
9967 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
9968 if(mEffect->isOnLPA() &&
9969 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
9970 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
9971 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
9972 // Notify Direct track for the change in Effect module
9973 // TODO: check if it is required to send mLPAHandle
9974 ALOGV("Notifying Direct Track for the change in effect config");
9975 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
9976 }
9977#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009978 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9979}
9980
Eric Laurent59255e42011-07-27 19:49:51 -07009981void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009982{
Steve Block3856b092011-10-20 11:56:00 +01009983 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009984
9985 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009986 mEnabled = enabled;
9987
Mathias Agopian65ab4712010-07-14 17:59:35 -07009988 if (signal && mEffectClient != 0) {
9989 mEffectClient->controlStatusChanged(hasControl);
9990 }
9991}
9992
Eric Laurent25f43952010-07-28 05:40:18 -07009993void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9994 uint32_t cmdSize,
9995 void *pCmdData,
9996 uint32_t replySize,
9997 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009998{
9999 if (mEffectClient != 0) {
10000 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10001 }
10002}
10003
10004
10005
10006void AudioFlinger::EffectHandle::setEnabled(bool enabled)
10007{
10008 if (mEffectClient != 0) {
10009 mEffectClient->enableStatusChanged(enabled);
10010 }
10011}
10012
10013status_t AudioFlinger::EffectHandle::onTransact(
10014 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10015{
10016 return BnEffect::onTransact(code, data, reply, flags);
10017}
10018
10019
10020void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
10021{
Glenn Kastena0d68332012-01-27 16:47:15 -080010022 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010023
10024 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -080010025 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -070010026 mPriority,
10027 mHasControl,
10028 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -070010029 mCblk ? mCblk->clientIndex : 0,
10030 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070010031 );
10032
10033 if (locked) {
10034 mCblk->lock.unlock();
10035 }
10036}
10037
10038#undef LOG_TAG
10039#define LOG_TAG "AudioFlinger::EffectChain"
10040
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010041AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010042 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010043 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -070010044 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
10045 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -080010046#ifdef QCOM_HARDWARE
10047 ,mIsForLPATrack(false)
10048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010049{
Dima Zavinfce7a472011-04-19 22:30:36 -070010050 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010051 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010052 return;
10053 }
10054 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
10055 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010056}
10057
10058AudioFlinger::EffectChain::~EffectChain()
10059{
10060 if (mOwnInBuffer) {
10061 delete mInBuffer;
10062 }
10063
10064}
10065
Eric Laurent59255e42011-07-27 19:49:51 -070010066// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010067sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010068{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010069 size_t size = mEffects.size();
10070
10071 for (size_t i = 0; i < size; i++) {
10072 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010073 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010074 }
10075 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010076 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010077}
10078
Eric Laurent59255e42011-07-27 19:49:51 -070010079// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010080sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010081{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010082 size_t size = mEffects.size();
10083
10084 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010085 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10086 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010087 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010088 }
10089 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010090 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010091}
10092
vivek mehta2192bc92012-12-04 11:46:08 -080010093#ifdef QCOM_HARDWARE
10094sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10095{
10096 sp<EffectModule> effect = NULL;
10097 if(idx < 0 || idx >= mEffects.size()) {
10098 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10099 }
10100 if(mEffects.size() > 0){
10101 effect = mEffects[idx];
10102 }
10103 return effect;
10104}
10105#endif
10106
Eric Laurent59255e42011-07-27 19:49:51 -070010107// getEffectFromType_l() must be called with ThreadBase::mLock held
10108sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10109 const effect_uuid_t *type)
10110{
Eric Laurent59255e42011-07-27 19:49:51 -070010111 size_t size = mEffects.size();
10112
10113 for (size_t i = 0; i < size; i++) {
10114 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010115 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010116 }
10117 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010118 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010119}
10120
Eric Laurent91b14c42012-05-30 12:30:29 -070010121void AudioFlinger::EffectChain::clearInputBuffer()
10122{
10123 Mutex::Autolock _l(mLock);
10124 sp<ThreadBase> thread = mThread.promote();
10125 if (thread == 0) {
10126 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10127 return;
10128 }
10129 clearInputBuffer_l(thread);
10130}
10131
10132// Must be called with EffectChain::mLock locked
10133void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10134{
10135 size_t numSamples = thread->frameCount() * thread->channelCount();
10136 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10137
10138}
10139
Mathias Agopian65ab4712010-07-14 17:59:35 -070010140// Must be called with EffectChain::mLock locked
10141void AudioFlinger::EffectChain::process_l()
10142{
Eric Laurentdac69112010-09-28 14:09:57 -070010143 sp<ThreadBase> thread = mThread.promote();
10144 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010145 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010146 return;
10147 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010148 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10149 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010150 // always process effects unless no more tracks are on the session and the effect tail
10151 // has been rendered
10152 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010153 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010154 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010155
Eric Laurent544fe9b2011-11-11 15:42:52 -080010156 if (!tracksOnSession && mTailBufferCount == 0) {
10157 doProcess = false;
10158 }
10159
10160 if (activeTrackCnt() == 0) {
10161 // if no track is active and the effect tail has not been rendered,
10162 // the input buffer must be cleared here as the mixer process will not do it
10163 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010164 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010165 if (mTailBufferCount > 0) {
10166 mTailBufferCount--;
10167 }
10168 }
10169 }
Eric Laurentdac69112010-09-28 14:09:57 -070010170 }
10171
Mathias Agopian65ab4712010-07-14 17:59:35 -070010172 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010173#ifdef QCOM_HARDWARE
10174 if (doProcess || isForLPATrack()) {
10175#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010176 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010177#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010178 for (size_t i = 0; i < size; i++) {
10179 mEffects[i]->process();
10180 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010181 }
10182 for (size_t i = 0; i < size; i++) {
10183 mEffects[i]->updateState();
10184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010185}
10186
Eric Laurentcab11242010-07-15 12:50:15 -070010187// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010188status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010189{
10190 effect_descriptor_t desc = effect->desc();
10191 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10192
10193 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010194 effect->setChain(this);
10195 sp<ThreadBase> thread = mThread.promote();
10196 if (thread == 0) {
10197 return NO_INIT;
10198 }
10199 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010200
10201 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10202 // Auxiliary effects are inserted at the beginning of mEffects vector as
10203 // they are processed first and accumulated in chain input buffer
10204 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010205
Mathias Agopian65ab4712010-07-14 17:59:35 -070010206 // the input buffer for auxiliary effect contains mono samples in
10207 // 32 bit format. This is to avoid saturation in AudoMixer
10208 // accumulation stage. Saturation is done in EffectModule::process() before
10209 // calling the process in effect engine
10210 size_t numSamples = thread->frameCount();
10211 int32_t *buffer = new int32_t[numSamples];
10212 memset(buffer, 0, numSamples * sizeof(int32_t));
10213 effect->setInBuffer((int16_t *)buffer);
10214 // auxiliary effects output samples to chain input buffer for further processing
10215 // by insert effects
10216 effect->setOutBuffer(mInBuffer);
10217 } else {
10218 // Insert effects are inserted at the end of mEffects vector as they are processed
10219 // after track and auxiliary effects.
10220 // Insert effect order as a function of indicated preference:
10221 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10222 // another effect is present
10223 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10224 // last effect claiming first position
10225 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10226 // first effect claiming last position
10227 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10228 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10229 // already present
10230
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010231 size_t size = mEffects.size();
10232 size_t idx_insert = size;
10233 ssize_t idx_insert_first = -1;
10234 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010235
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010236 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010237 effect_descriptor_t d = mEffects[i]->desc();
10238 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10239 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10240 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10241 // check invalid effect chaining combinations
10242 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10243 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010244 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010245 return INVALID_OPERATION;
10246 }
10247 // remember position of first insert effect and by default
10248 // select this as insert position for new effect
10249 if (idx_insert == size) {
10250 idx_insert = i;
10251 }
10252 // remember position of last insert effect claiming
10253 // first position
10254 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10255 idx_insert_first = i;
10256 }
10257 // remember position of first insert effect claiming
10258 // last position
10259 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10260 idx_insert_last == -1) {
10261 idx_insert_last = i;
10262 }
10263 }
10264 }
10265
10266 // modify idx_insert from first position if needed
10267 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10268 if (idx_insert_last != -1) {
10269 idx_insert = idx_insert_last;
10270 } else {
10271 idx_insert = size;
10272 }
10273 } else {
10274 if (idx_insert_first != -1) {
10275 idx_insert = idx_insert_first + 1;
10276 }
10277 }
10278
10279 // always read samples from chain input buffer
10280 effect->setInBuffer(mInBuffer);
10281
10282 // if last effect in the chain, output samples to chain
10283 // output buffer, otherwise to chain input buffer
10284 if (idx_insert == size) {
10285 if (idx_insert != 0) {
10286 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10287 mEffects[idx_insert-1]->configure();
10288 }
10289 effect->setOutBuffer(mOutBuffer);
10290 } else {
10291 effect->setOutBuffer(mInBuffer);
10292 }
10293 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010294
Steve Block3856b092011-10-20 11:56:00 +010010295 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010296 }
10297 effect->configure();
10298 return NO_ERROR;
10299}
10300
Eric Laurentcab11242010-07-15 12:50:15 -070010301// removeEffect_l() must be called with PlaybackThread::mLock held
10302size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010303{
10304 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010305 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010306 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10307
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010308 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010309 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010310 // calling stop here will remove pre-processing effect from the audio HAL.
10311 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10312 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010313 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10314 mEffects[i]->state() == EffectModule::STOPPING) {
10315 mEffects[i]->stop();
10316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010317 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10318 delete[] effect->inBuffer();
10319 } else {
10320 if (i == size - 1 && i != 0) {
10321 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10322 mEffects[i - 1]->configure();
10323 }
10324 }
10325 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010326 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010327 break;
10328 }
10329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010330
10331 return mEffects.size();
10332}
10333
Eric Laurentcab11242010-07-15 12:50:15 -070010334// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010335void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010336{
10337 size_t size = mEffects.size();
10338 for (size_t i = 0; i < size; i++) {
10339 mEffects[i]->setDevice(device);
10340 }
10341}
10342
Eric Laurentcab11242010-07-15 12:50:15 -070010343// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010344void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010345{
10346 size_t size = mEffects.size();
10347 for (size_t i = 0; i < size; i++) {
10348 mEffects[i]->setMode(mode);
10349 }
10350}
10351
Eric Laurent57b2dd12012-08-31 17:44:06 -070010352// setAudioSource_l() must be called with PlaybackThread::mLock held
10353void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10354{
10355 size_t size = mEffects.size();
10356 for (size_t i = 0; i < size; i++) {
10357 mEffects[i]->setAudioSource(source);
10358 }
10359}
10360
Eric Laurentcab11242010-07-15 12:50:15 -070010361// setVolume_l() must be called with PlaybackThread::mLock held
10362bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010363{
10364 uint32_t newLeft = *left;
10365 uint32_t newRight = *right;
10366 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010367 int ctrlIdx = -1;
10368 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010369
Eric Laurentcab11242010-07-15 12:50:15 -070010370 // first update volume controller
10371 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010372 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010373 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10374 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010375 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010376 break;
10377 }
10378 }
10379
10380 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010381 if (hasControl) {
10382 *left = mNewLeftVolume;
10383 *right = mNewRightVolume;
10384 }
10385 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010386 }
10387
10388 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010389 mLeftVolume = newLeft;
10390 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010391
10392 // second get volume update from volume controller
10393 if (ctrlIdx >= 0) {
10394 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010395 mNewLeftVolume = newLeft;
10396 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010397 }
10398 // then indicate volume to all other effects in chain.
10399 // Pass altered volume to effects before volume controller
10400 // and requested volume to effects after controller
10401 uint32_t lVol = newLeft;
10402 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010403
Mathias Agopian65ab4712010-07-14 17:59:35 -070010404 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010405 if ((int)i == ctrlIdx) continue;
10406 // this also works for ctrlIdx == -1 when there is no volume controller
10407 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010408 lVol = *left;
10409 rVol = *right;
10410 }
10411 mEffects[i]->setVolume(&lVol, &rVol, false);
10412 }
10413 *left = newLeft;
10414 *right = newRight;
10415
10416 return hasControl;
10417}
10418
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010419void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010420{
10421 const size_t SIZE = 256;
10422 char buffer[SIZE];
10423 String8 result;
10424
10425 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10426 result.append(buffer);
10427
10428 bool locked = tryLock(mLock);
10429 // failed to lock - AudioFlinger is probably deadlocked
10430 if (!locked) {
10431 result.append("\tCould not lock mutex:\n");
10432 }
10433
Eric Laurentcab11242010-07-15 12:50:15 -070010434 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10435 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010436 mEffects.size(),
10437 (uint32_t)mInBuffer,
10438 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010439 mActiveTrackCnt);
10440 result.append(buffer);
10441 write(fd, result.string(), result.size());
10442
10443 for (size_t i = 0; i < mEffects.size(); ++i) {
10444 sp<EffectModule> effect = mEffects[i];
10445 if (effect != 0) {
10446 effect->dump(fd, args);
10447 }
10448 }
10449
10450 if (locked) {
10451 mLock.unlock();
10452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010453}
10454
Eric Laurent59255e42011-07-27 19:49:51 -070010455// must be called with ThreadBase::mLock held
10456void AudioFlinger::EffectChain::setEffectSuspended_l(
10457 const effect_uuid_t *type, bool suspend)
10458{
10459 sp<SuspendedEffectDesc> desc;
10460 // use effect type UUID timelow as key as there is no real risk of identical
10461 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010462 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010463 if (suspend) {
10464 if (index >= 0) {
10465 desc = mSuspendedEffects.valueAt(index);
10466 } else {
10467 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010468 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010469 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010470 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010471 }
10472 if (desc->mRefCount++ == 0) {
10473 sp<EffectModule> effect = getEffectIfEnabled(type);
10474 if (effect != 0) {
10475 desc->mEffect = effect;
10476 effect->setSuspended(true);
10477 effect->setEnabled(false);
10478 }
10479 }
10480 } else {
10481 if (index < 0) {
10482 return;
10483 }
10484 desc = mSuspendedEffects.valueAt(index);
10485 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010486 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010487 desc->mRefCount = 1;
10488 }
10489 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010490 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010491 if (desc->mEffect != 0) {
10492 sp<EffectModule> effect = desc->mEffect.promote();
10493 if (effect != 0) {
10494 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010495 effect->lock();
10496 EffectHandle *handle = effect->controlHandle_l();
10497 if (handle != NULL && !handle->destroyed_l()) {
10498 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010499 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010500 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010501 }
10502 desc->mEffect.clear();
10503 }
10504 mSuspendedEffects.removeItemsAt(index);
10505 }
10506 }
10507}
10508
10509// must be called with ThreadBase::mLock held
10510void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10511{
10512 sp<SuspendedEffectDesc> desc;
10513
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010514 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010515 if (suspend) {
10516 if (index >= 0) {
10517 desc = mSuspendedEffects.valueAt(index);
10518 } else {
10519 desc = new SuspendedEffectDesc();
10520 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010521 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010522 }
10523 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010524 Vector< sp<EffectModule> > effects;
10525 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010526 for (size_t i = 0; i < effects.size(); i++) {
10527 setEffectSuspended_l(&effects[i]->desc().type, true);
10528 }
10529 }
10530 } else {
10531 if (index < 0) {
10532 return;
10533 }
10534 desc = mSuspendedEffects.valueAt(index);
10535 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010536 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010537 desc->mRefCount = 1;
10538 }
10539 if (--desc->mRefCount == 0) {
10540 Vector<const effect_uuid_t *> types;
10541 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10542 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10543 continue;
10544 }
10545 types.add(&mSuspendedEffects.valueAt(i)->mType);
10546 }
10547 for (size_t i = 0; i < types.size(); i++) {
10548 setEffectSuspended_l(types[i], false);
10549 }
Steve Block3856b092011-10-20 11:56:00 +010010550 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010551 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10552 }
10553 }
10554}
10555
Eric Laurent6bffdb82011-09-23 08:40:41 -070010556
10557// The volume effect is used for automated tests only
10558#ifndef OPENSL_ES_H_
10559static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10560 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10561const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10562#endif //OPENSL_ES_H_
10563
Eric Laurentdb7c0792011-08-10 10:37:50 -070010564bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10565{
10566 // auxiliary effects and visualizer are never suspended on output mix
10567 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10568 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010569 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10570 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010571 return false;
10572 }
10573 return true;
10574}
10575
Glenn Kastend0539712012-01-30 12:56:03 -080010576void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010577{
Glenn Kastend0539712012-01-30 12:56:03 -080010578 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010579 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010580 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10581 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010582 }
Eric Laurent59255e42011-07-27 19:49:51 -070010583 }
Eric Laurent59255e42011-07-27 19:49:51 -070010584}
10585
10586sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10587 const effect_uuid_t *type)
10588{
Glenn Kasten090f0192012-01-30 13:00:02 -080010589 sp<EffectModule> effect = getEffectFromType_l(type);
10590 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010591}
10592
10593void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10594 bool enabled)
10595{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010596 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010597 if (enabled) {
10598 if (index < 0) {
10599 // if the effect is not suspend check if all effects are suspended
10600 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10601 if (index < 0) {
10602 return;
10603 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010604 if (!isEffectEligibleForSuspend(effect->desc())) {
10605 return;
10606 }
Eric Laurent59255e42011-07-27 19:49:51 -070010607 setEffectSuspended_l(&effect->desc().type, enabled);
10608 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010609 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010610 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010611 return;
10612 }
Eric Laurent59255e42011-07-27 19:49:51 -070010613 }
Steve Block3856b092011-10-20 11:56:00 +010010614 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010615 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010616 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10617 // if effect is requested to suspended but was not yet enabled, supend it now.
10618 if (desc->mEffect == 0) {
10619 desc->mEffect = effect;
10620 effect->setEnabled(false);
10621 effect->setSuspended(true);
10622 }
10623 } else {
10624 if (index < 0) {
10625 return;
10626 }
Steve Block3856b092011-10-20 11:56:00 +010010627 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010628 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010629 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10630 desc->mEffect.clear();
10631 effect->setSuspended(false);
10632 }
10633}
10634
Mathias Agopian65ab4712010-07-14 17:59:35 -070010635#undef LOG_TAG
10636#define LOG_TAG "AudioFlinger"
10637
10638// ----------------------------------------------------------------------------
10639
10640status_t AudioFlinger::onTransact(
10641 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10642{
10643 return BnAudioFlinger::onTransact(code, data, reply, flags);
10644}
10645
Mathias Agopian65ab4712010-07-14 17:59:35 -070010646}; // namespace android