blob: ed221ed3a65545c2f9b79ed7e6e239ba959533ad [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
Mingming Yin84f109b2012-12-27 17:43:05 -08004** Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
vivek mehta2192bc92012-12-04 11:46:08 -08005**
vivek mehta2192bc92012-12-04 11:46:08 -08006** Not a Contribution, Apache license notifications and license are retained
7** for attribution purposes only.
Mathias Agopian65ab4712010-07-14 17:59:35 -07008**
9** Licensed under the Apache License, Version 2.0 (the "License");
10** you may not use this file except in compliance with the License.
11** You may obtain a copy of the License at
12**
13** http://www.apache.org/licenses/LICENSE-2.0
14**
15** Unless required by applicable law or agreed to in writing, software
16** distributed under the License is distributed on an "AS IS" BASIS,
17** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18** See the License for the specific language governing permissions and
19** limitations under the License.
20*/
21
22
23#define LOG_TAG "AudioFlinger"
24//#define LOG_NDEBUG 0
25
26#include <math.h>
27#include <signal.h>
28#include <sys/time.h>
29#include <sys/resource.h>
30
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
37#include <utils/String16.h>
38#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070039#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Dima Zavinfce7a472011-04-19 22:30:36 -070041#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080043#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#undef ADD_BATTERY_DATA
46
47#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080048#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080049#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070050#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
52#include <private/media/AudioTrackShared.h>
53#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070054
Dima Zavin64760242011-05-11 14:15:23 -070055#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070056#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
58#include "AudioMixer.h"
59#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080060#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Mathias Agopian65ab4712010-07-14 17:59:35 -070062#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070063#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070064#include <audio_effects/effect_ns.h>
65#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Glenn Kasten3b21c502011-12-15 09:52:39 -080067#include <audio_utils/primitives.h>
68
Eric Laurentfeb0db62011-07-22 09:04:31 -070069#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080070
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080072#ifdef DEBUG_CPU_USAGE
73#include <cpustats/CentralTendencyStatistics.h>
74#include <cpustats/ThreadCpuUsage.h>
75#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070076
John Grossman4ff14ba2012-02-08 16:37:41 -080077#include <common_time/cc_helper.h>
78#include <common_time/local_clock.h>
79
Glenn Kasten58912562012-04-03 10:45:00 -070080#include "FastMixer.h"
81
82// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070083#include <media/nbaio/AudioStreamOutSink.h>
84#include <media/nbaio/MonoPipe.h>
85#include <media/nbaio/MonoPipeReader.h>
86#include <media/nbaio/Pipe.h>
87#include <media/nbaio/PipeReader.h>
88#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070089
Glenn Kasten1dc28b72012-04-24 10:01:03 -070090#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070091
Mathias Agopian65ab4712010-07-14 17:59:35 -070092// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
John Grossman1c345192012-03-27 14:00:17 -070094// Note: the following macro is used for extremely verbose logging message. In
95// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
96// 0; but one side effect of this is to turn all LOGV's as well. Some messages
97// are so verbose that we want to suppress them even when we have ALOG_ASSERT
98// turned on. Do not uncomment the #def below unless you really know what you
99// are doing and want to see all of the extremely verbose messages.
100//#define VERY_VERY_VERBOSE_LOGGING
101#ifdef VERY_VERY_VERBOSE_LOGGING
102#define ALOGVV ALOGV
103#else
104#define ALOGVV(a...) do { } while(0)
105#endif
Eric Laurentde070132010-07-13 04:45:46 -0700106
vivek mehta2192bc92012-12-04 11:46:08 -0800107#ifdef QCOM_HARDWARE
108#define DIRECT_TRACK_EOS 1
Ravishankar Sarawadi20017912013-02-27 18:47:54 +0100109#define DIRECT_TRACK_HW_FAIL 6
vivek mehta2192bc92012-12-04 11:46:08 -0800110static const char lockName[] = "DirectTrack";
111#endif
112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113namespace android {
114
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800115static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
116static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800119static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121// retry counts for buffer fill timeout
122// 50 * ~20msecs = 1 second
123static const int8_t kMaxTrackRetries = 50;
124static const int8_t kMaxTrackStartupRetries = 50;
125// allow less retry attempts on direct output thread.
126// direct outputs can be a scarce resource in audio hardware and should
127// be released as quickly as possible.
128static const int8_t kMaxTrackRetriesDirect = 2;
129
130static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800131static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700132
Glenn Kasten7dede872011-12-13 11:04:14 -0800133// don't warn about blocked writes or record buffer overflows more often than this
134static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700136// RecordThread loop sleep time upon application overrun or audio HAL read error
137static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138
Glenn Kasten7dede872011-12-13 11:04:14 -0800139// maximum time to wait for setParameters to complete
140static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700141
Eric Laurent7cafbb32011-11-22 18:50:29 -0800142// minimum sleep time for the mixer thread loop when tracks are active but in underrun
143static const uint32_t kMinThreadSleepTimeUs = 5000;
144// maximum divider applied to the active sleep time in the mixer thread loop
145static const uint32_t kMaxThreadSleepTimeShift = 2;
146
Glenn Kasten58912562012-04-03 10:45:00 -0700147// minimum normal mix buffer size, expressed in milliseconds rather than frames
148static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700149// maximum normal mix buffer size
150static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700151
John Grossman4ff14ba2012-02-08 16:37:41 -0800152nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800153
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700160 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700162 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700171static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
172 // AudioFlinger::setParameters() updates, other threads read w/o lock
173
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700174// Priorities for requestPriority
175static const int kPriorityAudioApp = 2;
176static const int kPriorityFastMixer = 3;
177
Glenn Kasten3ed29202012-08-07 15:24:44 -0700178// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
179// for the track. The client then sub-divides this into smaller buffers for its use.
180// Currently the client uses double-buffering by default, but doesn't tell us about that.
181// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700182// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
183// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700184// See the client's minBufCount and mNotificationFramesAct calculations for details.
185static const int kFastTrackMultiplier = 2;
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700189#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800190// To collect the amplifier usage
191static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800192 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
193 if (service == NULL) {
194 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800195 return;
196 }
197
198 service->addBatteryData(params);
199}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700200#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800201
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700203{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700204 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 int rc;
206
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700207 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
208 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
209 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
210 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700212 }
213 rc = audio_hw_device_open(mod, dev);
214 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
215 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
216 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700218 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000219#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700220 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
221 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
222 rc = BAD_VALUE;
223 goto out;
224 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100225#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 return 0;
227
228out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 *dev = NULL;
230 return rc;
231}
232
vivek mehta2192bc92012-12-04 11:46:08 -0800233static uint32_t getInputChannelCount(uint32_t channels) {
234#ifdef QCOM_HARDWARE
235 // only mono or stereo and 5.1 are supported for input sources
236 return popcount((channels) & (AUDIO_CHANNEL_IN_STEREO | AUDIO_CHANNEL_IN_MONO | AUDIO_CHANNEL_IN_5POINT1));
237#else
238 return popcount(channels);
239#endif
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241// ----------------------------------------------------------------------------
242
243AudioFlinger::AudioFlinger()
244 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800245 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700246 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800248 mMasterMute(false),
249 mNextUniqueId(1),
250 mMode(AUDIO_MODE_INVALID),
251 mBtNrecIsOff(false)
Haynes Mathew George30fd2a32013-02-21 20:06:04 -0800252#ifdef QCOM_HARDWARE
253 ,mAllChainsLocked(false)
254#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700256}
257
258void AudioFlinger::onFirstRef()
259{
Dima Zavin799a70e2011-04-18 16:57:27 -0700260 int rc = 0;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800261#ifdef QCOM_HARDWARE
262 mA2DPHandle = -1;
263#endif
Dima Zavinfce7a472011-04-19 22:30:36 -0700264
Eric Laurent93575202011-01-18 18:39:02 -0800265 Mutex::Autolock _l(mLock);
266
Dima Zavin799a70e2011-04-18 16:57:27 -0700267 /* TODO: move all this work into an Init() function */
vivek mehta2192bc92012-12-04 11:46:08 -0800268#ifdef QCOM_HARDWARE
269 mLPASessionId = -2; // -2 is invalid session ID
270 mIsEffectConfigChanged = false;
271 mLPAEffectChain = NULL;
272#endif
John Grossman4ff14ba2012-02-08 16:37:41 -0800273 char val_str[PROPERTY_VALUE_MAX] = { 0 };
274 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
275 uint32_t int_val;
276 if (1 == sscanf(val_str, "%u", &int_val)) {
277 mStandbyTimeInNsecs = milliseconds(int_val);
278 ALOGI("Using %u mSec as standby time.", int_val);
279 } else {
280 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
281 ALOGI("Using default %u mSec as standby time.",
282 (uint32_t)(mStandbyTimeInNsecs / 1000000));
283 }
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285
Eric Laurenta4c5a552012-03-29 10:12:40 -0700286 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
289AudioFlinger::~AudioFlinger()
290{
291 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700292 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700293 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294 }
295 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700296 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700297 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700299
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800300 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
301 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
303 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304 }
305}
306
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307static const char * const audio_interfaces[] = {
308 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
309 AUDIO_HARDWARE_MODULE_ID_A2DP,
310 AUDIO_HARDWARE_MODULE_ID_USB,
311};
312#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
313
John Grossmanee578c02012-07-23 17:05:46 -0700314AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
315 audio_module_handle_t module,
316 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700317{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700318 // if module is 0, the request comes from an old policy manager and we should load
319 // well known modules
320 if (module == 0) {
321 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
322 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
323 loadHwModule_l(audio_interfaces[i]);
324 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700325 // then try to find a module supporting the requested device.
326 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
327 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
328 audio_hw_device_t *dev = audioHwDevice->hwDevice();
329 if ((dev->get_supported_devices != NULL) &&
330 (dev->get_supported_devices(dev) & devices) == devices)
331 return audioHwDevice;
Dorian Snyderf32d5702013-03-01 14:25:46 -0800332#ifdef ICS_AUDIO_BLOB
333 else if (dev->get_supported_devices == NULL && i != 0 &&
334 devices == 0x80)
335 // Reasonably safe assumption: A non-primary HAL without
336 // get_supported_devices is a locally-built A2DP binary
337 return audioHwDevice;
338#endif
Eric Laurentf1c04f92012-08-28 14:26:53 -0700339 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700340 } else {
341 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700342 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
343 if (audioHwDevice != NULL) {
344 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700345 }
346 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700347
Dima Zavin799a70e2011-04-18 16:57:27 -0700348 return NULL;
349}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700351void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352{
353 const size_t SIZE = 256;
354 char buffer[SIZE];
355 String8 result;
356
357 result.append("Clients:\n");
358 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800359 sp<Client> client = mClients.valueAt(i).promote();
360 if (client != 0) {
361 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
362 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 }
364 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700365
366 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800367 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700368 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
369 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800370 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700371 result.append(buffer);
372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374}
375
376
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700377void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378{
379 const size_t SIZE = 256;
380 char buffer[SIZE];
381 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800382 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383
John Grossman4ff14ba2012-02-08 16:37:41 -0800384 snprintf(buffer, SIZE, "Hardware status: %d\n"
385 "Standby Time mSec: %u\n",
386 hardwareStatus,
387 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 result.append(buffer);
389 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390}
391
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700392void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393{
394 const size_t SIZE = 256;
395 char buffer[SIZE];
396 String8 result;
397 snprintf(buffer, SIZE, "Permission Denial: "
398 "can't dump AudioFlinger from pid=%d, uid=%d\n",
399 IPCThreadState::self()->getCallingPid(),
400 IPCThreadState::self()->getCallingUid());
401 result.append(buffer);
402 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403}
404
405static bool tryLock(Mutex& mutex)
406{
407 bool locked = false;
408 for (int i = 0; i < kDumpLockRetries; ++i) {
409 if (mutex.tryLock() == NO_ERROR) {
410 locked = true;
411 break;
412 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800413 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700414 }
415 return locked;
416}
417
418status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
419{
Glenn Kasten44deb052012-02-05 18:09:08 -0800420 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 dumpPermissionDenial(fd, args);
422 } else {
423 // get state of hardware lock
424 bool hardwareLocked = tryLock(mHardwareLock);
425 if (!hardwareLocked) {
426 String8 result(kHardwareLockedString);
427 write(fd, result.string(), result.size());
428 } else {
429 mHardwareLock.unlock();
430 }
431
432 bool locked = tryLock(mLock);
433
434 // failed to lock - AudioFlinger is probably deadlocked
435 if (!locked) {
436 String8 result(kDeadlockedString);
437 write(fd, result.string(), result.size());
438 }
439
440 dumpClients(fd, args);
441 dumpInternals(fd, args);
442
443 // dump playback threads
444 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
445 mPlaybackThreads.valueAt(i)->dump(fd, args);
446 }
447
448 // dump record threads
449 for (size_t i = 0; i < mRecordThreads.size(); i++) {
450 mRecordThreads.valueAt(i)->dump(fd, args);
451 }
452
Dima Zavin799a70e2011-04-18 16:57:27 -0700453 // dump all hardware devs
454 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700455 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700456 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 }
458 if (locked) mLock.unlock();
459 }
460 return NO_ERROR;
461}
462
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800463sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
464{
465 // If pid is already in the mClients wp<> map, then use that entry
466 // (for which promote() is always != 0), otherwise create a new entry and Client.
467 sp<Client> client = mClients.valueFor(pid).promote();
468 if (client == 0) {
469 client = new Client(this, pid);
470 mClients.add(pid, client);
471 }
472
473 return client;
474}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475
476// IAudioFlinger interface
477
478
479sp<IAudioTrack> AudioFlinger::createTrack(
480 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800481 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800483 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700484 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800486 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800488 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800489 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 int *sessionId,
491 status_t *status)
492{
493 sp<PlaybackThread::Track> track;
494 sp<TrackHandle> trackHandle;
495 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 status_t lStatus;
497 int lSessionId;
498
Glenn Kasten263709e2012-01-06 08:40:01 -0800499 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
500 // but if someone uses binder directly they could bypass that and cause us to crash
501 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000502 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503 lStatus = BAD_VALUE;
504 goto Exit;
505 }
506
507 {
508 Mutex::Autolock _l(mLock);
509 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700510 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000512 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 lStatus = BAD_VALUE;
514 goto Exit;
515 }
516
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800517 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518
Steve Block3856b092011-10-20 11:56:00 +0100519 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700520 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700521 // check if an effect chain with the same session ID is present on another
522 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700523 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700524 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
525 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700526 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700527 if (sessions & PlaybackThread::EFFECT_SESSION) {
528 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700529 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700530 }
Eric Laurentde070132010-07-13 04:45:46 -0700531 }
532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 lSessionId = *sessionId;
534 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700535 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700536 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537 if (sessionId != NULL) {
538 *sessionId = lSessionId;
539 }
540 }
Steve Block3856b092011-10-20 11:56:00 +0100541 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542
543 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800544 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700545
546 // move effect chain to this output thread if an effect on same session was waiting
547 // for a track to be created
548 if (lStatus == NO_ERROR && effectThread != NULL) {
549 Mutex::Autolock _dl(thread->mLock);
550 Mutex::Autolock _sl(effectThread->mLock);
551 moveEffectChain_l(lSessionId, effectThread, thread, true);
552 }
Eric Laurenta011e352012-03-29 15:51:43 -0700553
554 // Look for sync events awaiting for a session to be used.
555 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
556 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
557 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700558 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700559 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700560 } else {
561 mPendingSyncEvents[i]->cancel();
562 }
Eric Laurenta011e352012-03-29 15:51:43 -0700563 mPendingSyncEvents.removeAt(i);
564 i--;
565 }
566 }
567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 }
569 if (lStatus == NO_ERROR) {
570 trackHandle = new TrackHandle(track);
571 } else {
572 // remove local strong reference to Client before deleting the Track so that the Client
573 // destructor is called by the TrackBase destructor with mLock held
574 client.clear();
575 track.clear();
576 }
577
578Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700579 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 *status = lStatus;
581 }
582 return trackHandle;
583}
584
vivek mehta2192bc92012-12-04 11:46:08 -0800585#ifdef QCOM_HARDWARE
586sp<IDirectTrack> AudioFlinger::createDirectTrack(
587 pid_t pid,
588 uint32_t sampleRate,
589 audio_channel_mask_t channelMask,
590 audio_io_handle_t output,
591 int *sessionId,
592 IDirectTrackClient *client,
593 audio_stream_type_t streamType,
594 status_t *status)
595{
596 *status = NO_ERROR;
597 status_t lStatus = NO_ERROR;
598 sp<IDirectTrack> track = NULL;
599 DirectAudioTrack* directTrack = NULL;
600 Mutex::Autolock _l(mLock);
601
602 ALOGV("createDirectTrack() sessionId: %d sampleRate %d channelMask %d",
603 *sessionId, sampleRate, channelMask);
604 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
605 if(desc == NULL) {
606 ALOGE("Error: Invalid output (%d) to create direct audio track", output);
607 lStatus = BAD_VALUE;
608 goto Exit;
609 }
610 desc->mStreamType = streamType;
611 if (desc->flag & AUDIO_OUTPUT_FLAG_LPA) {
612 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
613 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
614 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
615 // Check if the session ID is already associated with a track
616 uint32_t sessions = t->hasAudioSession(*sessionId);
617
618 // check if an effect with same session ID is waiting for a ssession to be created
619 ALOGV("check if an effect with same session ID is waiting for a ssession to be created");
620 if ((mLPAEffectChain == NULL) && (sessions & PlaybackThread::EFFECT_SESSION)) {
621 // Clear reference to previous effect chain if any
622 t->mLock.lock();
623 ALOGV("getting the LPA effect chain and setting LPA flag to true.");
624 mLPAEffectChain = t->getEffectChain_l(*sessionId);
625 t->mLock.unlock();
626 }
627 }
628 mLPASessionId = *sessionId;
629 if (mLPAEffectChain != NULL) {
630 mLPAEffectChain->setLPAFlag(true);
631 // For LPA, the volume will be applied in DSP. No need for volume
632 // control in the Effect chain, so setting it to unity.
633 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
634 mLPAEffectChain->setVolume_l(&volume,&volume);
635 } else {
636 ALOGW("There was no effectChain created for the sessionId(%d)", mLPASessionId);
637 }
638 mLPASampleRate = sampleRate;
639 mLPANumChannels = popcount(channelMask);
640 } else {
641 if(sessionId != NULL) {
642 ALOGE("Error: Invalid sessionID (%d) for direct audio track", *sessionId);
643 }
644 }
645 }
646 mLock.unlock();
647 directTrack = new DirectAudioTrack(this, output, desc, client, desc->flag);
648 desc->trackRefPtr = dynamic_cast<void *>(directTrack);
649 mLock.lock();
650 if (directTrack != 0) {
651 track = dynamic_cast<IDirectTrack *>(directTrack);
652 AudioEventObserver* obv = dynamic_cast<AudioEventObserver *>(directTrack);
653 ALOGE("setting observer mOutputDesc track %p, obv %p", track.get(), obv);
654 desc->stream->set_observer(desc->stream, reinterpret_cast<void *>(obv));
655 } else {
656 lStatus = BAD_VALUE;
657 }
658Exit:
659 if(lStatus) {
660 if (track != NULL) {
661 track.clear();
662 }
663 *status = lStatus;
664 }
665 return track;
666}
667
668void AudioFlinger::deleteEffectSession()
669{
670 Mutex::Autolock _l(mLock);
671 ALOGV("deleteSession");
672 // -2 is invalid session ID
673 mLPASessionId = -2;
674 if (mLPAEffectChain != NULL) {
675 mLPAEffectChain->setLPAFlag(false);
676 size_t i, numEffects = mLPAEffectChain->getNumEffects();
677 for(i = 0; i < numEffects; i++) {
678 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
679 effect->setInBuffer(mLPAEffectChain->inBuffer());
680 if (i == numEffects-1) {
681 effect->setOutBuffer(mLPAEffectChain->outBuffer());
682 } else {
683 effect->setOutBuffer(mLPAEffectChain->inBuffer());
684 }
685 effect->configure();
686 }
687 mLPAEffectChain.clear();
688 mLPAEffectChain = NULL;
689 }
690}
691
692// ToDo: Should we go ahead with this frameCount?
693#define DEAFULT_FRAME_COUNT 1200
694void AudioFlinger::applyEffectsOn(void *token, int16_t *inBuffer, int16_t *outBuffer, int size)
695{
696 ALOGV("applyEffectsOn: inBuf %p outBuf %p size %d token %p", inBuffer, outBuffer, size, token);
697 // This might be the first buffer to apply effects after effect config change
698 // should not skip effects processing
699 mIsEffectConfigChanged = false;
700
701 volatile size_t numEffects = 0;
702 if(mLPAEffectChain != NULL) {
703 numEffects = mLPAEffectChain->getNumEffects();
704 }
705
706 if( numEffects > 0) {
707 size_t i = 0;
708 int16_t *pIn = inBuffer;
709 int16_t *pOut = outBuffer;
710
711 int frameCount = size / (sizeof(int16_t) * mLPANumChannels);
712
713 while(frameCount > 0) {
714 if(mLPAEffectChain == NULL) {
715 ALOGV("LPA Effect Chain is removed - No effects processing !!");
716 numEffects = 0;
717 break;
718 }
719 mLPAEffectChain->lock();
720
721 numEffects = mLPAEffectChain->getNumEffects();
722 if(!numEffects) {
723 ALOGV("applyEffectsOn: All the effects are removed - nothing to process");
724 mLPAEffectChain->unlock();
725 break;
726 }
727
728 int outFrameCount = (frameCount > DEAFULT_FRAME_COUNT ? DEAFULT_FRAME_COUNT: frameCount);
729 bool isEffectEnabled = false;
730 for(i = 0; i < numEffects; i++) {
731 // If effect configuration is changed while applying effects do not process further
732 if(mIsEffectConfigChanged) {
733 mLPAEffectChain->unlock();
734 ALOGV("applyEffectsOn: mIsEffectConfigChanged is set - no further processing");
735 return;
736 }
737 sp<EffectModule> effect = mLPAEffectChain->getEffectFromIndex_l(i);
738 if(effect == NULL) {
739 ALOGE("getEffectFromIndex_l(%d) returned NULL ptr", i);
740 mLPAEffectChain->unlock();
741 return;
742 }
743 if(i == 0) {
744 // For the first set input and output buffers different
745 isEffectEnabled = effect->isProcessEnabled();
746 effect->setInBuffer(pIn);
747 effect->setOutBuffer(pOut);
748 } else {
749 // For the remaining use previous effect's output buffer as input buffer
750 effect->setInBuffer(pOut);
751 effect->setOutBuffer(pOut);
752 }
753 // true indicates that it is being applied on LPA output
754 effect->configure(true, mLPASampleRate, mLPANumChannels, outFrameCount);
755 }
756
757 if(isEffectEnabled) {
758 // Clear the output buffer
759 memset(pOut, 0, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
760 } else {
761 // Copy input buffer content to the output buffer
762 memcpy(pOut, pIn, (outFrameCount * mLPANumChannels * sizeof(int16_t)));
763 }
764
765 mLPAEffectChain->process_l();
766
767 mLPAEffectChain->unlock();
768
769 // Update input and output buffer pointers
770 pIn += (outFrameCount * mLPANumChannels);
771 pOut += (outFrameCount * mLPANumChannels);
772 frameCount -= outFrameCount;
773 }
774 }
775
776 if (!numEffects) {
777 ALOGV("applyEffectsOn: There are no effects to be applied");
778 if(inBuffer != outBuffer) {
779 // No effect applied so just copy input buffer to output buffer
780 memcpy(outBuffer, inBuffer, size);
781 }
782 }
783}
784#endif
785
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800786uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787{
788 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800789#ifdef QCOM_HARDWARE
790 if (!mDirectAudioTracks.isEmpty()) {
791 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
792 if(desc != NULL) {
793 return desc->stream->common.get_sample_rate(&desc->stream->common);
794 }
795 }
796#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 PlaybackThread *thread = checkPlaybackThread_l(output);
798 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000799 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 return 0;
801 }
802 return thread->sampleRate();
803}
804
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800805int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806{
807 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800808#ifdef QCOM_HARDWARE
809 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
810 if(desc != NULL) {
811 return desc->stream->common.get_channels(&desc->stream->common);
812 }
813#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 PlaybackThread *thread = checkPlaybackThread_l(output);
815 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000816 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return 0;
818 }
819 return thread->channelCount();
820}
821
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800822audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823{
824 Mutex::Autolock _l(mLock);
825 PlaybackThread *thread = checkPlaybackThread_l(output);
826 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000827 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800828 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 }
830 return thread->format();
831}
832
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800833size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
835 Mutex::Autolock _l(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -0800836#ifdef QCOM_HARDWARE
837 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
838 if(desc != NULL) {
839 return desc->stream->common.get_buffer_size(&desc->stream->common);
840 }
841#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 PlaybackThread *thread = checkPlaybackThread_l(output);
843 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000844 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
Glenn Kasten58912562012-04-03 10:45:00 -0700847 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
848 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return thread->frameCount();
850}
851
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800852uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853{
854 Mutex::Autolock _l(mLock);
855 PlaybackThread *thread = checkPlaybackThread_l(output);
856 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000857 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 return 0;
859 }
860 return thread->latency();
861}
862
863status_t AudioFlinger::setMasterVolume(float value)
864{
Eric Laurenta1884f92011-08-23 08:25:03 -0700865 status_t ret = initCheck();
866 if (ret != NO_ERROR) {
867 return ret;
868 }
869
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 // check calling permissions
871 if (!settingsAllowed()) {
872 return PERMISSION_DENIED;
873 }
874
Dorian Snyderf32d5702013-03-01 14:25:46 -0800875#ifdef QCOM_HARDWARE
876 mA2DPHandle = -1;
877#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -0700878 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700879 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700880
John Grossmanee578c02012-07-23 17:05:46 -0700881 // Set master volume in the HALs which support it.
882 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
883 AutoMutex lock(mHardwareLock);
884 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800885
John Grossmanee578c02012-07-23 17:05:46 -0700886 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
887 if (dev->canSetMasterVolume()) {
888 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800889 }
John Grossmanee578c02012-07-23 17:05:46 -0700890 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892
John Grossmanee578c02012-07-23 17:05:46 -0700893 // Now set the master volume in each playback thread. Playback threads
894 // assigned to HALs which do not have master volume support will apply
895 // master volume during the mix operation. Threads with HALs which do
896 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800897 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700898 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899
900 return NO_ERROR;
901}
902
Glenn Kastenf78aee72012-01-04 11:00:47 -0800903status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904{
Eric Laurenta1884f92011-08-23 08:25:03 -0700905 status_t ret = initCheck();
906 if (ret != NO_ERROR) {
907 return ret;
908 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909
910 // check calling permissions
911 if (!settingsAllowed()) {
912 return PERMISSION_DENIED;
913 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800914 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000915 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 return BAD_VALUE;
917 }
918
919 { // scope for the lock
920 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700921 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700923 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 mHardwareStatus = AUDIO_HW_IDLE;
925 }
926
927 if (NO_ERROR == ret) {
928 Mutex::Autolock _l(mLock);
929 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800930 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700931 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 }
933
934 return ret;
935}
936
937status_t AudioFlinger::setMicMute(bool state)
938{
Eric Laurenta1884f92011-08-23 08:25:03 -0700939 status_t ret = initCheck();
940 if (ret != NO_ERROR) {
941 return ret;
942 }
943
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 // check calling permissions
945 if (!settingsAllowed()) {
946 return PERMISSION_DENIED;
947 }
948
949 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700950 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700952 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 mHardwareStatus = AUDIO_HW_IDLE;
954 return ret;
955}
956
957bool AudioFlinger::getMicMute() const
958{
Eric Laurenta1884f92011-08-23 08:25:03 -0700959 status_t ret = initCheck();
960 if (ret != NO_ERROR) {
961 return false;
962 }
963
Dima Zavinfce7a472011-04-19 22:30:36 -0700964 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800965 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700966 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700968 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969 mHardwareStatus = AUDIO_HW_IDLE;
970 return state;
971}
972
973status_t AudioFlinger::setMasterMute(bool muted)
974{
John Grossmand8f178d2012-07-20 14:51:35 -0700975 status_t ret = initCheck();
976 if (ret != NO_ERROR) {
977 return ret;
978 }
979
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 // check calling permissions
981 if (!settingsAllowed()) {
982 return PERMISSION_DENIED;
983 }
984
John Grossmanee578c02012-07-23 17:05:46 -0700985 Mutex::Autolock _l(mLock);
986 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700987
John Grossmanee578c02012-07-23 17:05:46 -0700988 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100989#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700990 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
991 AutoMutex lock(mHardwareLock);
992 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700993
John Grossmanee578c02012-07-23 17:05:46 -0700994 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
995 if (dev->canSetMasterMute()) {
996 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700997 }
John Grossmanee578c02012-07-23 17:05:46 -0700998 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700999 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001000#endif
John Grossmand8f178d2012-07-20 14:51:35 -07001001
John Grossmanee578c02012-07-23 17:05:46 -07001002 // Now set the master mute in each playback thread. Playback threads
1003 // assigned to HALs which do not have master mute support will apply master
1004 // mute during the mix operation. Threads with HALs which do support master
1005 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001006 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -07001007 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008
1009 return NO_ERROR;
1010}
1011
1012float AudioFlinger::masterVolume() const
1013{
Glenn Kasten98067102011-12-13 11:47:54 -08001014 Mutex::Autolock _l(mLock);
1015 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016}
1017
1018bool AudioFlinger::masterMute() const
1019{
Glenn Kasten98067102011-12-13 11:47:54 -08001020 Mutex::Autolock _l(mLock);
1021 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022}
1023
John Grossman4ff14ba2012-02-08 16:37:41 -08001024float AudioFlinger::masterVolume_l() const
1025{
John Grossman4ff14ba2012-02-08 16:37:41 -08001026 return mMasterVolume;
1027}
1028
John Grossmand8f178d2012-07-20 14:51:35 -07001029bool AudioFlinger::masterMute_l() const
1030{
John Grossmanee578c02012-07-23 17:05:46 -07001031 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001032}
1033
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001034status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1035 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036{
1037 // check calling permissions
1038 if (!settingsAllowed()) {
1039 return PERMISSION_DENIED;
1040 }
1041
Glenn Kasten263709e2012-01-06 08:40:01 -08001042 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001043 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 return BAD_VALUE;
1045 }
1046
1047 AutoMutex lock(mLock);
vivek mehta2192bc92012-12-04 11:46:08 -08001048#ifdef QCOM_HARDWARE
1049 ALOGV("setStreamVolume stream %d, output %d, value %f",stream, output, value);
1050 AudioSessionDescriptor *desc = NULL;
1051 if (!mDirectAudioTracks.isEmpty()) {
1052 desc = mDirectAudioTracks.valueFor(output);
1053 if (desc != NULL) {
1054 ALOGV("setStreamVolume for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1055 if (desc->mStreamType == stream) {
1056 mStreamTypes[stream].volume = value;
Dorian Snyderf32d5702013-03-01 14:25:46 -08001057 desc->mVolumeScale = value;
vivek mehta2192bc92012-12-04 11:46:08 -08001058 desc->stream->set_volume(desc->stream,
1059 desc->mVolumeLeft * mStreamTypes[stream].volume,
1060 desc->mVolumeRight* mStreamTypes[stream].volume);
1061 return NO_ERROR;
1062 }
1063 }
1064 }
1065#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 PlaybackThread *thread = NULL;
1067 if (output) {
1068 thread = checkPlaybackThread_l(output);
1069 if (thread == NULL) {
vivek mehta2192bc92012-12-04 11:46:08 -08001070#ifdef QCOM_HARDWARE
1071 if (desc != NULL) {
1072 return NO_ERROR;
1073 }
1074#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 return BAD_VALUE;
1076 }
vivek mehta2192bc92012-12-04 11:46:08 -08001077
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 }
1079
1080 mStreamTypes[stream].volume = value;
1081
1082 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001084 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 }
1086 } else {
1087 thread->setStreamVolume(stream, value);
1088 }
1089
1090 return NO_ERROR;
1091}
1092
Glenn Kastenfff6d712012-01-12 16:38:12 -08001093status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
1095 // check calling permissions
1096 if (!settingsAllowed()) {
1097 return PERMISSION_DENIED;
1098 }
1099
Glenn Kasten263709e2012-01-06 08:40:01 -08001100 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -07001101 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001102 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 return BAD_VALUE;
1104 }
1105
Eric Laurent93575202011-01-18 18:39:02 -08001106 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 mStreamTypes[stream].mute = muted;
1108 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001109 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110
1111 return NO_ERROR;
1112}
1113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001114float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115{
Glenn Kasten263709e2012-01-06 08:40:01 -08001116 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 return 0.0f;
1118 }
1119
1120 AutoMutex lock(mLock);
1121 float volume;
1122 if (output) {
1123 PlaybackThread *thread = checkPlaybackThread_l(output);
1124 if (thread == NULL) {
1125 return 0.0f;
1126 }
1127 volume = thread->streamVolume(stream);
1128 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001129 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 }
1131
1132 return volume;
1133}
1134
Glenn Kastenfff6d712012-01-12 16:38:12 -08001135bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136{
Glenn Kasten263709e2012-01-06 08:40:01 -08001137 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138 return true;
1139 }
1140
Glenn Kasten6637baa2012-01-09 09:40:36 -08001141 AutoMutex lock(mLock);
1142 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143}
1144
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001145status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001147 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
1149 // check calling permissions
1150 if (!settingsAllowed()) {
1151 return PERMISSION_DENIED;
1152 }
1153
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 // ioHandle == 0 means the parameters are global to the audio hardware interface
1155 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001156 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001157 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001158 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001159 AutoMutex lock(mHardwareLock);
1160 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1161 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1162 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1163 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1164 final_result = result ?: final_result;
1165 }
1166 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001167 }
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001168#ifdef QCOM_HARDWARE
1169 AudioParameter param = AudioParameter(keyValuePairs);
1170 String8 value, key;
1171 int i = 0;
1172
1173 key = String8(AudioParameter::keyADSPStatus);
1174 if (param.get(key, value) == NO_ERROR) {
1175 ALOGV("Set keyADSPStatus:%s", value.string());
1176 if (value == "ONLINE" || value == "OFFLINE") {
1177 if (!mDirectAudioTracks.isEmpty()) {
1178 for (i=0; i < mDirectAudioTracks.size(); i++) {
1179 mDirectAudioTracks.valueAt(i)->stream->common.set_parameters(
1180 &mDirectAudioTracks.valueAt(i)->stream->common, keyValuePairs.string());
1181 }
1182 }
1183 }
1184 }
1185#else
Eric Laurent59bd0da2011-08-01 09:52:20 -07001186 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1187 AudioParameter param = AudioParameter(keyValuePairs);
1188 String8 value;
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01001189#endif
1190
Eric Laurent59bd0da2011-08-01 09:52:20 -07001191 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001192 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1193 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001194 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1195 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001196 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001197 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1198 // collect all of the thread's session IDs
1199 KeyedVector<int, bool> ids = thread->sessionIds();
1200 // suspend effects associated with those session IDs
1201 for (size_t j = 0; j < ids.size(); ++j) {
1202 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001203 thread->setEffectSuspended(FX_IID_AEC,
1204 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001205 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001206 thread->setEffectSuspended(FX_IID_NS,
1207 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001208 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001209 }
1210 }
Eric Laurentbee53372011-08-29 12:42:48 -07001211 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001212 }
1213 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001214 String8 screenState;
1215 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1216 bool isOff = screenState == "off";
1217 if (isOff != (gScreenState & 1)) {
1218 gScreenState = ((gScreenState & ~1) + 2) | isOff;
1219 }
1220 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001221 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 }
1223
vivek mehta2192bc92012-12-04 11:46:08 -08001224#ifdef QCOM_HARDWARE
1225 AudioSessionDescriptor *desc = NULL;
1226 if (!mDirectAudioTracks.isEmpty()) {
1227 desc = mDirectAudioTracks.valueFor(ioHandle);
1228 if (desc != NULL) {
1229 ALOGV("setParameters for mAudioTracks size %d desc %p",mDirectAudioTracks.size(),desc);
1230 desc->stream->common.set_parameters(&desc->stream->common, keyValuePairs.string());
Mingming Yin9b3dd172013-01-10 18:42:38 -08001231 AudioParameter param = AudioParameter(keyValuePairs);
1232 String8 key = String8(AudioParameter::keyRouting);
1233 int device;
1234 if (param.getInt(key, device) == NO_ERROR) {
1235 if(mLPAEffectChain != NULL){
1236 mLPAEffectChain->setDevice_l(device);
1237 audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1238 }
1239 }
vivek mehta2192bc92012-12-04 11:46:08 -08001240 }
1241 }
1242#endif
1243
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1245 // and the thread is exited once the lock is released
1246 sp<ThreadBase> thread;
1247 {
1248 Mutex::Autolock _l(mLock);
1249 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001250 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001252 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001253 // indicate output device change to all input threads for pre processing
1254 AudioParameter param = AudioParameter(keyValuePairs);
1255 int value;
vivek mehta2192bc92012-12-04 11:46:08 -08001256 DefaultKeyedVector< int, sp<RecordThread> > recordThreads = mRecordThreads;
1257 mLock.unlock();
Eric Laurent89d94e72012-03-16 20:37:59 -07001258 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1259 (value != 0)) {
vivek mehta2192bc92012-12-04 11:46:08 -08001260 for (size_t i = 0; i < recordThreads.size(); i++) {
1261 recordThreads.valueAt(i)->setParameters(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001262 }
1263 }
vivek mehta2192bc92012-12-04 11:46:08 -08001264 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 }
vivek mehta2192bc92012-12-04 11:46:08 -08001266 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001268 if (thread != 0) {
1269 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 }
1271 return BAD_VALUE;
1272}
1273
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001274String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275{
Glenn Kasten23d82a92012-02-03 11:10:00 -08001276// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
1278
Eric Laurenta4c5a552012-03-29 10:12:40 -07001279 Mutex::Autolock _l(mLock);
1280
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001282 String8 out_s8;
1283
Dima Zavin799a70e2011-04-18 16:57:27 -07001284 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001285 char *s;
1286 {
1287 AutoMutex lock(mHardwareLock);
1288 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001289 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001290 s = dev->get_parameters(dev, keys.string());
1291 mHardwareStatus = AUDIO_HW_IDLE;
1292 }
John Grossmanef7740b2012-02-09 11:28:36 -08001293 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001294 free(s);
1295 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001296 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 }
1298
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1300 if (playbackThread != NULL) {
1301 return playbackThread->getParameters(keys);
1302 }
1303 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1304 if (recordThread != NULL) {
1305 return recordThread->getParameters(keys);
1306 }
1307 return String8("");
1308}
1309
Glenn Kastendd8104c2012-07-02 12:42:44 -07001310size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1311 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312{
Eric Laurenta1884f92011-08-23 08:25:03 -07001313 status_t ret = initCheck();
1314 if (ret != NO_ERROR) {
1315 return 0;
1316 }
1317
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001318 AutoMutex lock(mHardwareLock);
1319 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001320 struct audio_config config = {
1321 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001322 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001323 format: format,
1324 };
John Grossmanee578c02012-07-23 17:05:46 -07001325 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001326#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07001327 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001328#else
1329 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1330#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001331 mHardwareStatus = AUDIO_HW_IDLE;
1332 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333}
1334
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001335unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337 Mutex::Autolock _l(mLock);
1338
1339 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1340 if (recordThread != NULL) {
1341 return recordThread->getInputFramesLost();
1342 }
1343 return 0;
1344}
1345
1346status_t AudioFlinger::setVoiceVolume(float value)
1347{
Eric Laurenta1884f92011-08-23 08:25:03 -07001348 status_t ret = initCheck();
1349 if (ret != NO_ERROR) {
1350 return ret;
1351 }
1352
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353 // check calling permissions
1354 if (!settingsAllowed()) {
1355 return PERMISSION_DENIED;
1356 }
1357
1358 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001359 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001360 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001361 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001362 mHardwareStatus = AUDIO_HW_IDLE;
1363
1364 return ret;
1365}
1366
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001367status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1368 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369{
1370 status_t status;
1371
1372 Mutex::Autolock _l(mLock);
1373
1374 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1375 if (playbackThread != NULL) {
1376 return playbackThread->getRenderPosition(halFrames, dspFrames);
1377 }
1378
1379 return BAD_VALUE;
1380}
1381
Mingming Yin84f109b2012-12-27 17:43:05 -08001382#ifdef QCOM_FM_ENABLED
1383status_t AudioFlinger::setFmVolume(float value)
1384{
1385 status_t ret = initCheck();
1386 if (ret != NO_ERROR) {
1387 return ret;
1388 }
1389
1390 // check calling permissions
1391 if (!settingsAllowed()) {
1392 return PERMISSION_DENIED;
1393 }
1394
1395 AutoMutex lock(mHardwareLock);
1396 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1397 mHardwareStatus = AUDIO_SET_FM_VOLUME;
1398 ret = dev->set_fm_volume(dev, value);
1399 mHardwareStatus = AUDIO_HW_IDLE;
1400
1401 return ret;
1402}
1403#endif
1404
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1406{
1407
1408 Mutex::Autolock _l(mLock);
1409
vivek mehta2192bc92012-12-04 11:46:08 -08001410 sp<IBinder> binder = client->asBinder();
1411 if (mNotificationClients.indexOfKey(binder) < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 sp<NotificationClient> notificationClient = new NotificationClient(this,
1413 client,
vivek mehta2192bc92012-12-04 11:46:08 -08001414 binder);
Dorian Snyderf32d5702013-03-01 14:25:46 -08001415 ALOGV("registerClient() client %p, binder %d", notificationClient.get(), binder.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416
vivek mehta2192bc92012-12-04 11:46:08 -08001417 mNotificationClients.add(binder, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418
1419 sp<IBinder> binder = client->asBinder();
1420 binder->linkToDeath(notificationClient);
1421
1422 // the config change is always sent from playback or record threads to avoid deadlock
1423 // with AudioSystem::gLock
1424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001425 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426 }
1427
1428 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001429 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430 }
1431 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08001432#ifdef QCOM_HARDWARE
1433 // Send the notification to the client only once.
1434 if (mA2DPHandle != -1) {
1435 ALOGV("A2DP active. Notifying the registered client");
1436 client->ioConfigChanged(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
1437 }
1438#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439}
1440
vivek mehta2192bc92012-12-04 11:46:08 -08001441#ifdef QCOM_HARDWARE
1442status_t AudioFlinger::deregisterClient(const sp<IAudioFlingerClient>& client)
1443{
1444 ALOGV("deregisterClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
1445 Mutex::Autolock _l(mLock);
1446
1447 sp<IBinder> binder = client->asBinder();
1448 int index = mNotificationClients.indexOfKey(binder);
1449 if (index >= 0) {
1450 mNotificationClients.removeItemsAt(index);
1451 return true;
1452 }
1453
1454 return false;
1455}
1456#endif
1457
1458void AudioFlinger::removeNotificationClient(sp<IBinder> binder)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459{
1460 Mutex::Autolock _l(mLock);
1461
vivek mehta2192bc92012-12-04 11:46:08 -08001462 mNotificationClients.removeItem(binder);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001463
vivek mehta2192bc92012-12-04 11:46:08 -08001464 int pid = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01001465 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001466 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001467 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001468 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001469 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001470 ALOGV(" pid %d @ %d", ref->mPid, i);
1471 if (ref->mPid == pid) {
1472 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001473 mAudioSessionRefs.removeAt(i);
1474 delete ref;
1475 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001476 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001477 } else {
1478 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001479 }
1480 }
1481 if (removed) {
1482 purgeStaleEffects_l();
1483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484}
1485
1486// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001487void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488{
vivek mehta2192bc92012-12-04 11:46:08 -08001489#ifdef QCOM_HARDWARE
1490 ALOGV("AudioFlinger::audioConfigChanged_l: event %d", event);
1491 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
1492 mIsEffectConfigChanged = true;
1493 }
1494#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495 size_t size = mNotificationClients.size();
1496 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001497 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1498 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 }
1500}
1501
1502// removeClient_l() must be called with AudioFlinger::mLock held
1503void AudioFlinger::removeClient_l(pid_t pid)
1504{
Steve Block3856b092011-10-20 11:56:00 +01001505 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 mClients.removeItem(pid);
1507}
1508
Eric Laurent717e1282012-06-29 16:36:52 -07001509// getEffectThread_l() must be called with AudioFlinger::mLock held
1510sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1511{
1512 sp<PlaybackThread> thread;
1513
1514 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1515 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1516 ALOG_ASSERT(thread == 0);
1517 thread = mPlaybackThreads.valueAt(i);
1518 }
1519 }
1520
1521 return thread;
1522}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523
1524// ----------------------------------------------------------------------------
1525
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001526AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001527 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001528 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001529 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001530 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001531 // mChannelMask
1532 mChannelCount(0),
1533 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1534 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001535 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1536 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001537 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001538 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539{
1540}
1541
1542AudioFlinger::ThreadBase::~ThreadBase()
1543{
1544 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001545 // do not lock the mutex in destructor
1546 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001547 if (mPowerManager != 0) {
1548 sp<IBinder> binder = mPowerManager->asBinder();
1549 binder->unlinkToDeath(mDeathRecipient);
1550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551}
1552
1553void AudioFlinger::ThreadBase::exit()
1554{
Steve Block3856b092011-10-20 11:56:00 +01001555 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001556 // do any cleanup required for exit to succeed
1557 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001559 // This lock prevents the following race in thread (uniprocessor for illustration):
1560 // if (!exitPending()) {
1561 // // context switch from here to exit()
1562 // // exit() calls requestExit(), what exitPending() observes
1563 // // exit() calls signal(), which is dropped since no waiters
1564 // // context switch back from exit() to here
1565 // mWaitWorkCV.wait(...);
1566 // // now thread is hung
1567 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001568 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001570 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001572 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1573 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 requestExitAndWait();
1575}
1576
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1578{
1579 status_t status;
1580
Steve Block3856b092011-10-20 11:56:00 +01001581 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 Mutex::Autolock _l(mLock);
1583
1584 mNewParameters.add(keyValuePairs);
1585 mWaitWorkCV.signal();
1586 // wait condition with timeout in case the thread loop has exited
1587 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001588 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 status = mParamStatus;
1590 mWaitWorkCV.signal();
1591 } else {
1592 status = TIMED_OUT;
1593 }
1594 return status;
1595}
1596
vivek mehta2192bc92012-12-04 11:46:08 -08001597#ifdef QCOM_HARDWARE
1598void AudioFlinger::ThreadBase::effectConfigChanged() {
1599 mAudioFlinger->mLock.lock();
1600 ALOGV("New effect is being added to LPA chain, Notifying LPA Direct Track");
1601 mAudioFlinger->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
1602 mAudioFlinger->mLock.unlock();
1603}
1604#endif
1605
Eric Laurent896adcd2012-09-13 11:18:23 -07001606void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607{
1608 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001609 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610}
1611
Eric Laurent896adcd2012-09-13 11:18:23 -07001612// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1613void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614{
Eric Laurent896adcd2012-09-13 11:18:23 -07001615 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1616 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1617 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1618 mWaitWorkCV.signal();
1619}
1620
1621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1623{
1624 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1625 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1626 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1627 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 mWaitWorkCV.signal();
1629}
1630
1631void AudioFlinger::ThreadBase::processConfigEvents()
1632{
1633 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001634 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001635 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001636 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 mConfigEvents.removeAt(0);
1638 // release mLock before locking AudioFlinger mLock: lock order is always
1639 // AudioFlinger then ThreadBase to avoid cross deadlock
1640 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001641 switch(event->type()) {
1642 case CFG_EVENT_PRIO: {
1643 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1644 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1645 if (err != 0) {
1646 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1647 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1648 }
1649 } break;
1650 case CFG_EVENT_IO: {
1651 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1652 mAudioFlinger->mLock.lock();
1653 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1654 mAudioFlinger->mLock.unlock();
1655 } break;
1656 default:
1657 ALOGE("processConfigEvents() unknown event type %d", event->type());
1658 break;
1659 }
1660 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 mLock.lock();
1662 }
1663 mLock.unlock();
1664}
1665
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001666void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667{
1668 const size_t SIZE = 256;
1669 char buffer[SIZE];
1670 String8 result;
1671
1672 bool locked = tryLock(mLock);
1673 if (!locked) {
1674 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1675 write(fd, buffer, strlen(buffer));
1676 }
1677
Eric Laurent612bbb52012-03-14 15:03:26 -07001678 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1679 result.append(buffer);
1680 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1681 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1683 result.append(buffer);
1684 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1685 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001686 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1687 result.append(buffer);
1688 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 result.append(buffer);
1690 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1691 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001692 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1693 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1695 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001696 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697 result.append(buffer);
1698
1699 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1700 result.append(buffer);
1701 result.append(" Index Command");
1702 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1703 snprintf(buffer, SIZE, "\n %02d ", i);
1704 result.append(buffer);
1705 result.append(mNewParameters[i]);
1706 }
1707
1708 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1709 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001711 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 result.append(buffer);
1713 }
1714 result.append("\n");
1715
1716 write(fd, result.string(), result.size());
1717
1718 if (locked) {
1719 mLock.unlock();
1720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721}
1722
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001723void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001724{
1725 const size_t SIZE = 256;
1726 char buffer[SIZE];
1727 String8 result;
1728
1729 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1730 write(fd, buffer, strlen(buffer));
1731
1732 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1733 sp<EffectChain> chain = mEffectChains[i];
1734 if (chain != 0) {
1735 chain->dump(fd, args);
1736 }
1737 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001738}
1739
Eric Laurentfeb0db62011-07-22 09:04:31 -07001740void AudioFlinger::ThreadBase::acquireWakeLock()
1741{
1742 Mutex::Autolock _l(mLock);
1743 acquireWakeLock_l();
1744}
1745
1746void AudioFlinger::ThreadBase::acquireWakeLock_l()
1747{
1748 if (mPowerManager == 0) {
1749 // use checkService() to avoid blocking if power service is not up yet
1750 sp<IBinder> binder =
1751 defaultServiceManager()->checkService(String16("power"));
1752 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001753 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001754 } else {
1755 mPowerManager = interface_cast<IPowerManager>(binder);
1756 binder->linkToDeath(mDeathRecipient);
1757 }
1758 }
1759 if (mPowerManager != 0) {
1760 sp<IBinder> binder = new BBinder();
1761 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1762 binder,
1763 String16(mName));
1764 if (status == NO_ERROR) {
1765 mWakeLockToken = binder;
1766 }
Steve Block3856b092011-10-20 11:56:00 +01001767 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001768 }
1769}
1770
1771void AudioFlinger::ThreadBase::releaseWakeLock()
1772{
1773 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001774 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001775}
1776
1777void AudioFlinger::ThreadBase::releaseWakeLock_l()
1778{
1779 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001780 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001781 if (mPowerManager != 0) {
1782 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1783 }
1784 mWakeLockToken.clear();
1785 }
1786}
1787
1788void AudioFlinger::ThreadBase::clearPowerManager()
1789{
1790 Mutex::Autolock _l(mLock);
1791 releaseWakeLock_l();
1792 mPowerManager.clear();
1793}
1794
1795void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1796{
1797 sp<ThreadBase> thread = mThread.promote();
1798 if (thread != 0) {
1799 thread->clearPowerManager();
1800 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001801 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001802}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001803
Eric Laurent59255e42011-07-27 19:49:51 -07001804void AudioFlinger::ThreadBase::setEffectSuspended(
1805 const effect_uuid_t *type, bool suspend, int sessionId)
1806{
1807 Mutex::Autolock _l(mLock);
1808 setEffectSuspended_l(type, suspend, sessionId);
1809}
1810
1811void AudioFlinger::ThreadBase::setEffectSuspended_l(
1812 const effect_uuid_t *type, bool suspend, int sessionId)
1813{
Glenn Kasten090f0192012-01-30 13:00:02 -08001814 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001815 if (chain != 0) {
1816 if (type != NULL) {
1817 chain->setEffectSuspended_l(type, suspend);
1818 } else {
1819 chain->setEffectSuspendedAll_l(suspend);
1820 }
1821 }
1822
1823 updateSuspendedSessions_l(type, suspend, sessionId);
1824}
1825
1826void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1827{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001828 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001829 if (index < 0) {
1830 return;
1831 }
1832
Glenn Kasten0a7af182012-07-09 16:09:19 -07001833 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1834 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001835
1836 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001837 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001838 for (int j = 0; j < desc->mRefCount; j++) {
1839 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1840 chain->setEffectSuspendedAll_l(true);
1841 } else {
Steve Block3856b092011-10-20 11:56:00 +01001842 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001843 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001844 chain->setEffectSuspended_l(&desc->mType, true);
1845 }
1846 }
1847 }
1848}
1849
Eric Laurent59255e42011-07-27 19:49:51 -07001850void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1851 bool suspend,
1852 int sessionId)
1853{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001854 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001855
1856 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1857
1858 if (suspend) {
1859 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001860 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001861 } else {
1862 mSuspendedSessions.add(sessionId, sessionEffects);
1863 }
1864 } else {
1865 if (index < 0) {
1866 return;
1867 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001868 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001869 }
1870
1871
1872 int key = EffectChain::kKeyForSuspendAll;
1873 if (type != NULL) {
1874 key = type->timeLow;
1875 }
1876 index = sessionEffects.indexOfKey(key);
1877
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001878 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001879 if (suspend) {
1880 if (index >= 0) {
1881 desc = sessionEffects.valueAt(index);
1882 } else {
1883 desc = new SuspendedSessionDesc();
1884 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001885 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001886 }
1887 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001888 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001889 }
1890 desc->mRefCount++;
1891 } else {
1892 if (index < 0) {
1893 return;
1894 }
1895 desc = sessionEffects.valueAt(index);
1896 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001898 sessionEffects.removeItemsAt(index);
1899 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001900 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001901 sessionId);
1902 mSuspendedSessions.removeItem(sessionId);
1903 }
1904 }
1905 }
1906 if (!sessionEffects.isEmpty()) {
1907 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1908 }
1909}
1910
1911void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1912 bool enabled,
1913 int sessionId)
1914{
1915 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001916 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1917}
Eric Laurent59255e42011-07-27 19:49:51 -07001918
Eric Laurenta85a74a2011-10-19 11:44:54 -07001919void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1920 bool enabled,
1921 int sessionId)
1922{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001923 if (mType != RECORD) {
1924 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1925 // another session. This gives the priority to well behaved effect control panels
1926 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001927 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1928 // global effects
1929 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001930 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1931 }
1932 }
Eric Laurent59255e42011-07-27 19:49:51 -07001933
1934 sp<EffectChain> chain = getEffectChain_l(sessionId);
1935 if (chain != 0) {
1936 chain->checkSuspendOnEffectEnabled(effect, enabled);
1937 }
1938}
1939
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940// ----------------------------------------------------------------------------
1941
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001942AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1943 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001944 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001945 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001946 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001947 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001948 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001949 // mStreamTypes[] initialized in constructor body
1950 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001951 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001952 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001953 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001954 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001955 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001956 // index 0 is reserved for normal mixer's submix
1957 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958{
Glenn Kasten480b4682012-02-28 12:30:08 -08001959 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001960
John Grossmanee578c02012-07-23 17:05:46 -07001961 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1962 // it would be safer to explicitly pass initial masterVolume/masterMute as
1963 // parameter.
1964 //
1965 // If the HAL we are using has support for master volume or master mute,
1966 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1967 // and the mute set to false).
1968 mMasterVolume = audioFlinger->masterVolume_l();
1969 mMasterMute = audioFlinger->masterMute_l();
1970 if (mOutput && mOutput->audioHwDev) {
1971 if (mOutput->audioHwDev->canSetMasterVolume()) {
1972 mMasterVolume = 1.0;
1973 }
1974
1975 if (mOutput->audioHwDev->canSetMasterMute()) {
1976 mMasterMute = false;
1977 }
1978 }
1979
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 readOutputParameters();
1981
Glenn Kasten263709e2012-01-06 08:40:01 -08001982 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001983 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1984 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1985 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001986 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1987 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001989 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1990 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991}
1992
1993AudioFlinger::PlaybackThread::~PlaybackThread()
1994{
1995 delete [] mMixBuffer;
1996}
1997
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001998void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999{
2000 dumpInternals(fd, args);
2001 dumpTracks(fd, args);
2002 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003}
2004
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002005void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006{
2007 const size_t SIZE = 256;
2008 char buffer[SIZE];
2009 String8 result;
2010
Glenn Kasten58912562012-04-03 10:45:00 -07002011 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
2012 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2013 const stream_type_t *st = &mStreamTypes[i];
2014 if (i > 0) {
2015 result.appendFormat(", ");
2016 }
2017 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2018 if (st->mute) {
2019 result.append("M");
2020 }
2021 }
2022 result.append("\n");
2023 write(fd, result.string(), result.length());
2024 result.clear();
2025
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
2027 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002028 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 for (size_t i = 0; i < mTracks.size(); ++i) {
2030 sp<Track> track = mTracks[i];
2031 if (track != 0) {
2032 track->dump(buffer, SIZE);
2033 result.append(buffer);
2034 }
2035 }
2036
2037 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
2038 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07002039 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08002041 sp<Track> track = mActiveTracks[i].promote();
2042 if (track != 0) {
2043 track->dump(buffer, SIZE);
2044 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 }
2046 }
2047 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07002048
2049 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2050 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
2051 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
2052 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053}
2054
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07002055void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056{
2057 const size_t SIZE = 256;
2058 char buffer[SIZE];
2059 String8 result;
2060
2061 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
2062 result.append(buffer);
2063 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
2064 result.append(buffer);
2065 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
2066 result.append(buffer);
2067 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
2068 result.append(buffer);
2069 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
2070 result.append(buffer);
2071 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
2072 result.append(buffer);
2073 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
2074 result.append(buffer);
2075 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002076 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077
2078 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079}
2080
2081// Thread virtuals
2082status_t AudioFlinger::PlaybackThread::readyToRun()
2083{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002084 status_t status = initCheck();
2085 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00002086 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002087 } else {
Steve Block29357bc2012-01-06 19:20:56 +00002088 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002090 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091}
2092
2093void AudioFlinger::PlaybackThread::onFirstRef()
2094{
Eric Laurentfeb0db62011-07-22 09:04:31 -07002095 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096}
2097
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07002098// ThreadBase virtuals
2099void AudioFlinger::PlaybackThread::preExit()
2100{
2101 ALOGV(" preExit()");
2102 // FIXME this is using hard-coded strings but in the future, this functionality will be
2103 // converted to use audio HAL extensions required to support tunneling
2104 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
2105}
2106
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07002108sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08002110 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08002112 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07002113 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 int frameCount,
2115 const sp<IMemory>& sharedBuffer,
2116 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07002117 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08002118 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 status_t *status)
2120{
2121 sp<Track> track;
2122 status_t lStatus;
2123
Glenn Kasten73d22752012-03-19 13:38:30 -07002124 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
2125
2126 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07002127 if (flags & IAudioFlinger::TRACK_FAST) {
2128 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07002129 // not timed
2130 (!isTimed) &&
2131 // either of these use cases:
2132 (
2133 // use case 1: shared buffer with any frame count
2134 (
2135 (sharedBuffer != 0)
2136 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07002137 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07002138 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08002139 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07002140 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07002141 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07002142 )
2143 ) &&
2144 // PCM data
2145 audio_is_linear_pcm(format) &&
2146 // mono or stereo
2147 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
2148 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07002149#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07002150 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07002151 (sampleRate == mSampleRate) &&
2152#endif
2153 // normal mixer has an associated fast mixer
2154 hasFastMixer() &&
2155 // there are sufficient fast track slots available
2156 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07002157 // FIXME test that MixerThread for this fast track has a capable output HAL
2158 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07002159 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07002160 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
2161 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07002162 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002163 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07002164 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002165 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07002166 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07002167 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07002168 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07002169 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2170 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
2171 audio_is_linear_pcm(format),
2172 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07002173 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07002174 // For compatibility with AudioTrack calculation, buffer depth is forced
2175 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
2176 // This is probably too conservative, but legacy application code may depend on it.
2177 // If you change this calculation, also review the start threshold which is related.
2178 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
2179 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
2180 if (minBufCount < 2) {
2181 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07002182 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07002183 int minFrameCount = mNormalFrameCount * minBufCount;
2184 if (frameCount < minFrameCount) {
2185 frameCount = minFrameCount;
2186 }
2187 }
Glenn Kasten73d22752012-03-19 13:38:30 -07002188 }
2189
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002191 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
2192 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00002193 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002194 "for output %p with format %d",
2195 sampleRate, format, channelMask, mOutput, mFormat);
2196 lStatus = BAD_VALUE;
2197 goto Exit;
2198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
2200 } else {
2201 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
2202 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00002203 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 lStatus = BAD_VALUE;
2205 goto Exit;
2206 }
2207 }
2208
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002209 lStatus = initCheck();
2210 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002211 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212 goto Exit;
2213 }
2214
2215 { // scope for mLock
2216 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002217
2218 // all tracks in same audio session must share the same routing strategy otherwise
2219 // conflicts will happen when tracks are moved from one output to another by audio policy
2220 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08002221 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07002222 for (size_t i = 0; i < mTracks.size(); ++i) {
2223 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08002224 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002225 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07002226 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00002227 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07002228 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07002229 lStatus = BAD_VALUE;
2230 goto Exit;
2231 }
2232 }
2233 }
2234
John Grossman4ff14ba2012-02-08 16:37:41 -08002235 if (!isTimed) {
2236 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07002237 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08002238 } else {
2239 track = TimedTrack::create(this, client, streamType, sampleRate, format,
2240 channelMask, frameCount, sharedBuffer, sessionId);
2241 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07002242 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 lStatus = NO_MEMORY;
2244 goto Exit;
2245 }
2246 mTracks.add(track);
2247
2248 sp<EffectChain> chain = getEffectChain_l(sessionId);
2249 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002250 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08002252 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07002253 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002255
Eric Laurent896adcd2012-09-13 11:18:23 -07002256 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
2257 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2258 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2259 // so ask activity manager to do this on our behalf
2260 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08002261 }
2262 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08002263
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 lStatus = NO_ERROR;
2265
2266Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002267 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 *status = lStatus;
2269 }
2270 return track;
2271}
2272
Eric Laurente737cda2012-05-22 18:55:44 -07002273uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
2274{
2275 if (mFastMixer != NULL) {
2276 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2277 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2278 }
2279 return latency;
2280}
2281
2282uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
2283{
2284 return latency;
2285}
2286
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287uint32_t AudioFlinger::PlaybackThread::latency() const
2288{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002289 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07002290 return latency_l();
2291}
2292uint32_t AudioFlinger::PlaybackThread::latency_l() const
2293{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002294 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07002295 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002296 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 return 0;
2298 }
2299}
2300
Glenn Kasten6637baa2012-01-09 09:40:36 -08002301void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002303 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002304 // Don't apply master volume in SW if our HAL can do it for us.
2305 if (mOutput && mOutput->audioHwDev &&
2306 mOutput->audioHwDev->canSetMasterVolume()) {
2307 mMasterVolume = 1.0;
2308 } else {
2309 mMasterVolume = value;
2310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311}
2312
Glenn Kasten6637baa2012-01-09 09:40:36 -08002313void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002315 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07002316 // Don't apply master mute in SW if our HAL can do it for us.
2317 if (mOutput && mOutput->audioHwDev &&
2318 mOutput->audioHwDev->canSetMasterMute()) {
2319 mMasterMute = false;
2320 } else {
2321 mMasterMute = muted;
2322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323}
2324
Glenn Kasten6637baa2012-01-09 09:40:36 -08002325void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002327 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329}
2330
Glenn Kasten6637baa2012-01-09 09:40:36 -08002331void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002333 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335}
2336
Glenn Kastenfff6d712012-01-12 16:38:12 -08002337float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338{
Glenn Kasten6637baa2012-01-09 09:40:36 -08002339 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 return mStreamTypes[stream].volume;
2341}
2342
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343// addTrack_l() must be called with ThreadBase::mLock held
2344status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2345{
2346 status_t status = ALREADY_EXISTS;
2347
2348 // set retry count for buffer fill
2349 track->mRetryCount = kMaxTrackStartupRetries;
2350 if (mActiveTracks.indexOf(track) < 0) {
2351 // the track is newly added, make sure it fills up all its
2352 // buffers before playing. This is to ensure the client will
2353 // effectively get the latency it requested.
2354 track->mFillingUpStatus = Track::FS_FILLING;
2355 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07002356 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 mActiveTracks.add(track);
2358 if (track->mainBuffer() != mMixBuffer) {
2359 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2360 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002361 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002362 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 }
2364 }
2365
2366 status = NO_ERROR;
2367 }
2368
Steve Block3856b092011-10-20 11:56:00 +01002369 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 mWaitWorkCV.broadcast();
2371
2372 return status;
2373}
2374
2375// destroyTrack_l() must be called with ThreadBase::mLock held
2376void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2377{
2378 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002379 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002381 removeTrack_l(track);
2382 }
2383}
2384
2385void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2386{
Eric Laurent29864602012-05-08 18:57:51 -07002387 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002388 mTracks.remove(track);
2389 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002390 // redundant as track is about to be destroyed, for dumpsys only
2391 track->mName = -1;
2392 if (track->isFastTrack()) {
2393 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002394 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002395 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2396 mFastTrackAvailMask |= 1 << index;
2397 // redundant as track is about to be destroyed, for dumpsys only
2398 track->mFastIndex = -1;
2399 }
Eric Laurentb469b942011-05-09 12:09:06 -07002400 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2401 if (chain != 0) {
2402 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 }
2404}
2405
2406String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2407{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002408 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002409 char *s;
2410
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002411 Mutex::Autolock _l(mLock);
2412 if (initCheck() != NO_ERROR) {
2413 return out_s8;
2414 }
2415
Dima Zavin799a70e2011-04-18 16:57:27 -07002416 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002417 out_s8 = String8(s);
2418 free(s);
2419 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420}
2421
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002422// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2424 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002425 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426
Steve Block3856b092011-10-20 11:56:00 +01002427 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428
2429 switch (event) {
2430 case AudioSystem::OUTPUT_OPENED:
2431 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002432 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 desc.samplingRate = mSampleRate;
2434 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002435 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 desc.latency = latency();
2437 param2 = &desc;
2438 break;
2439
2440 case AudioSystem::STREAM_CONFIG_CHANGED:
2441 param2 = &param;
2442 case AudioSystem::OUTPUT_CLOSED:
2443 default:
2444 break;
2445 }
2446 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2447}
2448
2449void AudioFlinger::PlaybackThread::readOutputParameters()
2450{
Dima Zavin799a70e2011-04-18 16:57:27 -07002451 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002452 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2453 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002454 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002455 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002456 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002457 if (mFrameCount & 15) {
2458 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2459 mFrameCount);
2460 }
2461
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002462 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002463 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002464 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002465 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002466 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2467 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2468 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2469 maxNormalFrameCount = maxNormalFrameCount & ~15;
2470 if (maxNormalFrameCount < minNormalFrameCount) {
2471 maxNormalFrameCount = minNormalFrameCount;
2472 }
2473 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2474 if (multiplier <= 1.0) {
2475 multiplier = 1.0;
2476 } else if (multiplier <= 2.0) {
2477 if (2 * mFrameCount <= maxNormalFrameCount) {
2478 multiplier = 2.0;
2479 } else {
2480 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2481 }
2482 } else {
2483 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2484 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2485 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2486 // FIXME this rounding up should not be done if no HAL SRC
2487 uint32_t truncMult = (uint32_t) multiplier;
2488 if ((truncMult & 1)) {
2489 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2490 ++truncMult;
2491 }
2492 }
2493 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002494 }
Glenn Kasten58912562012-04-03 10:45:00 -07002495 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002496 mNormalFrameCount = multiplier * mFrameCount;
2497 // round up to nearest 16 frames to satisfy AudioMixer
2498 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002499 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500
Glenn Kastene9dd0172012-01-27 18:08:45 -08002501 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002502 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2503 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504
Eric Laurentde070132010-07-13 04:45:46 -07002505 // force reconfiguration of effect chains and engines to take new buffer size and audio
2506 // parameters into account
2507 // Note that mLock is not held when readOutputParameters() is called from the constructor
2508 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2509 // matter.
2510 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2511 Vector< sp<EffectChain> > effectChains = mEffectChains;
2512 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002513 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515}
2516
Eric Laurente737cda2012-05-22 18:55:44 -07002517
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2519{
Glenn Kastena0d68332012-01-27 16:47:15 -08002520 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 return BAD_VALUE;
2522 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002523 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002524 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 return INVALID_OPERATION;
2526 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002527 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528
Eric Laurent1afc26d2012-09-23 15:20:50 -07002529 if (isSuspended()) {
2530 // return an estimation of rendered frames when the output is suspended
2531 int32_t frames = mBytesWritten - latency_l();
2532 if (frames < 0) {
2533 frames = 0;
2534 }
2535 *dspFrames = (uint32_t)frames;
2536 return NO_ERROR;
2537 } else {
2538 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540}
2541
Glenn Kasten106e8a42012-08-02 13:37:12 -07002542uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543{
2544 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002545 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002547 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 }
2549
2550 for (size_t i = 0; i < mTracks.size(); ++i) {
2551 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002552 if (sessionId == track->sessionId() &&
2553 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002554 result |= TRACK_SESSION;
2555 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 }
2557 }
2558
Eric Laurent39e94f82010-07-28 01:32:47 -07002559 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560}
2561
Eric Laurentde070132010-07-13 04:45:46 -07002562uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2563{
Dima Zavinfce7a472011-04-19 22:30:36 -07002564 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002565 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002566 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2567 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002568 }
2569 for (size_t i = 0; i < mTracks.size(); i++) {
2570 sp<Track> track = mTracks[i];
2571 if (sessionId == track->sessionId() &&
2572 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002573 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002574 }
2575 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002576 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002577}
2578
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
Glenn Kastenaed850d2012-01-26 09:46:34 -08002580AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002581{
2582 Mutex::Autolock _l(mLock);
2583 return mOutput;
2584}
2585
2586AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2587{
2588 Mutex::Autolock _l(mLock);
2589 AudioStreamOut *output = mOutput;
2590 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002591 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2592 // must push a NULL and wait for ack
2593 mOutputSink.clear();
2594 mPipeSink.clear();
2595 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002596 return output;
2597}
2598
2599// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002600audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002601{
2602 if (mOutput == NULL) {
2603 return NULL;
2604 }
2605 return &mOutput->stream->common;
2606}
2607
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002608uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002609{
Eric Laurentab9071b2012-06-04 13:45:29 -07002610 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002611}
2612
Eric Laurenta011e352012-03-29 15:51:43 -07002613status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2614{
2615 if (!isValidSyncEvent(event)) {
2616 return BAD_VALUE;
2617 }
2618
2619 Mutex::Autolock _l(mLock);
2620
2621 for (size_t i = 0; i < mTracks.size(); ++i) {
2622 sp<Track> track = mTracks[i];
2623 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002624 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002625 return NO_ERROR;
2626 }
2627 }
2628
2629 return NAME_NOT_FOUND;
2630}
2631
Glenn Kasten106e8a42012-08-02 13:37:12 -07002632bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002633{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002634 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002635}
2636
Eric Laurent44a957f2012-05-15 15:26:05 -07002637void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2638{
2639 size_t count = tracksToRemove.size();
2640 if (CC_UNLIKELY(count)) {
2641 for (size_t i = 0 ; i < count ; i++) {
2642 const sp<Track>& track = tracksToRemove.itemAt(i);
2643 if ((track->sharedBuffer() != 0) &&
2644 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2645 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2646 }
2647 }
2648 }
2649
2650}
2651
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652// ----------------------------------------------------------------------------
2653
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002654AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002655 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002656 : PlaybackThread(audioFlinger, output, id, device, type),
2657 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002658 // mFastMixer below
2659 mFastMixerFutex(0)
2660 // mOutputSink below
2661 // mPipeSink below
2662 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002664 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002665 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002666 "mFrameCount=%d, mNormalFrameCount=%d",
2667 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2668 mNormalFrameCount);
2669 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2670
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002672 if (mChannelCount != FCC_2) {
2673 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674 }
Glenn Kasten58912562012-04-03 10:45:00 -07002675
2676 // create an NBAIO sink for the HAL output stream, and negotiate
2677 mOutputSink = new AudioStreamOutSink(output->stream);
2678 size_t numCounterOffers = 0;
2679 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2680 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2681 ALOG_ASSERT(index == 0);
2682
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002683 // initialize fast mixer depending on configuration
2684 bool initFastMixer;
2685 switch (kUseFastMixer) {
2686 case FastMixer_Never:
2687 initFastMixer = false;
2688 break;
2689 case FastMixer_Always:
2690 initFastMixer = true;
2691 break;
2692 case FastMixer_Static:
2693 case FastMixer_Dynamic:
2694 initFastMixer = mFrameCount < mNormalFrameCount;
2695 break;
2696 }
2697 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002698
2699 // create a MonoPipe to connect our submix to FastMixer
2700 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002701 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2702 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2703 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2704 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002705 const NBAIO_Format offers[1] = {format};
2706 size_t numCounterOffers = 0;
2707 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2708 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002709 monoPipe->setAvgFrames((mScreenState & 1) ?
2710 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002711 mPipeSink = monoPipe;
2712
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002713#ifdef TEE_SINK_FRAMES
2714 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2715 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2716 numCounterOffers = 0;
2717 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2718 ALOG_ASSERT(index == 0);
2719 mTeeSink = teeSink;
2720 PipeReader *teeSource = new PipeReader(*teeSink);
2721 numCounterOffers = 0;
2722 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2723 ALOG_ASSERT(index == 0);
2724 mTeeSource = teeSource;
2725#endif
2726
Glenn Kasten58912562012-04-03 10:45:00 -07002727 // create fast mixer and configure it initially with just one fast track for our submix
2728 mFastMixer = new FastMixer();
2729 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002730#ifdef STATE_QUEUE_DUMP
2731 sq->setObserverDump(&mStateQueueObserverDump);
2732 sq->setMutatorDump(&mStateQueueMutatorDump);
2733#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002734 FastMixerState *state = sq->begin();
2735 FastTrack *fastTrack = &state->mFastTracks[0];
2736 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2737 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2738 fastTrack->mVolumeProvider = NULL;
2739 fastTrack->mGeneration++;
2740 state->mFastTracksGen++;
2741 state->mTrackMask = 1;
2742 // fast mixer will use the HAL output sink
2743 state->mOutputSink = mOutputSink.get();
2744 state->mOutputSinkGen++;
2745 state->mFrameCount = mFrameCount;
2746 state->mCommand = FastMixerState::COLD_IDLE;
2747 // already done in constructor initialization list
2748 //mFastMixerFutex = 0;
2749 state->mColdFutexAddr = &mFastMixerFutex;
2750 state->mColdGen++;
2751 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002752 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002753 sq->end();
2754 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2755
2756 // start the fast mixer
2757 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002758 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002759 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002760 if (err != 0) {
2761 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002762 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002763 }
Glenn Kasten58912562012-04-03 10:45:00 -07002764
Glenn Kastenc15d6652012-05-30 14:52:57 -07002765#ifdef AUDIO_WATCHDOG
2766 // create and start the watchdog
2767 mAudioWatchdog = new AudioWatchdog();
2768 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2769 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2770 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002771 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002772 if (err != 0) {
2773 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002774 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002775 }
2776#endif
2777
Glenn Kasten58912562012-04-03 10:45:00 -07002778 } else {
2779 mFastMixer = NULL;
2780 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002781
2782 switch (kUseFastMixer) {
2783 case FastMixer_Never:
2784 case FastMixer_Dynamic:
2785 mNormalSink = mOutputSink;
2786 break;
2787 case FastMixer_Always:
2788 mNormalSink = mPipeSink;
2789 break;
2790 case FastMixer_Static:
2791 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2792 break;
2793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794}
2795
2796AudioFlinger::MixerThread::~MixerThread()
2797{
Glenn Kasten58912562012-04-03 10:45:00 -07002798 if (mFastMixer != NULL) {
2799 FastMixerStateQueue *sq = mFastMixer->sq();
2800 FastMixerState *state = sq->begin();
2801 if (state->mCommand == FastMixerState::COLD_IDLE) {
2802 int32_t old = android_atomic_inc(&mFastMixerFutex);
2803 if (old == -1) {
2804 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2805 }
2806 }
2807 state->mCommand = FastMixerState::EXIT;
2808 sq->end();
2809 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2810 mFastMixer->join();
2811 // Though the fast mixer thread has exited, it's state queue is still valid.
2812 // We'll use that extract the final state which contains one remaining fast track
2813 // corresponding to our sub-mix.
2814 state = sq->begin();
2815 ALOG_ASSERT(state->mTrackMask == 1);
2816 FastTrack *fastTrack = &state->mFastTracks[0];
2817 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2818 delete fastTrack->mBufferProvider;
2819 sq->end(false /*didModify*/);
2820 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002821#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002822 if (mAudioWatchdog != 0) {
2823 mAudioWatchdog->requestExit();
2824 mAudioWatchdog->requestExitAndWait();
2825 mAudioWatchdog.clear();
2826 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002827#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002828 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 delete mAudioMixer;
2830}
2831
Glenn Kasten83efdd02012-02-24 07:21:32 -08002832class CpuStats {
2833public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002834 CpuStats();
2835 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002836#ifdef DEBUG_CPU_USAGE
2837private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002838 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2839 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2840
2841 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2842
2843 int mCpuNum; // thread's current CPU number
2844 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002845#endif
2846};
2847
Glenn Kasten190a46f2012-03-06 11:27:10 -08002848CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002849#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002850 : mCpuNum(-1), mCpukHz(-1)
2851#endif
2852{
2853}
2854
2855void CpuStats::sample(const String8 &title) {
2856#ifdef DEBUG_CPU_USAGE
2857 // get current thread's delta CPU time in wall clock ns
2858 double wcNs;
2859 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2860
2861 // record sample for wall clock statistics
2862 if (valid) {
2863 mWcStats.sample(wcNs);
2864 }
2865
2866 // get the current CPU number
2867 int cpuNum = sched_getcpu();
2868
2869 // get the current CPU frequency in kHz
2870 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2871
2872 // check if either CPU number or frequency changed
2873 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2874 mCpuNum = cpuNum;
2875 mCpukHz = cpukHz;
2876 // ignore sample for purposes of cycles
2877 valid = false;
2878 }
2879
2880 // if no change in CPU number or frequency, then record sample for cycle statistics
2881 if (valid && mCpukHz > 0) {
2882 double cycles = wcNs * cpukHz * 0.000001;
2883 mHzStats.sample(cycles);
2884 }
2885
2886 unsigned n = mWcStats.n();
2887 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002888 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002889 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002890 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2891 double perLoop = elapsed / (double) n;
2892 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002893 double perLoop1k = perLoop * 0.001;
2894 double mean = mWcStats.mean();
2895 double stddev = mWcStats.stddev();
2896 double minimum = mWcStats.minimum();
2897 double maximum = mWcStats.maximum();
2898 double meanCycles = mHzStats.mean();
2899 double stddevCycles = mHzStats.stddev();
2900 double minCycles = mHzStats.minimum();
2901 double maxCycles = mHzStats.maximum();
2902 mCpuUsage.resetElapsed();
2903 mWcStats.reset();
2904 mHzStats.reset();
2905 ALOGD("CPU usage for %s over past %.1f secs\n"
2906 " (%u mixer loops at %.1f mean ms per loop):\n"
2907 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2908 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2909 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2910 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002911 elapsed * .000000001, n, perLoop * .000001,
2912 mean * .001,
2913 stddev * .001,
2914 minimum * .001,
2915 maximum * .001,
2916 mean / perLoop100,
2917 stddev / perLoop100,
2918 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002919 maximum / perLoop100,
2920 meanCycles / perLoop1k,
2921 stddevCycles / perLoop1k,
2922 minCycles / perLoop1k,
2923 maxCycles / perLoop1k);
2924
Glenn Kasten83efdd02012-02-24 07:21:32 -08002925 }
2926 }
2927#endif
2928};
2929
Glenn Kasten37d825e2012-02-24 07:21:48 -08002930void AudioFlinger::PlaybackThread::checkSilentMode_l()
2931{
2932 if (!mMasterMute) {
2933 char value[PROPERTY_VALUE_MAX];
2934 if (property_get("ro.audio.silent", value, "0") > 0) {
2935 char *endptr;
2936 unsigned long ul = strtoul(value, &endptr, 0);
2937 if (*endptr == '\0' && ul != 0) {
2938 ALOGD("Silence is golden");
2939 // The setprop command will not allow a property to be changed after
2940 // the first time it is set, so we don't have to worry about un-muting.
2941 setMasterMute_l(true);
2942 }
2943 }
2944 }
2945}
2946
Glenn Kasten000f0e32012-03-01 17:10:56 -08002947bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948{
2949 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002950
Glenn Kasten000f0e32012-03-01 17:10:56 -08002951 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002952
2953 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002955
Glenn Kasten000f0e32012-03-01 17:10:56 -08002956 // DUPLICATING
2957 // FIXME could this be made local to while loop?
2958 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002959
Glenn Kasten66fcab92012-02-24 14:59:21 -08002960 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002961 sleepTime = idleSleepTime;
2962
Glenn Kasten9f34a362012-03-20 16:46:41 -07002963 if (mType == MIXER) {
2964 sleepTimeShift = 0;
2965 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002966
Glenn Kasten83efdd02012-02-24 07:21:32 -08002967 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002968 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969
Eric Laurentfeb0db62011-07-22 09:04:31 -07002970 acquireWakeLock();
2971
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 while (!exitPending())
2973 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002974 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002975
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002976 Vector< sp<EffectChain> > effectChains;
2977
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 processConfigEvents();
2979
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 { // scope for mLock
2981
2982 Mutex::Autolock _l(mLock);
2983
2984 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002985 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 }
2987
Glenn Kastenfa26a852012-03-06 11:28:04 -08002988 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002989
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002991 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002992 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002994
2995 threadLoop_standby();
2996
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 }
2999
Glenn Kasten3e074702012-02-28 18:40:35 -08003000 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 // we're about to wait, flush the binder command buffer
3002 IPCThreadState::self()->flushCommands();
3003
Glenn Kastenfa26a852012-03-06 11:28:04 -08003004 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003005
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 if (exitPending()) break;
3007
Eric Laurentfeb0db62011-07-22 09:04:31 -07003008 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08003010 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08003012 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003013 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003014
Eric Laurentda747442012-04-25 18:53:13 -07003015 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07003016 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07003017 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003018
Glenn Kasten37d825e2012-02-24 07:21:48 -08003019 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020
Glenn Kasten000f0e32012-03-01 17:10:56 -08003021 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003023 if (mType == MIXER) {
3024 sleepTimeShift = 0;
3025 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003026
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 continue;
3028 }
3029 }
3030
Glenn Kasten81028042012-04-30 18:15:12 -07003031 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07003032 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033
3034 // prevent any changes in effect chain list and in each effect chain
3035 // during mixing and effect process as the audio buffers could be deleted
3036 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003037 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08003038 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039
Glenn Kastenfec279f2012-03-08 07:47:15 -08003040 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003041 threadLoop_mix();
3042 } else {
3043 threadLoop_sleepTime();
3044 }
3045
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003046 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003047 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07003048 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003049 }
3050
3051 // only process effects if we're going to write
3052 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08003053 for (size_t i = 0; i < effectChains.size(); i ++) {
vivek mehta2192bc92012-12-04 11:46:08 -08003054#ifdef QCOM_HARDWARE
3055 if (effectChains[i] != mAudioFlinger->mLPAEffectChain)
3056#endif
3057 effectChains[i]->process_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003058 }
3059 }
3060
3061 // enable changes in effect chain
3062 unlockEffectChains(effectChains);
3063
3064 // sleepTime == 0 means we must write to audio hardware
3065 if (sleepTime == 0) {
3066
3067 threadLoop_write();
3068
3069if (mType == MIXER) {
3070 // write blocked detection
3071 nsecs_t now = systemTime();
3072 nsecs_t delta = now - mLastWriteTime;
3073 if (!mStandby && delta > maxPeriod) {
3074 mNumDelayedWrites++;
3075 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07003076#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07003077 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003078#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08003079 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3080 ns2ms(delta), mNumDelayedWrites, this);
3081 lastWarning = now;
3082 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003083 }
3084}
3085
3086 mStandby = false;
3087 } else {
3088 usleep(sleepTime);
3089 }
3090
Glenn Kasten58912562012-04-03 10:45:00 -07003091 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08003092 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07003093 // same lock. This will also mutate and push a new fast mixer state.
3094 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003095 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003096
Glenn Kastenfa26a852012-03-06 11:28:04 -08003097 // FIXME I don't understand the need for this here;
3098 // it was in the original code but maybe the
3099 // assignment in saveOutputTracks() makes this unnecessary?
3100 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08003101
3102 // Effect chains will be actually deleted here if they were removed from
3103 // mEffectChains list during mixing or effects processing
3104 effectChains.clear();
3105
3106 // FIXME Note that the above .clear() is no longer necessary since effectChains
3107 // is now local to this block, but will keep it for now (at least until merge done).
3108 }
3109
Glenn Kasten9f34a362012-03-20 16:46:41 -07003110 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
3111 if (mType == MIXER || mType == DIRECT) {
3112 // put output stream into standby mode
3113 if (!mStandby) {
3114 mOutput->stream->common.standby(&mOutput->stream->common);
3115 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003116 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003117
3118 releaseWakeLock();
3119
3120 ALOGV("Thread %p type %d exiting", this, mType);
3121 return false;
3122}
3123
Glenn Kasten58912562012-04-03 10:45:00 -07003124void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3125{
Glenn Kasten58912562012-04-03 10:45:00 -07003126 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3127}
3128
3129void AudioFlinger::MixerThread::threadLoop_write()
3130{
3131 // FIXME we should only do one push per cycle; confirm this is true
3132 // Start the fast mixer if it's not already running
3133 if (mFastMixer != NULL) {
3134 FastMixerStateQueue *sq = mFastMixer->sq();
3135 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003136 if (state->mCommand != FastMixerState::MIX_WRITE &&
3137 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003138 if (state->mCommand == FastMixerState::COLD_IDLE) {
3139 int32_t old = android_atomic_inc(&mFastMixerFutex);
3140 if (old == -1) {
3141 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3142 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003143#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003144 if (mAudioWatchdog != 0) {
3145 mAudioWatchdog->resume();
3146 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003147#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003148 }
3149 state->mCommand = FastMixerState::MIX_WRITE;
3150 sq->end();
3151 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003152 if (kUseFastMixer == FastMixer_Dynamic) {
3153 mNormalSink = mPipeSink;
3154 }
Glenn Kasten58912562012-04-03 10:45:00 -07003155 } else {
3156 sq->end(false /*didModify*/);
3157 }
3158 }
3159 PlaybackThread::threadLoop_write();
3160}
3161
Glenn Kasten000f0e32012-03-01 17:10:56 -08003162// shared by MIXER and DIRECT, overridden by DUPLICATING
3163void AudioFlinger::PlaybackThread::threadLoop_write()
3164{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003165 // FIXME rewrite to reduce number of system calls
3166 mLastWriteTime = systemTime();
3167 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07003168 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07003169
Eric Laurent67c0a582012-05-01 19:31:12 -07003170 // If an NBAIO sink is present, use it to write the normal mixer's submix
3171 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07003172#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07003173 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07003174#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003175 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07003176#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07003177 // update the setpoint when gScreenState changes
3178 uint32_t screenState = gScreenState;
3179 if (screenState != mScreenState) {
3180 mScreenState = screenState;
3181 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3182 if (pipe != NULL) {
3183 pipe->setAvgFrames((mScreenState & 1) ?
3184 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3185 }
3186 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003187 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003188#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07003189 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07003190#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07003191 if (framesWritten > 0) {
3192 bytesWritten = framesWritten << mBitShift;
3193 } else {
3194 bytesWritten = framesWritten;
3195 }
3196 // otherwise use the HAL / AudioStreamOut directly
3197 } else {
3198 // Direct output thread.
3199 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07003200 }
3201
Eric Laurent67c0a582012-05-01 19:31:12 -07003202 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003203 mNumWrites++;
3204 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003205}
3206
Glenn Kasten58912562012-04-03 10:45:00 -07003207void AudioFlinger::MixerThread::threadLoop_standby()
3208{
3209 // Idle the fast mixer if it's currently running
3210 if (mFastMixer != NULL) {
3211 FastMixerStateQueue *sq = mFastMixer->sq();
3212 FastMixerState *state = sq->begin();
3213 if (!(state->mCommand & FastMixerState::IDLE)) {
3214 state->mCommand = FastMixerState::COLD_IDLE;
3215 state->mColdFutexAddr = &mFastMixerFutex;
3216 state->mColdGen++;
3217 mFastMixerFutex = 0;
3218 sq->end();
3219 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3220 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07003221 if (kUseFastMixer == FastMixer_Dynamic) {
3222 mNormalSink = mOutputSink;
3223 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003224#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003225 if (mAudioWatchdog != 0) {
3226 mAudioWatchdog->pause();
3227 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003228#endif
Glenn Kasten58912562012-04-03 10:45:00 -07003229 } else {
3230 sq->end(false /*didModify*/);
3231 }
3232 }
3233 PlaybackThread::threadLoop_standby();
3234}
3235
Glenn Kasten000f0e32012-03-01 17:10:56 -08003236// shared by MIXER and DIRECT, overridden by DUPLICATING
3237void AudioFlinger::PlaybackThread::threadLoop_standby()
3238{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07003239 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003240 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08003241}
3242
3243void AudioFlinger::MixerThread::threadLoop_mix()
3244{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003245 // obtain the presentation timestamp of the next output buffer
3246 int64_t pts;
3247 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08003248
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003249#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07003250 if (mNormalSink != 0) {
3251 status = mNormalSink->getNextWriteTimestamp(&pts);
3252 } else {
3253 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003254 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01003255#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08003256
Glenn Kasten952eeb22012-03-06 11:30:57 -08003257 if (status != NO_ERROR) {
3258 pts = AudioBufferProvider::kInvalidPTS;
3259 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003260
Glenn Kasten952eeb22012-03-06 11:30:57 -08003261 // mix buffers...
3262 mAudioMixer->process(pts);
3263 // increase sleep time progressively when application underrun condition clears.
3264 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3265 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3266 // such that we would underrun the audio HAL.
3267 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3268 sleepTimeShift--;
3269 }
3270 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003271 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003272 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08003273}
3274
3275void AudioFlinger::MixerThread::threadLoop_sleepTime()
3276{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003277 // If no tracks are ready, sleep once for the duration of an output
3278 // buffer size, then write 0s to the output
3279 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003280 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003281 sleepTime = activeSleepTime >> sleepTimeShift;
3282 if (sleepTime < kMinThreadSleepTimeUs) {
3283 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003285 // reduce sleep time in case of consecutive application underruns to avoid
3286 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3287 // duration we would end up writing less data than needed by the audio HAL if
3288 // the condition persists.
3289 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3290 sleepTimeShift++;
3291 }
3292 } else {
3293 sleepTime = idleSleepTime;
3294 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003295 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003296 memset (mMixBuffer, 0, mixBufferSize);
3297 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07003298 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08003299 }
3300 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301}
3302
3303// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08003304AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08003305 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306{
3307
Glenn Kasten29c23c32012-01-26 13:37:52 -08003308 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08003310 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 size_t mixedTracks = 0;
3312 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003313 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003314 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316
3317 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003318 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319
Eric Laurent571d49c2010-08-11 05:20:11 -07003320 if (masterMute) {
3321 masterVolume = 0;
3322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07003324 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07003326 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07003327 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 masterVolume = (float)((v + (1 << 23)) >> 24);
3329 chain.clear();
3330 }
3331
Glenn Kasten288ed212012-04-25 17:52:27 -07003332 // prepare a new state to push
3333 FastMixerStateQueue *sq = NULL;
3334 FastMixerState *state = NULL;
3335 bool didModify = false;
3336 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3337 if (mFastMixer != NULL) {
3338 sq = mFastMixer->sq();
3339 state = sq->begin();
3340 }
3341
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08003343 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 if (t == 0) continue;
3345
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003346 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07003348
Glenn Kasten288ed212012-04-25 17:52:27 -07003349 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07003350 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003351
3352 // It's theoretically possible (though unlikely) for a fast track to be created
3353 // and then removed within the same normal mix cycle. This is not a problem, as
3354 // the track never becomes active so it's fast mixer slot is never touched.
3355 // The converse, of removing an (active) track and then creating a new track
3356 // at the identical fast mixer slot within the same normal mix cycle,
3357 // is impossible because the slot isn't marked available until the end of each cycle.
3358 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07003359 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3360 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07003361 FastTrack *fastTrack = &state->mFastTracks[j];
3362
3363 // Determine whether the track is currently in underrun condition,
3364 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07003365 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3366 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07003367 uint32_t recentFull = (underruns.mBitFields.mFull -
3368 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3369 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3370 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3371 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3372 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3373 uint32_t recentUnderruns = recentPartial + recentEmpty;
3374 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003375 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003376 // or stopped which can occur when flush() is called while active
3377 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003378 track->mUnderrunCount += recentUnderruns;
3379 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003380
Glenn Kastend08f48c2012-05-01 18:14:02 -07003381 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003382 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003383 bool isActive = true;
3384 switch (track->mState) {
3385 case TrackBase::STOPPING_1:
3386 // track stays active in STOPPING_1 state until first underrun
3387 if (recentUnderruns > 0) {
3388 track->mState = TrackBase::STOPPING_2;
3389 }
3390 break;
3391 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003392 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003393 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003394 break;
3395 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003396 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003397 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003398 break;
3399 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003400 if (recentFull > 0 || recentPartial > 0) {
3401 // track has provided at least some frames recently: reset retry count
3402 track->mRetryCount = kMaxTrackRetries;
3403 }
3404 if (recentUnderruns == 0) {
3405 // no recent underruns: stay active
3406 break;
3407 }
3408 // there has recently been an underrun of some kind
3409 if (track->sharedBuffer() == 0) {
3410 // were any of the recent underruns "empty" (no frames available)?
3411 if (recentEmpty == 0) {
3412 // no, then ignore the partial underruns as they are allowed indefinitely
3413 break;
3414 }
3415 // there has recently been an "empty" underrun: decrement the retry counter
3416 if (--(track->mRetryCount) > 0) {
3417 break;
3418 }
3419 // indicate to client process that the track was disabled because of underrun;
3420 // it will then automatically call start() when data is available
3421 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3422 // remove from active list, but state remains ACTIVE [confusing but true]
3423 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003424 break;
3425 }
3426 // fall through
3427 case TrackBase::STOPPING_2:
3428 case TrackBase::PAUSED:
3429 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003430 case TrackBase::STOPPED:
3431 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003432 // Check for presentation complete if track is inactive
3433 // We have consumed all the buffers of this track.
3434 // This would be incomplete if we auto-paused on underrun
3435 {
3436 size_t audioHALFrames =
3437 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3438 size_t framesWritten =
3439 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003440 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003441 // track stays in active list until presentation is complete
3442 break;
3443 }
3444 }
3445 if (track->isStopping_2()) {
3446 track->mState = TrackBase::STOPPED;
3447 }
3448 if (track->isStopped()) {
3449 // Can't reset directly, as fast mixer is still polling this track
3450 // track->reset();
3451 // So instead mark this track as needing to be reset after push with ack
3452 resetMask |= 1 << i;
3453 }
3454 isActive = false;
3455 break;
3456 case TrackBase::IDLE:
3457 default:
3458 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003459 }
3460
3461 if (isActive) {
3462 // was it previously inactive?
3463 if (!(state->mTrackMask & (1 << j))) {
3464 ExtendedAudioBufferProvider *eabp = track;
3465 VolumeProvider *vp = track;
3466 fastTrack->mBufferProvider = eabp;
3467 fastTrack->mVolumeProvider = vp;
3468 fastTrack->mSampleRate = track->mSampleRate;
3469 fastTrack->mChannelMask = track->mChannelMask;
3470 fastTrack->mGeneration++;
3471 state->mTrackMask |= 1 << j;
3472 didModify = true;
3473 // no acknowledgement required for newly active tracks
3474 }
3475 // cache the combined master volume and stream type volume for fast mixer; this
3476 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3477 track->mCachedVolume = track->isMuted() ?
3478 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3479 ++fastTracks;
3480 } else {
3481 // was it previously active?
3482 if (state->mTrackMask & (1 << j)) {
3483 fastTrack->mBufferProvider = NULL;
3484 fastTrack->mGeneration++;
3485 state->mTrackMask &= ~(1 << j);
3486 didModify = true;
3487 // If any fast tracks were removed, we must wait for acknowledgement
3488 // because we're about to decrement the last sp<> on those tracks.
3489 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003490 } else {
3491 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003492 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003493 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003494 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003495 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003496 }
3497 continue;
3498 }
3499
3500 { // local variable scope to avoid goto warning
3501
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 audio_track_cblk_t* cblk = track->cblk();
3503
3504 // The first time a track is added we wait
3505 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003506 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003507 // make sure that we have enough frames to mix one full buffer.
3508 // enforce this condition only once to enable draining the buffer in case the client
3509 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003510 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003511 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003512 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003513 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003514 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003515 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003516 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003517 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003518 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003519 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003520 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003521 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003522 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3523 // the minimum track buffer size is normally twice the number of frames necessary
3524 // to fill one buffer and the resampler should not leave more than one buffer worth
3525 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003526 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003527 }
3528 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003529 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 !track->isPaused() && !track->isTerminated())
3531 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003532 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533
3534 mixedTracks++;
3535
3536 // track->mainBuffer() != mMixBuffer means there is an effect chain
3537 // connected to the track
3538 chain.clear();
3539 if (track->mainBuffer() != mMixBuffer) {
3540 chain = getEffectChain_l(track->sessionId());
3541 // Delegate volume control to effect in track effect chain if needed
3542 if (chain != 0) {
3543 tracksWithEffect++;
3544 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003545 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003546 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 }
3548 }
3549
3550
3551 int param = AudioMixer::VOLUME;
3552 if (track->mFillingUpStatus == Track::FS_FILLED) {
3553 // no ramp for the first volume setting
3554 track->mFillingUpStatus = Track::FS_ACTIVE;
3555 if (track->mState == TrackBase::RESUMING) {
3556 track->mState = TrackBase::ACTIVE;
3557 param = AudioMixer::RAMP_VOLUME;
3558 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003559 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 } else if (cblk->server != 0) {
3561 // If the track is stopped before the first frame was mixed,
3562 // do not apply ramp
3563 param = AudioMixer::RAMP_VOLUME;
3564 }
3565
3566 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003567 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003568 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003569 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003570 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 if (track->isPausing()) {
3572 track->setPaused();
3573 }
3574 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003575
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003577 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003579 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003580 vl = vlr & 0xFFFF;
3581 vr = vlr >> 16;
3582 // track volumes come from shared memory, so can't be trusted and must be clamped
3583 if (vl > MAX_GAIN_INT) {
3584 ALOGV("Track left volume out of range: %04X", vl);
3585 vl = MAX_GAIN_INT;
3586 }
3587 if (vr > MAX_GAIN_INT) {
3588 ALOGV("Track right volume out of range: %04X", vr);
3589 vr = MAX_GAIN_INT;
3590 }
3591 // now apply the master volume and stream type volume
3592 vl = (uint32_t)(v * vl) << 12;
3593 vr = (uint32_t)(v * vr) << 12;
3594 // assuming master volume and stream type volume each go up to 1.0,
3595 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596
Glenn Kasten05632a52012-01-03 14:22:33 -08003597 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3598 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003599 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003600 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003601 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003602 }
3603 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003605 // Delegate volume control to effect in track effect chain if needed
3606 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3607 // Do not ramp volume if volume is controlled by effect
3608 param = AudioMixer::VOLUME;
3609 track->mHasVolumeController = true;
3610 } else {
3611 // force no volume ramp when volume controller was just disabled or removed
3612 // from effect chain to avoid volume spike
3613 if (track->mHasVolumeController) {
3614 param = AudioMixer::VOLUME;
3615 }
3616 track->mHasVolumeController = false;
3617 }
3618
3619 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003620 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003621 vl = (vl + (1 << 11)) >> 12;
3622 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3623 vr = (vr + (1 << 11)) >> 12;
3624 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003625
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003626 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 -07003627
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003629 mAudioMixer->setBufferProvider(name, track);
3630 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003632 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3633 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3634 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003636 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 AudioMixer::TRACK,
3638 AudioMixer::FORMAT, (void *)track->format());
3639 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003640 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003642 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003644 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645 AudioMixer::RESAMPLE,
3646 AudioMixer::SAMPLE_RATE,
3647 (void *)(cblk->sampleRate));
3648 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003649 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650 AudioMixer::TRACK,
3651 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3652 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003653 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 AudioMixer::TRACK,
3655 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3656
3657 // reset retry count
3658 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003659
Eric Laurent27741442012-01-17 19:20:12 -08003660 // If one track is ready, set the mixer ready if:
3661 // - the mixer was not ready during previous round OR
3662 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003663 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003664 mixerStatus != MIXER_TRACKS_ENABLED) {
3665 mixerStatus = MIXER_TRACKS_READY;
3666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003668 // clear effect chain input buffer if an active track underruns to avoid sending
3669 // previous audio buffer again to effects
3670 chain = getEffectChain_l(track->sessionId());
3671 if (chain != 0) {
3672 chain->clearInputBuffer();
3673 }
3674
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003675 //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 -07003676 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003677 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678 // We have consumed all the buffers of this track.
3679 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003680 // TODO: use actual buffer filling status instead of latency when available from
3681 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003682 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003683 size_t framesWritten =
3684 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003685 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003686 if (track->isStopped()) {
3687 track->reset();
3688 }
Eric Laurenta011e352012-03-29 15:51:43 -07003689 tracksToRemove->add(track);
3690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003692 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 // No buffers for this track. Give it a few chances to
3694 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003695 if (--(track->mRetryCount) <= 0) {
3696 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003697 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003698 // indicate to client process that the track was disabled because of underrun;
3699 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003700 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003701 // If one track is not ready, mark the mixer also not ready if:
3702 // - the mixer was ready during previous round OR
3703 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003704 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003705 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706 mixerStatus = MIXER_TRACKS_ENABLED;
3707 }
3708 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003709 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 }
Glenn Kasten58912562012-04-03 10:45:00 -07003711
3712 } // local variable scope to avoid goto warning
3713track_is_ready: ;
3714
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 }
3716
Glenn Kasten288ed212012-04-25 17:52:27 -07003717 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003718 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003719 if (didModify) {
3720 state->mFastTracksGen++;
3721 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3722 if (kUseFastMixer == FastMixer_Dynamic &&
3723 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3724 state->mCommand = FastMixerState::COLD_IDLE;
3725 state->mColdFutexAddr = &mFastMixerFutex;
3726 state->mColdGen++;
3727 mFastMixerFutex = 0;
3728 if (kUseFastMixer == FastMixer_Dynamic) {
3729 mNormalSink = mOutputSink;
3730 }
3731 // If we go into cold idle, need to wait for acknowledgement
3732 // so that fast mixer stops doing I/O.
3733 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003734 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003735 }
3736 sq->end();
3737 }
3738 if (sq != NULL) {
3739 sq->end(didModify);
3740 sq->push(block);
3741 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003742#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003743 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3744 mAudioWatchdog->pause();
3745 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003746#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003747
3748 // Now perform the deferred reset on fast tracks that have stopped
3749 while (resetMask != 0) {
3750 size_t i = __builtin_ctz(resetMask);
3751 ALOG_ASSERT(i < count);
3752 resetMask &= ~(1 << i);
3753 sp<Track> t = mActiveTracks[i].promote();
3754 if (t == 0) continue;
3755 Track* track = t.get();
3756 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3757 track->reset();
3758 }
Glenn Kasten58912562012-04-03 10:45:00 -07003759
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 // remove all the tracks that need to be...
3761 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003762 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 for (size_t i=0 ; i<count ; i++) {
3764 const sp<Track>& track = tracksToRemove->itemAt(i);
3765 mActiveTracks.remove(track);
3766 if (track->mainBuffer() != mMixBuffer) {
3767 chain = getEffectChain_l(track->sessionId());
3768 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003769 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003770 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 }
3772 }
3773 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003774 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 }
3776 }
3777 }
3778
3779 // mix buffer must be cleared if all tracks are connected to an
3780 // effect chain as in this case the mixer will not write to
3781 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003782 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3783 // FIXME as a performance optimization, should remember previous zero status
3784 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785 }
3786
Glenn Kasten58912562012-04-03 10:45:00 -07003787 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003788 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003789 if (fastTracks > 0) {
3790 mixerStatus = MIXER_TRACKS_READY;
3791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 return mixerStatus;
3793}
3794
Glenn Kasten66fcab92012-02-24 14:59:21 -08003795/*
3796The derived values that are cached:
3797 - mixBufferSize from frame count * frame size
3798 - activeSleepTime from activeSleepTimeUs()
3799 - idleSleepTime from idleSleepTimeUs()
3800 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3801 - maxPeriod from frame count and sample rate (MIXER only)
3802
3803The parameters that affect these derived values are:
3804 - frame count
3805 - frame size
3806 - sample rate
3807 - device type: A2DP or not
3808 - device latency
3809 - format: PCM or not
3810 - active sleep time
3811 - idle sleep time
3812*/
3813
3814void AudioFlinger::PlaybackThread::cacheParameters_l()
3815{
Glenn Kasten58912562012-04-03 10:45:00 -07003816 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003817 activeSleepTime = activeSleepTimeUs();
3818 idleSleepTime = idleSleepTimeUs();
3819}
3820
Eric Laurent22167852012-06-20 12:26:32 -07003821void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822{
Steve Block3856b092011-10-20 11:56:00 +01003823 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003824 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003826
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827 size_t size = mTracks.size();
3828 for (size_t i = 0; i < size; i++) {
3829 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003830 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003831 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 }
3834 }
3835}
3836
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003838int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003840 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841}
3842
3843// deleteTrackName_l() must be called with ThreadBase::mLock held
3844void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3845{
Steve Block3856b092011-10-20 11:56:00 +01003846 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 mAudioMixer->deleteTrackName(name);
3848}
3849
3850// checkForNewParameters_l() must be called with ThreadBase::mLock held
3851bool AudioFlinger::MixerThread::checkForNewParameters_l()
3852{
Glenn Kasten58912562012-04-03 10:45:00 -07003853 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3854 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855 bool reconfig = false;
3856
3857 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003858
3859 if (mFastMixer != NULL) {
3860 FastMixerStateQueue *sq = mFastMixer->sq();
3861 FastMixerState *state = sq->begin();
3862 if (!(state->mCommand & FastMixerState::IDLE)) {
3863 previousCommand = state->mCommand;
3864 state->mCommand = FastMixerState::HOT_IDLE;
3865 sq->end();
3866 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3867 } else {
3868 sq->end(false /*didModify*/);
3869 }
3870 }
3871
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 status_t status = NO_ERROR;
3873 String8 keyValuePair = mNewParameters[0];
3874 AudioParameter param = AudioParameter(keyValuePair);
3875 int value;
3876
3877 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3878 reconfig = true;
3879 }
3880 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003881 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882 status = BAD_VALUE;
3883 } else {
3884 reconfig = true;
3885 }
3886 }
3887 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003888 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 status = BAD_VALUE;
3890 } else {
3891 reconfig = true;
3892 }
3893 }
3894 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3895 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003896 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 // if frame count is changed after track creation
3898 if (!mTracks.isEmpty()) {
3899 status = INVALID_OPERATION;
3900 } else {
3901 reconfig = true;
3902 }
3903 }
3904 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003905#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003906 // when changing the audio output device, call addBatteryData to notify
3907 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003908 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003909 uint32_t params = 0;
3910 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003911 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003912 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3913 }
3914
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003915 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003916 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003917 // check if any other device (except speaker) is on
3918 if (value & deviceWithoutSpeaker ) {
3919 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3920 }
3921
3922 if (params != 0) {
3923 addBatteryData(params);
3924 }
3925 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003926#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003927
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 // forward device change to effects that have requested to be
3929 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003930 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003932 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003933 }
3934 }
3935
3936 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003937 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003938 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003940 mOutput->stream->common.standby(&mOutput->stream->common);
3941 mStandby = true;
3942 mBytesWritten = 0;
3943 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003944 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 }
3946 if (status == NO_ERROR && reconfig) {
3947 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003948 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3949 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003951 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003952 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003953 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 if (name < 0) break;
3955 mTracks[i]->mName = name;
3956 // limit track sample rate to 2 x new output sample rate
3957 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3958 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3959 }
3960 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003961 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 }
3963 }
3964
3965 mNewParameters.removeAt(0);
3966
3967 mParamStatus = status;
3968 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003969 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3970 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003971 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 }
Glenn Kasten58912562012-04-03 10:45:00 -07003973
3974 if (!(previousCommand & FastMixerState::IDLE)) {
3975 ALOG_ASSERT(mFastMixer != NULL);
3976 FastMixerStateQueue *sq = mFastMixer->sq();
3977 FastMixerState *state = sq->begin();
3978 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3979 state->mCommand = previousCommand;
3980 sq->end();
3981 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3982 }
3983
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 return reconfig;
3985}
3986
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003987void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988{
3989 const size_t SIZE = 256;
3990 char buffer[SIZE];
3991 String8 result;
3992
3993 PlaybackThread::dumpInternals(fd, args);
3994
3995 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3996 result.append(buffer);
3997 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003998
3999 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4000 FastMixerDumpState copy = mFastMixerDumpState;
4001 copy.dump(fd);
4002
Glenn Kasten39993082012-05-31 13:40:27 -07004003#ifdef STATE_QUEUE_DUMP
4004 // Similar for state queue
4005 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4006 observerCopy.dump(fd);
4007 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4008 mutatorCopy.dump(fd);
4009#endif
4010
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004011 // Write the tee output to a .wav file
4012 NBAIO_Source *teeSource = mTeeSource.get();
4013 if (teeSource != NULL) {
4014 char teePath[64];
4015 struct timeval tv;
4016 gettimeofday(&tv, NULL);
4017 struct tm tm;
4018 localtime_r(&tv.tv_sec, &tm);
4019 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
4020 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
4021 if (teeFd >= 0) {
4022 char wavHeader[44];
4023 memcpy(wavHeader,
4024 "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",
4025 sizeof(wavHeader));
4026 NBAIO_Format format = teeSource->format();
4027 unsigned channelCount = Format_channelCount(format);
4028 ALOG_ASSERT(channelCount <= FCC_2);
4029 unsigned sampleRate = Format_sampleRate(format);
4030 wavHeader[22] = channelCount; // number of channels
4031 wavHeader[24] = sampleRate; // sample rate
4032 wavHeader[25] = sampleRate >> 8;
4033 wavHeader[32] = channelCount * 2; // block alignment
4034 write(teeFd, wavHeader, sizeof(wavHeader));
4035 size_t total = 0;
4036 bool firstRead = true;
4037 for (;;) {
4038#define TEE_SINK_READ 1024
4039 short buffer[TEE_SINK_READ * FCC_2];
4040 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07004041 ssize_t actual = teeSource->read(buffer, count,
4042 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004043 bool wasFirstRead = firstRead;
4044 firstRead = false;
4045 if (actual <= 0) {
4046 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
4047 continue;
4048 }
4049 break;
4050 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07004051 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07004052 write(teeFd, buffer, actual * channelCount * sizeof(short));
4053 total += actual;
4054 }
4055 lseek(teeFd, (off_t) 4, SEEK_SET);
4056 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
4057 write(teeFd, &temp, sizeof(temp));
4058 lseek(teeFd, (off_t) 40, SEEK_SET);
4059 temp = total * channelCount * sizeof(short);
4060 write(teeFd, &temp, sizeof(temp));
4061 close(teeFd);
4062 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
4063 } else {
4064 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
4065 }
4066 }
4067
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004068#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07004069 if (mAudioWatchdog != 0) {
4070 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4071 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4072 wdCopy.dump(fd);
4073 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07004074#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075}
4076
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004077uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078{
Glenn Kasten58912562012-04-03 10:45:00 -07004079 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080}
4081
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004082uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004083{
Glenn Kasten58912562012-04-03 10:45:00 -07004084 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004085}
4086
Glenn Kasten66fcab92012-02-24 14:59:21 -08004087void AudioFlinger::MixerThread::cacheParameters_l()
4088{
4089 PlaybackThread::cacheParameters_l();
4090
4091 // FIXME: Relaxed timing because of a certain device that can't meet latency
4092 // Should be reduced to 2x after the vendor fixes the driver issue
4093 // increase threshold again due to low power audio mode. The way this warning
4094 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07004095 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08004096}
4097
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004099AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07004100 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004101 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004102 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104}
4105
4106AudioFlinger::DirectOutputThread::~DirectOutputThread()
4107{
4108}
4109
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004110AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4111 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08004112)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004114 sp<Track> trackToRemove;
4115
Glenn Kastenfec279f2012-03-08 07:47:15 -08004116 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117
Glenn Kasten952eeb22012-03-06 11:30:57 -08004118 // find out which tracks need to be processed
4119 if (mActiveTracks.size() != 0) {
4120 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08004121 // The track died recently
4122 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123
Glenn Kasten952eeb22012-03-06 11:30:57 -08004124 Track* const track = t.get();
4125 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126
Glenn Kasten952eeb22012-03-06 11:30:57 -08004127 // The first time a track is added we wait
4128 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07004129 uint32_t minFrames;
4130 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
4131 minFrames = mNormalFrameCount;
4132 } else {
4133 minFrames = 1;
4134 }
4135 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08004136 !track->isPaused() && !track->isTerminated())
4137 {
4138 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139
Glenn Kasten952eeb22012-03-06 11:30:57 -08004140 if (track->mFillingUpStatus == Track::FS_FILLED) {
4141 track->mFillingUpStatus = Track::FS_ACTIVE;
4142 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004143 if (track->mState == TrackBase::RESUMING) {
4144 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004145 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004146 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004147
Glenn Kasten952eeb22012-03-06 11:30:57 -08004148 // compute volume for this track
4149 float left, right;
4150 if (track->isMuted() || mMasterMute || track->isPausing() ||
4151 mStreamTypes[track->streamType()].mute) {
4152 left = right = 0;
4153 if (track->isPausing()) {
4154 track->setPaused();
4155 }
4156 } else {
4157 float typeVolume = mStreamTypes[track->streamType()].volume;
4158 float v = mMasterVolume * typeVolume;
4159 uint32_t vlr = cblk->getVolumeLR();
4160 float v_clamped = v * (vlr & 0xFFFF);
4161 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4162 left = v_clamped/MAX_GAIN;
4163 v_clamped = v * (vlr >> 16);
4164 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
4165 right = v_clamped/MAX_GAIN;
4166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167
Glenn Kasten952eeb22012-03-06 11:30:57 -08004168 if (left != mLeftVolFloat || right != mRightVolFloat) {
4169 mLeftVolFloat = left;
4170 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171
Glenn Kasten952eeb22012-03-06 11:30:57 -08004172 // Convert volumes from float to 8.24
4173 uint32_t vl = (uint32_t)(left * (1 << 24));
4174 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175
Glenn Kasten952eeb22012-03-06 11:30:57 -08004176 // Delegate volume control to effect in track effect chain if needed
4177 // only one effect chain can be present on DirectOutputThread, so if
4178 // there is one, the track is connected to it
4179 if (!mEffectChains.isEmpty()) {
4180 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07004181 mEffectChains[0]->setVolume_l(&vl, &vr);
4182 left = (float)vl / (1 << 24);
4183 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004184 }
Eric Laurent67c0a582012-05-01 19:31:12 -07004185 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004186 }
4187
4188 // reset retry count
4189 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004190 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08004191 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004192 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07004193 // clear effect chain input buffer if an active track underruns to avoid sending
4194 // previous audio buffer again to effects
4195 if (!mEffectChains.isEmpty()) {
4196 mEffectChains[0]->clearInputBuffer();
4197 }
4198
Glenn Kasten952eeb22012-03-06 11:30:57 -08004199 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07004200 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07004201 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004202 // We have consumed all the buffers of this track.
4203 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07004204 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07004205 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07004206 size_t framesWritten =
4207 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07004208 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07004209 if (track->isStopped()) {
4210 track->reset();
4211 }
Eric Laurenta011e352012-03-29 15:51:43 -07004212 trackToRemove = track;
4213 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004214 } else {
4215 // No buffers for this track. Give it a few chances to
4216 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07004217 if (--(track->mRetryCount) <= 0) {
4218 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08004219 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004221 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 }
4223 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08004224 }
4225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004227 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08004228 // remove all the tracks that need to be...
4229 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08004230 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004231 mActiveTracks.remove(trackToRemove);
4232 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004233 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08004234 trackToRemove->sessionId());
4235 mEffectChains[0]->decActiveTrackCnt();
4236 }
4237 if (trackToRemove->isTerminated()) {
4238 removeTrack_l(trackToRemove);
4239 }
4240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
Glenn Kastenfec279f2012-03-08 07:47:15 -08004242 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004243}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
Glenn Kasten000f0e32012-03-01 17:10:56 -08004245void AudioFlinger::DirectOutputThread::threadLoop_mix()
4246{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004247 AudioBufferProvider::Buffer buffer;
4248 size_t frameCount = mFrameCount;
4249 int8_t *curBuf = (int8_t *)mMixBuffer;
4250 // output audio to hardware
4251 while (frameCount) {
4252 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004253 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004254 if (CC_UNLIKELY(buffer.raw == NULL)) {
4255 memset(curBuf, 0, frameCount * mFrameSize);
4256 break;
4257 }
4258 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4259 frameCount -= buffer.frameCount;
4260 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004261 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004262 }
4263 sleepTime = 0;
4264 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08004265 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08004266
Glenn Kasten000f0e32012-03-01 17:10:56 -08004267}
4268
4269void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4270{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004271 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004272 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004273 sleepTime = activeSleepTime;
4274 } else {
4275 sleepTime = idleSleepTime;
4276 }
4277 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07004278 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08004279 sleepTime = 0;
4280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281}
4282
4283// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004284int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
4285 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286{
4287 return 0;
4288}
4289
4290// deleteTrackName_l() must be called with ThreadBase::mLock held
4291void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
4292{
4293}
4294
4295// checkForNewParameters_l() must be called with ThreadBase::mLock held
4296bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
4297{
4298 bool reconfig = false;
4299
4300 while (!mNewParameters.isEmpty()) {
4301 status_t status = NO_ERROR;
4302 String8 keyValuePair = mNewParameters[0];
4303 AudioParameter param = AudioParameter(keyValuePair);
4304 int value;
4305
4306 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4307 // do not accept frame count changes if tracks are open as the track buffer
4308 // size depends on frame count and correct behavior would not be garantied
4309 // if frame count is changed after track creation
4310 if (!mTracks.isEmpty()) {
4311 status = INVALID_OPERATION;
4312 } else {
4313 reconfig = true;
4314 }
4315 }
4316 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004317 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004318 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004320 mOutput->stream->common.standby(&mOutput->stream->common);
4321 mStandby = true;
4322 mBytesWritten = 0;
4323 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07004324 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 }
4326 if (status == NO_ERROR && reconfig) {
4327 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07004328 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004329 }
4330 }
4331
4332 mNewParameters.removeAt(0);
4333
4334 mParamStatus = status;
4335 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004336 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4337 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004338 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339 }
4340 return reconfig;
4341}
4342
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004343uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344{
4345 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004346 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004347 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 } else {
4349 time = 10000;
4350 }
4351 return time;
4352}
4353
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004354uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355{
4356 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004357 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004358 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 } else {
4360 time = 10000;
4361 }
4362 return time;
4363}
4364
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004365uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004366{
4367 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004368 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004369 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4370 } else {
4371 time = 10000;
4372 }
4373 return time;
4374}
4375
Glenn Kasten66fcab92012-02-24 14:59:21 -08004376void AudioFlinger::DirectOutputThread::cacheParameters_l()
4377{
4378 PlaybackThread::cacheParameters_l();
4379
4380 // use shorter standby delay as on normal output to release
4381 // hardware resources as soon as possible
4382 standbyDelay = microseconds(activeSleepTime*2);
4383}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004384
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385// ----------------------------------------------------------------------------
4386
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004387AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004388 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07004389 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004390 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 addOutputTrack(mainThread);
4393}
4394
4395AudioFlinger::DuplicatingThread::~DuplicatingThread()
4396{
4397 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4398 mOutputTracks[i]->destroy();
4399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400}
4401
Glenn Kasten000f0e32012-03-01 17:10:56 -08004402void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004404 // mix buffers...
4405 if (outputsReady(outputTracks)) {
4406 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4407 } else {
4408 memset(mMixBuffer, 0, mixBufferSize);
4409 }
4410 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004411 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004412 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004413}
4414
4415void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4416{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004417 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004418 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004419 sleepTime = activeSleepTime;
4420 } else {
4421 sleepTime = idleSleepTime;
4422 }
4423 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004424 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4425 writeFrames = mNormalFrameCount;
4426 memset(mMixBuffer, 0, mixBufferSize);
4427 } else {
4428 // flush remaining overflow buffers in output tracks
4429 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004430 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004431 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004432 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004433}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434
Glenn Kasten000f0e32012-03-01 17:10:56 -08004435void AudioFlinger::DuplicatingThread::threadLoop_write()
4436{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004437 for (size_t i = 0; i < outputTracks.size(); i++) {
4438 outputTracks[i]->write(mMixBuffer, writeFrames);
4439 }
4440 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004441}
Glenn Kasten688a6402012-02-29 07:57:06 -08004442
Glenn Kasten000f0e32012-03-01 17:10:56 -08004443void AudioFlinger::DuplicatingThread::threadLoop_standby()
4444{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004445 // DuplicatingThread implements standby by stopping all tracks
4446 for (size_t i = 0; i < outputTracks.size(); i++) {
4447 outputTracks[i]->stop();
4448 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449}
4450
Glenn Kastenfa26a852012-03-06 11:28:04 -08004451void AudioFlinger::DuplicatingThread::saveOutputTracks()
4452{
4453 outputTracks = mOutputTracks;
4454}
4455
4456void AudioFlinger::DuplicatingThread::clearOutputTracks()
4457{
4458 outputTracks.clear();
4459}
4460
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4462{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004463 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004464 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004465 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004466 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467 this,
4468 mSampleRate,
4469 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004470 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 frameCount);
4472 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004473 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004475 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004476 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 }
4478}
4479
4480void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4481{
4482 Mutex::Autolock _l(mLock);
4483 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004484 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 mOutputTracks[i]->destroy();
4486 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004487 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488 return;
4489 }
4490 }
Steve Block3856b092011-10-20 11:56:00 +01004491 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492}
4493
Glenn Kasten438b0362012-03-06 11:24:48 -08004494// caller must hold mLock
4495void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496{
4497 mWaitTimeMs = UINT_MAX;
4498 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4499 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004500 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4502 if (waitTimeMs < mWaitTimeMs) {
4503 mWaitTimeMs = waitTimeMs;
4504 }
4505 }
4506 }
4507}
4508
4509
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004510bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511{
4512 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004513 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004515 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 return false;
4517 }
4518 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004519 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004521 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 return false;
4523 }
4524 }
4525 return true;
4526}
4527
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004528uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004529{
4530 return (mWaitTimeMs * 1000) / 2;
4531}
4532
Glenn Kasten66fcab92012-02-24 14:59:21 -08004533void AudioFlinger::DuplicatingThread::cacheParameters_l()
4534{
4535 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4536 updateWaitTime_l();
4537
4538 MixerThread::cacheParameters_l();
4539}
4540
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541// ----------------------------------------------------------------------------
4542
4543// TrackBase constructor must be called with AudioFlinger::mLock held
4544AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004545 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 const sp<Client>& client,
4547 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004548 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004549 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 const sp<IMemory>& sharedBuffer,
4552 int sessionId)
4553 : RefBase(),
4554 mThread(thread),
4555 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004556 mCblk(NULL),
4557 // mBuffer
4558 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 mFrameCount(0),
4560 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004561 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004563 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004565 // mChannelCount
4566 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567{
Steve Block3856b092011-10-20 11:56:00 +01004568 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569
Steve Blockb8a80522011-12-20 16:23:08 +00004570 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004571 size_t size = sizeof(audio_track_cblk_t);
4572 uint8_t channelCount = popcount(channelMask);
4573 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4574 if (sharedBuffer == 0) {
4575 size += bufferSize;
4576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004577
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004578 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579 mCblkMemory = client->heap()->allocate(size);
4580 if (mCblkMemory != 0) {
4581 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004582 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 new(mCblk) audio_track_cblk_t();
4584 // clear all buffers
4585 mCblk->frameCount = frameCount;
4586 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004587// uncomment the following lines to quickly test 32-bit wraparound
4588// mCblk->user = 0xffff0000;
4589// mCblk->server = 0xffff0000;
4590// mCblk->userBase = 0xffff0000;
4591// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004592 mChannelCount = channelCount;
4593 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 if (sharedBuffer == 0) {
4595 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4596 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4597 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004598 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 mCblk->flags = CBLK_UNDERRUN_ON;
4600 } else {
4601 mBuffer = sharedBuffer->pointer();
4602 }
4603 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4604 }
4605 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004606 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 client->heap()->dump("AudioTrack");
4608 return;
4609 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004610 } else {
4611 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004612 // construct the shared structure in-place.
4613 new(mCblk) audio_track_cblk_t();
4614 // clear all buffers
4615 mCblk->frameCount = frameCount;
4616 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004617// uncomment the following lines to quickly test 32-bit wraparound
4618// mCblk->user = 0xffff0000;
4619// mCblk->server = 0xffff0000;
4620// mCblk->userBase = 0xffff0000;
4621// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004622 mChannelCount = channelCount;
4623 mChannelMask = channelMask;
4624 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4625 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4626 // Force underrun condition to avoid false underrun callback until first data is
4627 // written to buffer (other flags are cleared)
4628 mCblk->flags = CBLK_UNDERRUN_ON;
4629 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631}
4632
4633AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4634{
Glenn Kastena0d68332012-01-27 16:47:15 -08004635 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004636 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004638 } else {
4639 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 }
4641 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004642 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004643 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004644 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004646 // If the client's reference count drops to zero, the associated destructor
4647 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4648 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 mClient.clear();
4650 }
4651}
4652
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004653// AudioBufferProvider interface
4654// getNextBuffer() = 0;
4655// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4657{
Glenn Kastene0feee32011-12-13 11:53:26 -08004658 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004660 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004661 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 buffer->frameCount = 0;
4663}
4664
4665bool AudioFlinger::ThreadBase::TrackBase::step() {
4666 bool result;
4667 audio_track_cblk_t* cblk = this->cblk();
4668
4669 result = cblk->stepServer(mFrameCount);
4670 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004671 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004672 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 }
4674 return result;
4675}
4676
4677void AudioFlinger::ThreadBase::TrackBase::reset() {
4678 audio_track_cblk_t* cblk = this->cblk();
4679
4680 cblk->user = 0;
4681 cblk->server = 0;
4682 cblk->userBase = 0;
4683 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004684 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004685 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686}
4687
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4689 return (int)mCblk->sampleRate;
4690}
4691
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4693 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004694 size_t frameSize = cblk->frameSize;
4695 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4696 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697
4698 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004699 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4700 "TrackBase::getBuffer buffer out of range:\n"
4701 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4702 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004703 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004704 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705
4706 return bufferStart;
4707}
4708
Eric Laurenta011e352012-03-29 15:51:43 -07004709status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4710{
4711 mSyncEvents.add(event);
4712 return NO_ERROR;
4713}
4714
Mathias Agopian65ab4712010-07-14 17:59:35 -07004715// ----------------------------------------------------------------------------
4716
4717// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4718AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004719 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004720 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004721 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004722 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004723 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004724 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004725 int frameCount,
4726 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004727 int sessionId,
4728 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004729 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004730 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004731 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004732 // mRetryCount initialized later when needed
4733 mSharedBuffer(sharedBuffer),
4734 mStreamType(streamType),
4735 mName(-1), // see note below
4736 mMainBuffer(thread->mixBuffer()),
4737 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004738 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004739 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004740 mFlags(flags),
4741 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004742 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004743 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744{
4745 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4747 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004748 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004749 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004750 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004751 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004752 if (mName < 0) {
4753 ALOGE("no more track names available");
4754 return;
4755 }
4756 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004757 if (flags & IAudioFlinger::TRACK_FAST) {
4758 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4759 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4760 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004761 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004762 // FIXME This is too eager. We allocate a fast track index before the
4763 // fast track becomes active. Since fast tracks are a scarce resource,
4764 // this means we are potentially denying other more important fast tracks from
4765 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004766 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004767 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004768 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004769 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004770 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004773 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774}
4775
4776AudioFlinger::PlaybackThread::Track::~Track()
4777{
Steve Block3856b092011-10-20 11:56:00 +01004778 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779}
4780
4781void AudioFlinger::PlaybackThread::Track::destroy()
4782{
4783 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4784 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004785 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786 // we must acquire a strong reference on this Track before locking mLock
4787 // here so that the destructor is called only when exiting this function.
4788 // On the other hand, as long as Track::destroy() is only called by
4789 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4790 // this Track with its member mTrack.
4791 sp<Track> keep(this);
4792 { // scope for mLock
4793 sp<ThreadBase> thread = mThread.promote();
4794 if (thread != 0) {
4795 if (!isOutputTrack()) {
4796 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004797 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004798
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004799#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004800 // to track the speaker usage
4801 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004802#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803 }
4804 AudioSystem::releaseOutput(thread->id());
4805 }
4806 Mutex::Autolock _l(thread->mLock);
4807 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4808 playbackThread->destroyTrack_l(this);
4809 }
4810 }
4811}
4812
Glenn Kasten288ed212012-04-25 17:52:27 -07004813/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4814{
Glenn Kastene213c862012-04-25 13:46:15 -07004815 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 -07004816 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004817}
4818
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4820{
Glenn Kasten83d86532012-01-17 14:39:34 -08004821 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004822 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004823 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004824 } else {
4825 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4826 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004827 track_state state = mState;
4828 char stateChar;
4829 switch (state) {
4830 case IDLE:
4831 stateChar = 'I';
4832 break;
4833 case TERMINATED:
4834 stateChar = 'T';
4835 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004836 case STOPPING_1:
4837 stateChar = 's';
4838 break;
4839 case STOPPING_2:
4840 stateChar = '5';
4841 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004842 case STOPPED:
4843 stateChar = 'S';
4844 break;
4845 case RESUMING:
4846 stateChar = 'R';
4847 break;
4848 case ACTIVE:
4849 stateChar = 'A';
4850 break;
4851 case PAUSING:
4852 stateChar = 'p';
4853 break;
4854 case PAUSED:
4855 stateChar = 'P';
4856 break;
Eric Laurent29864602012-05-08 18:57:51 -07004857 case FLUSHED:
4858 stateChar = 'F';
4859 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004860 default:
4861 stateChar = '?';
4862 break;
4863 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004864 char nowInUnderrun;
4865 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4866 case UNDERRUN_FULL:
4867 nowInUnderrun = ' ';
4868 break;
4869 case UNDERRUN_PARTIAL:
4870 nowInUnderrun = '<';
4871 break;
4872 case UNDERRUN_EMPTY:
4873 nowInUnderrun = '*';
4874 break;
4875 default:
4876 nowInUnderrun = '?';
4877 break;
4878 }
Glenn Kastene213c862012-04-25 13:46:15 -07004879 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4880 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004881 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004882 mStreamType,
4883 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004884 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 mSessionId,
4886 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004887 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004888 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 mMute,
4890 mFillingUpStatus,
4891 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004892 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4893 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 mCblk->server,
4895 mCblk->user,
4896 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004897 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004898 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004899 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004900 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004901}
4902
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004903// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004904status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004905 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004906{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004907 audio_track_cblk_t* cblk = this->cblk();
4908 uint32_t framesReady;
4909 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004911 // Check if last stepServer failed, try to step now
4912 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004913 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4914 // Since the fast mixer is higher priority than client callback thread,
4915 // it does not result in priority inversion for client.
4916 // But a non-blocking solution would be preferable to avoid
4917 // fast mixer being unable to tryLock(), and
4918 // to avoid the extra context switches if the client wakes up,
4919 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004920 if (!step()) goto getNextBuffer_exit;
4921 ALOGV("stepServer recovered");
4922 mStepServerFailed = false;
4923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924
Glenn Kasten288ed212012-04-25 17:52:27 -07004925 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004926 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004928 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 uint32_t s = cblk->server;
4930 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4931
4932 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4933 if (framesReq > framesReady) {
4934 framesReq = framesReady;
4935 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004936 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937 framesReq = bufferEnd - s;
4938 }
4939
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004940 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004941 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944
4945getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004946 buffer->raw = NULL;
4947 buffer->frameCount = 0;
4948 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4949 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950}
4951
Glenn Kasten288ed212012-04-25 17:52:27 -07004952// Note that framesReady() takes a mutex on the control block using tryLock().
4953// This could result in priority inversion if framesReady() is called by the normal mixer,
4954// as the normal mixer thread runs at lower
4955// priority than the client's callback thread: there is a short window within framesReady()
4956// during which the normal mixer could be preempted, and the client callback would block.
4957// Another problem can occur if framesReady() is called by the fast mixer:
4958// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4959// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4960size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004961 return mCblk->framesReady();
4962}
4963
Glenn Kasten288ed212012-04-25 17:52:27 -07004964// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004966 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004967
John Grossman4ff14ba2012-02-08 16:37:41 -08004968 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4970 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004971 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 return true;
4973 }
4974 return false;
4975}
4976
Glenn Kasten3acbd052012-02-28 10:39:56 -08004977status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004978 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979{
4980 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004981 ALOGV("start(%d), calling pid %d session %d",
4982 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004983
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984 sp<ThreadBase> thread = mThread.promote();
4985 if (thread != 0) {
4986 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004987 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 // here the track could be either new, or restarted
4989 // in both cases "unstop" the track
4990 if (mState == PAUSED) {
4991 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004992 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 } else {
4994 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004995 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 }
4997
4998 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4999 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005000 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005002
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005003#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005004 // to track the speaker usage
5005 if (status == NO_ERROR) {
5006 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
5007 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005008#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 }
5010 if (status == NO_ERROR) {
5011 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5012 playbackThread->addTrack_l(this);
5013 } else {
5014 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07005015 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016 }
5017 } else {
5018 status = BAD_VALUE;
5019 }
5020 return status;
5021}
5022
5023void AudioFlinger::PlaybackThread::Track::stop()
5024{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005025 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 sp<ThreadBase> thread = mThread.promote();
5027 if (thread != 0) {
5028 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08005029 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07005030 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 // If the track is not active (PAUSED and buffers full), flush buffers
5032 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5033 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5034 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07005035 mState = STOPPED;
5036 } else if (!isFastTrack()) {
5037 mState = STOPPED;
5038 } else {
5039 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
5040 // and then to STOPPED and reset() when presentation is complete
5041 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07005043 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 }
5045 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
5046 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005047 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005049
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005050#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005051 // to track the speaker usage
5052 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005053#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005054 }
5055 }
5056}
5057
5058void AudioFlinger::PlaybackThread::Track::pause()
5059{
Glenn Kasten23d82a92012-02-03 11:10:00 -08005060 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 sp<ThreadBase> thread = mThread.promote();
5062 if (thread != 0) {
5063 Mutex::Autolock _l(thread->mLock);
5064 if (mState == ACTIVE || mState == RESUMING) {
5065 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01005066 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 if (!isOutputTrack()) {
5068 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08005069 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08005071
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005072#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08005073 // to track the speaker usage
5074 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07005075#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 }
5077 }
5078 }
5079}
5080
5081void AudioFlinger::PlaybackThread::Track::flush()
5082{
Steve Block3856b092011-10-20 11:56:00 +01005083 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 sp<ThreadBase> thread = mThread.promote();
5085 if (thread != 0) {
5086 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07005087 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kastend9833642012-11-15 14:13:16 -08005088 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089 return;
5090 }
5091 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07005092 // FLUSHED state
5093 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07005094 // do not reset the track if it is still in the process of being stopped or paused.
5095 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07005096 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07005097 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07005098 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5099 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
5100 reset();
5101 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 }
5103}
5104
5105void AudioFlinger::PlaybackThread::Track::reset()
5106{
5107 // Do not reset twice to avoid discarding data written just after a flush and before
5108 // the audioflinger thread detects the track is stopped.
5109 if (!mResetDone) {
5110 TrackBase::reset();
5111 // Force underrun condition to avoid false underrun callback until first data is
5112 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07005113 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
5114 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005115 mFillingUpStatus = FS_FILLING;
5116 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07005117 if (mState == FLUSHED) {
5118 mState = IDLE;
5119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 }
5121}
5122
5123void AudioFlinger::PlaybackThread::Track::mute(bool muted)
5124{
5125 mMute = muted;
5126}
5127
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
5129{
5130 status_t status = DEAD_OBJECT;
5131 sp<ThreadBase> thread = mThread.promote();
5132 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005133 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07005134 sp<AudioFlinger> af = mClient->audioFlinger();
5135
5136 Mutex::Autolock _l(af->mLock);
5137
5138 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07005139
Eric Laurent109347d2012-07-02 12:31:03 -07005140 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07005141 Mutex::Autolock _dl(playbackThread->mLock);
5142 Mutex::Autolock _sl(srcThread->mLock);
5143 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5144 if (chain == 0) {
5145 return INVALID_OPERATION;
5146 }
5147
5148 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
5149 if (effect == 0) {
5150 return INVALID_OPERATION;
5151 }
5152 srcThread->removeEffect_l(effect);
5153 playbackThread->addEffect_l(effect);
5154 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5155 if (effect->state() == EffectModule::ACTIVE ||
5156 effect->state() == EffectModule::STOPPING) {
5157 effect->start();
5158 }
5159
5160 sp<EffectChain> dstChain = effect->chain().promote();
5161 if (dstChain == 0) {
5162 srcThread->addEffect_l(effect);
5163 return INVALID_OPERATION;
5164 }
5165 AudioSystem::unregisterEffect(effect->id());
5166 AudioSystem::registerEffect(&effect->desc(),
5167 srcThread->id(),
5168 dstChain->strategy(),
5169 AUDIO_SESSION_OUTPUT_MIX,
5170 effect->id());
5171 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005172 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 }
5174 return status;
5175}
5176
5177void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
5178{
5179 mAuxEffectId = EffectId;
5180 mAuxBuffer = buffer;
5181}
5182
Eric Laurenta011e352012-03-29 15:51:43 -07005183bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
5184 size_t audioHalFrames)
5185{
5186 // a track is considered presented when the total number of frames written to audio HAL
5187 // corresponds to the number of frames written when presentationComplete() is called for the
5188 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
5189 if (mPresentationCompleteFrames == 0) {
5190 mPresentationCompleteFrames = framesWritten + audioHalFrames;
5191 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
5192 mPresentationCompleteFrames, audioHalFrames);
5193 }
5194 if (framesWritten >= mPresentationCompleteFrames) {
5195 ALOGV("presentationComplete() session %d complete: framesWritten %d",
5196 mSessionId, framesWritten);
5197 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07005198 return true;
5199 }
5200 return false;
5201}
5202
5203void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
5204{
5205 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
5206 if (mSyncEvents[i]->type() == type) {
5207 mSyncEvents[i]->trigger();
5208 mSyncEvents.removeAt(i);
5209 i--;
5210 }
5211 }
5212}
5213
Glenn Kasten58912562012-04-03 10:45:00 -07005214// implement VolumeBufferProvider interface
5215
5216uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
5217{
5218 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
5219 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
5220 uint32_t vlr = mCblk->getVolumeLR();
5221 uint32_t vl = vlr & 0xFFFF;
5222 uint32_t vr = vlr >> 16;
5223 // track volumes come from shared memory, so can't be trusted and must be clamped
5224 if (vl > MAX_GAIN_INT) {
5225 vl = MAX_GAIN_INT;
5226 }
5227 if (vr > MAX_GAIN_INT) {
5228 vr = MAX_GAIN_INT;
5229 }
5230 // now apply the cached master volume and stream type volume;
5231 // this is trusted but lacks any synchronization or barrier so may be stale
5232 float v = mCachedVolume;
5233 vl *= v;
5234 vr *= v;
5235 // re-combine into U4.16
5236 vlr = (vr << 16) | (vl & 0xFFFF);
5237 // FIXME look at mute, pause, and stop flags
5238 return vlr;
5239}
Eric Laurenta011e352012-03-29 15:51:43 -07005240
Eric Laurent29864602012-05-08 18:57:51 -07005241status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
5242{
5243 if (mState == TERMINATED || mState == PAUSED ||
5244 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
5245 (mState == STOPPED)))) {
5246 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
5247 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
5248 event->cancel();
5249 return INVALID_OPERATION;
5250 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07005251 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07005252 return NO_ERROR;
5253}
5254
John Grossman4ff14ba2012-02-08 16:37:41 -08005255// timed audio tracks
5256
5257sp<AudioFlinger::PlaybackThread::TimedTrack>
5258AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005259 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005260 const sp<Client>& client,
5261 audio_stream_type_t streamType,
5262 uint32_t sampleRate,
5263 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005264 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 int frameCount,
5266 const sp<IMemory>& sharedBuffer,
5267 int sessionId) {
5268 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07005269 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08005270
Glenn Kastena0356762012-03-19 10:38:51 -07005271 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08005272 thread, client, streamType, sampleRate, format, channelMask, frameCount,
5273 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08005274}
5275
5276AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005277 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08005278 const sp<Client>& client,
5279 audio_stream_type_t streamType,
5280 uint32_t sampleRate,
5281 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005282 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08005283 int frameCount,
5284 const sp<IMemory>& sharedBuffer,
5285 int sessionId)
5286 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07005287 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07005288 mQueueHeadInFlight(false),
5289 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07005290 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08005291 mTimedSilenceBuffer(NULL),
5292 mTimedSilenceBufferSize(0),
5293 mTimedAudioOutputOnTime(false),
5294 mMediaTimeTransformValid(false)
5295{
5296 LocalClock lc;
5297 mLocalTimeFreq = lc.getLocalFreq();
5298
5299 mLocalTimeToSampleTransform.a_zero = 0;
5300 mLocalTimeToSampleTransform.b_zero = 0;
5301 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
5302 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
5303 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
5304 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07005305
5306 mMediaTimeToSampleTransform.a_zero = 0;
5307 mMediaTimeToSampleTransform.b_zero = 0;
5308 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
5309 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
5310 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
5311 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08005312}
5313
5314AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
5315 mClient->releaseTimedTrack();
5316 delete [] mTimedSilenceBuffer;
5317}
5318
5319status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
5320 size_t size, sp<IMemory>* buffer) {
5321
5322 Mutex::Autolock _l(mTimedBufferQueueLock);
5323
5324 trimTimedBufferQueue_l();
5325
5326 // lazily initialize the shared memory heap for timed buffers
5327 if (mTimedMemoryDealer == NULL) {
5328 const int kTimedBufferHeapSize = 512 << 10;
5329
5330 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
5331 "AudioFlingerTimed");
5332 if (mTimedMemoryDealer == NULL)
5333 return NO_MEMORY;
5334 }
5335
5336 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
5337 if (newBuffer == NULL) {
5338 newBuffer = mTimedMemoryDealer->allocate(size);
5339 if (newBuffer == NULL)
5340 return NO_MEMORY;
5341 }
5342
5343 *buffer = newBuffer;
5344 return NO_ERROR;
5345}
5346
5347// caller must hold mTimedBufferQueueLock
5348void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5349 int64_t mediaTimeNow;
5350 {
5351 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5352 if (!mMediaTimeTransformValid)
5353 return;
5354
5355 int64_t targetTimeNow;
5356 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5357 ? mCCHelper.getCommonTime(&targetTimeNow)
5358 : mCCHelper.getLocalTime(&targetTimeNow);
5359
5360 if (OK != res)
5361 return;
5362
5363 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5364 &mediaTimeNow)) {
5365 return;
5366 }
5367 }
5368
John Grossman1c345192012-03-27 14:00:17 -07005369 size_t trimEnd;
5370 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005371 int64_t bufEnd;
5372
John Grossmanc95cfbb2012-04-12 11:53:11 -07005373 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5374 // We have a next buffer. Just use its PTS as the PTS of the frame
5375 // following the last frame in this buffer. If the stream is sparse
5376 // (ie, there are deliberate gaps left in the stream which should be
5377 // filled with silence by the TimedAudioTrack), then this can result
5378 // in one extra buffer being left un-trimmed when it could have
5379 // been. In general, this is not typical, and we would rather
5380 // optimized away the TS calculation below for the more common case
5381 // where PTSes are contiguous.
5382 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5383 } else {
5384 // We have no next buffer. Compute the PTS of the frame following
5385 // the last frame in this buffer by computing the duration of of
5386 // this frame in media time units and adding it to the PTS of the
5387 // buffer.
5388 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5389 / mCblk->frameSize;
5390
5391 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5392 &bufEnd)) {
5393 ALOGE("Failed to convert frame count of %lld to media time"
5394 " duration" " (scale factor %d/%u) in %s",
5395 frameCount,
5396 mMediaTimeToSampleTransform.a_to_b_numer,
5397 mMediaTimeToSampleTransform.a_to_b_denom,
5398 __PRETTY_FUNCTION__);
5399 break;
5400 }
5401 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005402 }
John Grossman9fbdee12012-03-26 17:51:46 -07005403
5404 if (bufEnd > mediaTimeNow)
5405 break;
5406
5407 // Is the buffer we want to use in the middle of a mix operation right
5408 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5409 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005410 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005411 mTrimQueueHeadOnRelease = true;
5412 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005413 }
5414
John Grossman9fbdee12012-03-26 17:51:46 -07005415 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005416 if (trimStart < trimEnd) {
5417 // Update the bookkeeping for framesReady()
5418 for (size_t i = trimStart; i < trimEnd; ++i) {
5419 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5420 }
5421
5422 // Now actually remove the buffers from the queue.
5423 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005424 }
5425}
5426
John Grossman1c345192012-03-27 14:00:17 -07005427void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5428 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005429 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5430 "%s called (reason \"%s\"), but timed buffer queue has no"
5431 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005432
5433 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5434 mTimedBufferQueue.removeAt(0);
5435}
5436
5437void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5438 const TimedBuffer& buf,
5439 const char* logTag) {
5440 uint32_t bufBytes = buf.buffer()->size();
5441 uint32_t consumedAlready = buf.position();
5442
Eric Laurentb388e532012-04-14 13:32:48 -07005443 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005444 "Bad bookkeeping while updating frames pending. Timed buffer is"
5445 " only %u bytes long, but claims to have consumed %u"
5446 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005447 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005448
5449 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005450 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5451 "Bad bookkeeping while updating frames pending. Should have at"
5452 " least %u queued frames, but we think we have only %u. (update"
5453 " reason: \"%s\")",
5454 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005455
5456 mFramesPendingInQueue -= bufFrames;
5457}
5458
John Grossman4ff14ba2012-02-08 16:37:41 -08005459status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5460 const sp<IMemory>& buffer, int64_t pts) {
5461
5462 {
5463 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5464 if (!mMediaTimeTransformValid)
5465 return INVALID_OPERATION;
5466 }
5467
5468 Mutex::Autolock _l(mTimedBufferQueueLock);
5469
John Grossman1c345192012-03-27 14:00:17 -07005470 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5471 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005472 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5473
5474 return NO_ERROR;
5475}
5476
5477status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5478 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5479
John Grossman1c345192012-03-27 14:00:17 -07005480 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5481 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5482 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005483
5484 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5485 target == TimedAudioTrack::COMMON_TIME)) {
5486 return BAD_VALUE;
5487 }
5488
5489 Mutex::Autolock lock(mMediaTimeTransformLock);
5490 mMediaTimeTransform = xform;
5491 mMediaTimeTransformTarget = target;
5492 mMediaTimeTransformValid = true;
5493
5494 return NO_ERROR;
5495}
5496
5497#define min(a, b) ((a) < (b) ? (a) : (b))
5498
5499// implementation of getNextBuffer for tracks whose buffers have timestamps
5500status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5501 AudioBufferProvider::Buffer* buffer, int64_t pts)
5502{
5503 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005504 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005505 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005506 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005507 return INVALID_OPERATION;
5508 }
5509
John Grossman4ff14ba2012-02-08 16:37:41 -08005510 Mutex::Autolock _l(mTimedBufferQueueLock);
5511
John Grossman9fbdee12012-03-26 17:51:46 -07005512 ALOG_ASSERT(!mQueueHeadInFlight,
5513 "getNextBuffer called without releaseBuffer!");
5514
John Grossman4ff14ba2012-02-08 16:37:41 -08005515 while (true) {
5516
5517 // if we have no timed buffers, then fail
5518 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005519 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005520 buffer->frameCount = 0;
5521 return NOT_ENOUGH_DATA;
5522 }
5523
5524 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5525
5526 // calculate the PTS of the head of the timed buffer queue expressed in
5527 // local time
5528 int64_t headLocalPTS;
5529 {
5530 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5531
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005532 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005533
5534 if (mMediaTimeTransform.a_to_b_denom == 0) {
5535 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005536 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005537 return NO_ERROR;
5538 }
5539
5540 int64_t transformedPTS;
5541 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5542 &transformedPTS)) {
5543 // the transform failed. this shouldn't happen, but if it does
5544 // then just drop this buffer
5545 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005546 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005547 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005548 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005549 return NO_ERROR;
5550 }
5551
5552 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5553 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5554 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005555 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005556 buffer->frameCount = 0;
5557 return INVALID_OPERATION;
5558 }
5559 } else {
5560 headLocalPTS = transformedPTS;
5561 }
5562 }
5563
5564 // adjust the head buffer's PTS to reflect the portion of the head buffer
5565 // that has already been consumed
5566 int64_t effectivePTS = headLocalPTS +
5567 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5568
5569 // Calculate the delta in samples between the head of the input buffer
5570 // queue and the start of the next output buffer that will be written.
5571 // If the transformation fails because of over or underflow, it means
5572 // that the sample's position in the output stream is so far out of
5573 // whack that it should just be dropped.
5574 int64_t sampleDelta;
5575 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5576 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005577 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5578 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005579 continue;
5580 }
5581 if (!mLocalTimeToSampleTransform.doForwardTransform(
5582 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005583 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005584 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005585 continue;
5586 }
5587
John Grossman1c345192012-03-27 14:00:17 -07005588 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5589 " sampleDelta=[%d.%08x]",
5590 head.pts(), head.position(), pts,
5591 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5592 + (sampleDelta >> 32)),
5593 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005594
5595 // if the delta between the ideal placement for the next input sample and
5596 // the current output position is within this threshold, then we will
5597 // concatenate the next input samples to the previous output
5598 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005599 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005600
5601 // if this is the first buffer of audio that we're emitting from this track
5602 // then it should be almost exactly on time.
5603 const int64_t kSampleStartupThreshold = 1LL << 32;
5604
5605 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005606 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005607 // the next input is close enough to being on time, so concatenate it
5608 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005609 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005610
John Grossman1c345192012-03-27 14:00:17 -07005611 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5612 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005613 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005614 }
5615
5616 // Looks like our output is not on time. Reset our on timed status.
5617 // Next time we mix samples from our input queue, then should be within
5618 // the StartupThreshold.
5619 mTimedAudioOutputOnTime = false;
5620 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005621 // the gap between the current output position and the proper start of
5622 // the next input sample is too big, so fill it with silence
5623 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5624
John Grossman9fbdee12012-03-26 17:51:46 -07005625 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005626 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5627 return NO_ERROR;
5628 } else {
5629 // the next input sample is late
5630 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5631 size_t onTimeSamplePosition =
5632 head.position() + lateFrames * mCblk->frameSize;
5633
5634 if (onTimeSamplePosition > head.buffer()->size()) {
5635 // all the remaining samples in the head are too late, so
5636 // drop it and move on
5637 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005638 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005639 continue;
5640 } else {
5641 // skip over the late samples
5642 head.setPosition(onTimeSamplePosition);
5643
5644 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005645 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005646
5647 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5648 return NO_ERROR;
5649 }
5650 }
5651 }
5652}
5653
5654// Yield samples from the timed buffer queue head up to the given output
5655// buffer's capacity.
5656//
5657// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005658void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005659 AudioBufferProvider::Buffer* buffer) {
5660
5661 const TimedBuffer& head = mTimedBufferQueue[0];
5662
5663 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5664 head.position());
5665
5666 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5667 mCblk->frameSize);
5668 size_t framesRequested = buffer->frameCount;
5669 buffer->frameCount = min(framesLeftInHead, framesRequested);
5670
John Grossman9fbdee12012-03-26 17:51:46 -07005671 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005672 mTimedAudioOutputOnTime = true;
5673}
5674
5675// Yield samples of silence up to the given output buffer's capacity
5676//
5677// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005678void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005679 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5680
5681 // lazily allocate a buffer filled with silence
5682 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5683 delete [] mTimedSilenceBuffer;
5684 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5685 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5686 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5687 }
5688
5689 buffer->raw = mTimedSilenceBuffer;
5690 size_t framesRequested = buffer->frameCount;
5691 buffer->frameCount = min(numFrames, framesRequested);
5692
5693 mTimedAudioOutputOnTime = false;
5694}
5695
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005696// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005697void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5698 AudioBufferProvider::Buffer* buffer) {
5699
5700 Mutex::Autolock _l(mTimedBufferQueueLock);
5701
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005702 // If the buffer which was just released is part of the buffer at the head
5703 // of the queue, be sure to update the amt of the buffer which has been
5704 // consumed. If the buffer being returned is not part of the head of the
5705 // queue, its either because the buffer is part of the silence buffer, or
5706 // because the head of the timed queue was trimmed after the mixer called
5707 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005708 if (buffer->raw == mTimedSilenceBuffer) {
5709 ALOG_ASSERT(!mQueueHeadInFlight,
5710 "Queue head in flight during release of silence buffer!");
5711 goto done;
5712 }
5713
5714 ALOG_ASSERT(mQueueHeadInFlight,
5715 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5716 " head in flight.");
5717
5718 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005719 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005720
5721 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005722 void* end = reinterpret_cast<void*>(
5723 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5724 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005725
John Grossman9fbdee12012-03-26 17:51:46 -07005726 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5727 "released buffer not within the head of the timed buffer"
5728 " queue; qHead = [%p, %p], released buffer = %p",
5729 start, end, buffer->raw);
5730
5731 head.setPosition(head.position() +
5732 (buffer->frameCount * mCblk->frameSize));
5733 mQueueHeadInFlight = false;
5734
John Grossman1c345192012-03-27 14:00:17 -07005735 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5736 "Bad bookkeeping during releaseBuffer! Should have at"
5737 " least %u queued frames, but we think we have only %u",
5738 buffer->frameCount, mFramesPendingInQueue);
5739
5740 mFramesPendingInQueue -= buffer->frameCount;
5741
John Grossman9fbdee12012-03-26 17:51:46 -07005742 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5743 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005744 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005745 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005746 }
John Grossman9fbdee12012-03-26 17:51:46 -07005747 } else {
5748 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5749 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005750 }
5751
John Grossman9fbdee12012-03-26 17:51:46 -07005752done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005753 buffer->raw = 0;
5754 buffer->frameCount = 0;
5755}
5756
Glenn Kasten288ed212012-04-25 17:52:27 -07005757size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005758 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005759 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005760}
5761
5762AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5763 : mPTS(0), mPosition(0) {}
5764
5765AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5766 const sp<IMemory>& buffer, int64_t pts)
5767 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5768
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769// ----------------------------------------------------------------------------
5770
5771// RecordTrack constructor must be called with AudioFlinger::mLock held
5772AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005773 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 const sp<Client>& client,
5775 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005776 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005777 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779 int sessionId)
5780 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005781 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 mOverflow(false)
5783{
5784 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005785 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5786 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5787 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5788 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5789 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5790 } else {
5791 mCblk->frameSize = sizeof(int8_t);
5792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 }
5794}
5795
5796AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5797{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005798 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799}
5800
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005801// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005802status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803{
5804 audio_track_cblk_t* cblk = this->cblk();
5805 uint32_t framesAvail;
5806 uint32_t framesReq = buffer->frameCount;
5807
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005808 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005809 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005811 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005812 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 }
5814
5815 framesAvail = cblk->framesAvailable_l();
5816
Glenn Kastenf6b16782011-12-15 09:51:17 -08005817 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 uint32_t s = cblk->server;
5819 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5820
5821 if (framesReq > framesAvail) {
5822 framesReq = framesAvail;
5823 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005824 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 framesReq = bufferEnd - s;
5826 }
5827
5828 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 buffer->frameCount = framesReq;
5830 return NO_ERROR;
5831 }
5832
5833getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005834 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835 buffer->frameCount = 0;
5836 return NOT_ENOUGH_DATA;
5837}
5838
Glenn Kasten3acbd052012-02-28 10:39:56 -08005839status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005840 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841{
5842 sp<ThreadBase> thread = mThread.promote();
5843 if (thread != 0) {
5844 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005845 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846 } else {
5847 return BAD_VALUE;
5848 }
5849}
5850
5851void AudioFlinger::RecordThread::RecordTrack::stop()
5852{
5853 sp<ThreadBase> thread = mThread.promote();
5854 if (thread != 0) {
5855 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005856 recordThread->mLock.lock();
5857 bool doStop = recordThread->stop_l(this);
5858 if (doStop) {
5859 TrackBase::reset();
5860 // Force overrun condition to avoid false overrun callback until first data is
5861 // read from buffer
5862 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5863 }
5864 recordThread->mLock.unlock();
5865 if (doStop) {
5866 AudioSystem::stopInput(recordThread->id());
5867 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 }
5869}
5870
Glenn Kasten510a3d62012-07-16 14:24:34 -07005871/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5872{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005873 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005874}
5875
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5877{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005878 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005879 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005881 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005882 mSessionId,
5883 mFrameCount,
5884 mState,
5885 mCblk->sampleRate,
5886 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005887 mCblk->user,
5888 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889}
5890
5891
5892// ----------------------------------------------------------------------------
5893
5894AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005895 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 DuplicatingThread *sourceThread,
5897 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005898 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005899 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005901 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5902 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 mActive(false), mSourceThread(sourceThread)
5904{
5905
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 if (mCblk != NULL) {
5907 mCblk->flags |= CBLK_DIRECTION_OUT;
5908 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909 mOutBuffer.frameCount = 0;
5910 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005911 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005912 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5913 mCblk, mBuffer, mCblk->buffers,
5914 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005916 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 }
5918}
5919
5920AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5921{
5922 clearBufferQueue();
5923}
5924
Glenn Kasten3acbd052012-02-28 10:39:56 -08005925status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005926 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005928 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929 if (status != NO_ERROR) {
5930 return status;
5931 }
5932
5933 mActive = true;
5934 mRetryCount = 127;
5935 return status;
5936}
5937
5938void AudioFlinger::PlaybackThread::OutputTrack::stop()
5939{
5940 Track::stop();
5941 clearBufferQueue();
5942 mOutBuffer.frameCount = 0;
5943 mActive = false;
5944}
5945
5946bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5947{
5948 Buffer *pInBuffer;
5949 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005950 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 bool outputBufferFull = false;
5952 inBuffer.frameCount = frames;
5953 inBuffer.i16 = data;
5954
5955 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5956
5957 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005958 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 sp<ThreadBase> thread = mThread.promote();
5960 if (thread != 0) {
5961 MixerThread *mixerThread = (MixerThread *)thread.get();
5962 if (mCblk->frameCount > frames){
5963 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5964 uint32_t startFrames = (mCblk->frameCount - frames);
5965 pInBuffer = new Buffer;
5966 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5967 pInBuffer->frameCount = startFrames;
5968 pInBuffer->i16 = pInBuffer->mBuffer;
5969 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5970 mBufferQueue.add(pInBuffer);
5971 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005972 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 }
5974 }
5975 }
5976 }
5977
5978 while (waitTimeLeftMs) {
5979 // First write pending buffers, then new data
5980 if (mBufferQueue.size()) {
5981 pInBuffer = mBufferQueue.itemAt(0);
5982 } else {
5983 pInBuffer = &inBuffer;
5984 }
5985
5986 if (pInBuffer->frameCount == 0) {
5987 break;
5988 }
5989
5990 if (mOutBuffer.frameCount == 0) {
5991 mOutBuffer.frameCount = pInBuffer->frameCount;
5992 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005993 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005994 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 outputBufferFull = true;
5996 break;
5997 }
5998 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5999 if (waitTimeLeftMs >= waitTimeMs) {
6000 waitTimeLeftMs -= waitTimeMs;
6001 } else {
6002 waitTimeLeftMs = 0;
6003 }
6004 }
6005
6006 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
6007 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
6008 mCblk->stepUser(outFrames);
6009 pInBuffer->frameCount -= outFrames;
6010 pInBuffer->i16 += outFrames * channelCount;
6011 mOutBuffer.frameCount -= outFrames;
6012 mOutBuffer.i16 += outFrames * channelCount;
6013
6014 if (pInBuffer->frameCount == 0) {
6015 if (mBufferQueue.size()) {
6016 mBufferQueue.removeAt(0);
6017 delete [] pInBuffer->mBuffer;
6018 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01006019 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 } else {
6021 break;
6022 }
6023 }
6024 }
6025
6026 // If we could not write all frames, allocate a buffer and queue it for next time.
6027 if (inBuffer.frameCount) {
6028 sp<ThreadBase> thread = mThread.promote();
6029 if (thread != 0 && !thread->standby()) {
6030 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
6031 pInBuffer = new Buffer;
6032 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
6033 pInBuffer->frameCount = inBuffer.frameCount;
6034 pInBuffer->i16 = pInBuffer->mBuffer;
6035 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
6036 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01006037 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006039 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 }
6041 }
6042 }
6043
6044 // Calling write() with a 0 length buffer, means that no more data will be written:
6045 // If no more buffers are pending, fill output track buffer to make sure it is started
6046 // by output mixer.
6047 if (frames == 0 && mBufferQueue.size() == 0) {
6048 if (mCblk->user < mCblk->frameCount) {
6049 frames = mCblk->frameCount - mCblk->user;
6050 pInBuffer = new Buffer;
6051 pInBuffer->mBuffer = new int16_t[frames * channelCount];
6052 pInBuffer->frameCount = frames;
6053 pInBuffer->i16 = pInBuffer->mBuffer;
6054 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
6055 mBufferQueue.add(pInBuffer);
6056 } else if (mActive) {
6057 stop();
6058 }
6059 }
6060
6061 return outputBufferFull;
6062}
6063
6064status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
6065{
6066 int active;
6067 status_t result;
6068 audio_track_cblk_t* cblk = mCblk;
6069 uint32_t framesReq = buffer->frameCount;
6070
Steve Block3856b092011-10-20 11:56:00 +01006071// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 buffer->frameCount = 0;
6073
6074 uint32_t framesAvail = cblk->framesAvailable();
6075
6076
6077 if (framesAvail == 0) {
6078 Mutex::Autolock _l(cblk->lock);
6079 goto start_loop_here;
6080 while (framesAvail == 0) {
6081 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08006082 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08006084 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 }
6086 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
6087 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006088 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089 }
6090 // read the server count again
6091 start_loop_here:
6092 framesAvail = cblk->framesAvailable_l();
6093 }
6094 }
6095
6096// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08006097// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098// }
6099
6100 if (framesReq > framesAvail) {
6101 framesReq = framesAvail;
6102 }
6103
6104 uint32_t u = cblk->user;
6105 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
6106
Marco Nelissena1472d92012-03-30 14:36:54 -07006107 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 framesReq = bufferEnd - u;
6109 }
6110
6111 buffer->frameCount = framesReq;
6112 buffer->raw = (void *)cblk->buffer(u);
6113 return NO_ERROR;
6114}
6115
6116
6117void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
6118{
6119 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120
6121 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08006122 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 delete [] pBuffer->mBuffer;
6124 delete pBuffer;
6125 }
6126 mBufferQueue.clear();
6127}
6128
6129// ----------------------------------------------------------------------------
6130
6131AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
6132 : RefBase(),
6133 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08006134 // 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 -07006135 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08006136 mPid(pid),
6137 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138{
6139 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
6140}
6141
6142// Client destructor must be called with AudioFlinger::mLock held
6143AudioFlinger::Client::~Client()
6144{
6145 mAudioFlinger->removeClient_l(mPid);
6146}
6147
Glenn Kasten435dbe62012-01-30 10:15:48 -08006148sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149{
6150 return mMemoryDealer;
6151}
6152
John Grossman4ff14ba2012-02-08 16:37:41 -08006153// Reserve one of the limited slots for a timed audio track associated
6154// with this client
6155bool AudioFlinger::Client::reserveTimedTrack()
6156{
6157 const int kMaxTimedTracksPerClient = 4;
6158
6159 Mutex::Autolock _l(mTimedTrackLock);
6160
6161 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
6162 ALOGW("can not create timed track - pid %d has exceeded the limit",
6163 mPid);
6164 return false;
6165 }
6166
6167 mTimedTrackCount++;
6168 return true;
6169}
6170
6171// Release a slot for a timed audio track
6172void AudioFlinger::Client::releaseTimedTrack()
6173{
6174 Mutex::Autolock _l(mTimedTrackLock);
6175 mTimedTrackCount--;
6176}
6177
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178// ----------------------------------------------------------------------------
6179
6180AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
6181 const sp<IAudioFlingerClient>& client,
vivek mehta2192bc92012-12-04 11:46:08 -08006182 sp<IBinder> binder)
6183 : mAudioFlinger(audioFlinger), mBinder(binder), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184{
6185}
6186
6187AudioFlinger::NotificationClient::~NotificationClient()
6188{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189}
6190
6191void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
6192{
6193 sp<NotificationClient> keep(this);
vivek mehta2192bc92012-12-04 11:46:08 -08006194 mAudioFlinger->removeNotificationClient(mBinder);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195}
6196
6197// ----------------------------------------------------------------------------
vivek mehta2192bc92012-12-04 11:46:08 -08006198#ifdef QCOM_HARDWARE
6199AudioFlinger::DirectAudioTrack::DirectAudioTrack(const sp<AudioFlinger>& audioFlinger,
6200 int output, AudioSessionDescriptor *outputDesc,
6201 IDirectTrackClient* client, audio_output_flags_t outflag)
6202 : BnDirectTrack(), mIsPaused(false), mAudioFlinger(audioFlinger), mOutput(output), mOutputDesc(outputDesc),
6203 mClient(client), mEffectConfigChanged(false), mKillEffectsThread(false), mFlag(outflag)
6204{
6205 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6206 createEffectThread();
6207
6208 mAudioFlingerClient = new AudioFlingerDirectTrackClient(this);
6209 mAudioFlinger->registerClient(mAudioFlingerClient);
6210
6211 allocateBufPool();
6212 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08006213 outputDesc->mVolumeScale = 1.0;
vivek mehta2192bc92012-12-04 11:46:08 -08006214 mDeathRecipient = new PMDeathRecipient(this);
6215 acquireWakeLock();
6216}
6217
6218AudioFlinger::DirectAudioTrack::~DirectAudioTrack() {
6219 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6220 requestAndWaitForEffectsThreadExit();
6221 mAudioFlinger->deregisterClient(mAudioFlingerClient);
6222 mAudioFlinger->deleteEffectSession();
6223 deallocateBufPool();
6224 }
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006225 AudioSystem::releaseOutput(mOutput);
vivek mehta2192bc92012-12-04 11:46:08 -08006226 releaseWakeLock();
Alexy Joseph8ea530c2012-12-22 00:58:48 -08006227
Mingming Yin9b3dd172013-01-10 18:42:38 -08006228 {
6229 Mutex::Autolock _l(pmLock);
6230 if (mPowerManager != 0) {
6231 sp<IBinder> binder = mPowerManager->asBinder();
6232 binder->unlinkToDeath(mDeathRecipient);
6233 }
vivek mehta2192bc92012-12-04 11:46:08 -08006234 }
vivek mehta2192bc92012-12-04 11:46:08 -08006235}
6236
6237status_t AudioFlinger::DirectAudioTrack::start() {
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08006238 AudioSystem::startOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
vivek mehta2192bc92012-12-04 11:46:08 -08006239 if(mIsPaused) {
6240 mIsPaused = false;
6241 mOutputDesc->stream->start(mOutputDesc->stream);
6242 }
6243 mOutputDesc->mActive = true;
vivek mehta2192bc92012-12-04 11:46:08 -08006244 return NO_ERROR;
6245}
6246
6247void AudioFlinger::DirectAudioTrack::stop() {
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08006248 ALOGV("DirectAudioTrack::stop");
vivek mehta2192bc92012-12-04 11:46:08 -08006249 mOutputDesc->mActive = false;
6250 mOutputDesc->stream->stop(mOutputDesc->stream);
6251 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6252}
6253
6254void AudioFlinger::DirectAudioTrack::pause() {
6255 if(!mIsPaused) {
6256 mIsPaused = true;
6257 mOutputDesc->stream->pause(mOutputDesc->stream);
6258 mOutputDesc->mActive = false;
6259 AudioSystem::stopOutput(mOutput, (audio_stream_type_t)mOutputDesc->mStreamType);
6260 }
6261}
6262
6263ssize_t AudioFlinger::DirectAudioTrack::write(const void *buffer, size_t size) {
6264 ALOGV("Writing to AudioSessionOut");
6265 int isAvail = 0;
6266 mOutputDesc->stream->is_buffer_available(mOutputDesc->stream, &isAvail);
6267 if (!isAvail) {
6268 return 0;
6269 }
6270
6271 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6272 mEffectLock.lock();
6273 List<BufferInfo>::iterator it = mEffectsPool.begin();
6274 BufferInfo buf = *it;
6275 mEffectsPool.erase(it);
6276 memcpy((char *) buf.localBuf, (char *)buffer, size);
6277 buf.bytesToWrite = size;
6278 mEffectsPool.push_back(buf);
6279 mAudioFlinger->applyEffectsOn(static_cast<void *>(this), (int16_t*)buf.localBuf,(int16_t*)buffer,(int)size);
6280 mEffectLock.unlock();
6281 }
6282 return mOutputDesc->stream->write(mOutputDesc->stream, buffer, size);
6283}
6284
6285void AudioFlinger::DirectAudioTrack::flush() {
6286 if (mFlag & AUDIO_OUTPUT_FLAG_LPA) {
6287 mEffectsPool.clear();
6288 mEffectsPool = mBufPool;
6289 }
6290 mOutputDesc->stream->flush(mOutputDesc->stream);
6291}
6292
6293void AudioFlinger::DirectAudioTrack::mute(bool muted) {
6294}
6295
6296void AudioFlinger::DirectAudioTrack::setVolume(float left, float right) {
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08006297 ALOGV("DirectAudioTrack::setVolume left: %f, right: %f", left, right);
6298 if(mOutputDesc && mOutputDesc->mActive) {
6299 mOutputDesc->mVolumeLeft = left;
6300 mOutputDesc->mVolumeRight = right;
6301 mOutputDesc->stream->set_volume(mOutputDesc->stream,
Dorian Snyderf32d5702013-03-01 14:25:46 -08006302 left * mOutputDesc->mVolumeScale,
6303 right* mOutputDesc->mVolumeScale);
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08006304 }
vivek mehta2192bc92012-12-04 11:46:08 -08006305}
6306
6307int64_t AudioFlinger::DirectAudioTrack::getTimeStamp() {
6308 int64_t time;
6309 mOutputDesc->stream->get_next_write_timestamp(mOutputDesc->stream, &time);
6310 ALOGV("Timestamp %lld",time);
6311 return time;
6312}
6313
6314void AudioFlinger::DirectAudioTrack::postEOS(int64_t delayUs) {
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006315#ifdef QCOM_HARDWARE
6316 if (delayUs == 0 ) {
6317 ALOGV("Notify Audio Track of EOS event");
6318 mClient->notify(DIRECT_TRACK_EOS);
6319 } else {
6320 ALOGV("Notify Audio Track of hardware failure event");
6321 mClient->notify(DIRECT_TRACK_HW_FAIL);
6322 }
6323#else
vivek mehta2192bc92012-12-04 11:46:08 -08006324 ALOGV("Notify Audio Track of EOS event");
6325 mClient->notify(DIRECT_TRACK_EOS);
Ravishankar Sarawadi20017912013-02-27 18:47:54 +01006326#endif
vivek mehta2192bc92012-12-04 11:46:08 -08006327}
6328
6329void AudioFlinger::DirectAudioTrack::allocateBufPool() {
6330 void *dsp_buf = NULL;
6331 void *local_buf = NULL;
6332
6333 //1. get the ion buffer information
6334 struct buf_info* buf = NULL;
6335 mOutputDesc->stream->get_buffer_info(mOutputDesc->stream, &buf);
6336 ALOGV("get buffer info %p",buf);
6337 if (!buf) {
6338 ALOGV("buffer is NULL");
6339 return;
6340 }
6341 int nSize = buf->bufsize;
6342 int bufferCount = buf->nBufs;
6343
6344 //2. allocate the buffer pool, allocate local buffers
6345 for (int i = 0; i < bufferCount; i++) {
6346 dsp_buf = (void *)buf->buffers[i];
6347 local_buf = malloc(nSize);
6348 memset(local_buf, 0, nSize);
6349 // Store this information for internal mapping / maintanence
6350 BufferInfo buf(local_buf, dsp_buf, nSize);
6351 buf.bytesToWrite = 0;
6352 mBufPool.push_back(buf);
6353 mEffectsPool.push_back(buf);
6354
6355 ALOGV("The MEM that is allocated buffer is %x, size %d",(unsigned int)dsp_buf,nSize);
6356 }
6357 free(buf);
6358}
6359
6360void AudioFlinger::DirectAudioTrack::deallocateBufPool() {
6361
6362 //1. Deallocate the local memory
6363 //2. Remove all the buffers from bufpool
6364 while (!mBufPool.empty()) {
6365 List<BufferInfo>::iterator it = mBufPool.begin();
6366 BufferInfo &memBuffer = *it;
6367 // free the local buffer corresponding to mem buffer
6368 if (memBuffer.localBuf) {
6369 free(memBuffer.localBuf);
6370 memBuffer.localBuf = NULL;
6371 }
6372 ALOGV("Removing from bufpool");
6373 mBufPool.erase(it);
6374 }
6375}
6376
6377status_t AudioFlinger::DirectAudioTrack::onTransact(
6378 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6379{
6380 return BnDirectTrack::onTransact(code, data, reply, flags);
6381}
6382
6383void *AudioFlinger::DirectAudioTrack::EffectsThreadWrapper(void *me) {
6384 static_cast<DirectAudioTrack *>(me)->EffectsThreadEntry();
6385 return NULL;
6386}
6387
6388void AudioFlinger::DirectAudioTrack::EffectsThreadEntry() {
6389 while(1) {
6390 mEffectLock.lock();
6391 if (!mEffectConfigChanged && !mKillEffectsThread) {
6392 mEffectCv.wait(mEffectLock);
6393 }
6394
6395 if(mKillEffectsThread) {
6396 mEffectLock.unlock();
6397 break;
6398 }
6399
6400 if (mEffectConfigChanged) {
6401 mEffectConfigChanged = false;
6402 for ( List<BufferInfo>::iterator it = mEffectsPool.begin();
6403 it != mEffectsPool.end(); it++) {
6404 ALOGV("Apply effects on the buffer dspbuf %p, mEffectsPool.size() %d",it->dspBuf,mEffectsPool.size());
6405 mAudioFlinger->applyEffectsOn(static_cast<void *>(this),
6406 (int16_t *)it->localBuf,
6407 (int16_t *)it->dspBuf,
6408 it->bytesToWrite);
6409 if (mEffectConfigChanged) {
6410 break;
6411 }
6412 }
6413
6414 }
6415 mEffectLock.unlock();
6416 }
6417 ALOGV("Effects thread is dead");
6418 mEffectsThreadAlive = false;
6419}
6420
6421void AudioFlinger::DirectAudioTrack::requestAndWaitForEffectsThreadExit() {
6422 if (!mEffectsThreadAlive)
6423 return;
6424 mKillEffectsThread = true;
6425 mEffectCv.signal();
6426 pthread_join(mEffectsThread,NULL);
6427 ALOGV("effects thread killed");
6428}
6429
6430void AudioFlinger::DirectAudioTrack::createEffectThread() {
6431 //Create the effects thread
6432 pthread_attr_t attr;
6433 pthread_attr_init(&attr);
6434 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
6435 mEffectsThreadAlive = true;
6436 ALOGV("Creating Effects Thread");
6437 pthread_create(&mEffectsThread, &attr, EffectsThreadWrapper, this);
6438}
6439AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::AudioFlingerDirectTrackClient(void *obj)
6440{
6441 ALOGV("AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient");
6442 pBaseClass = (DirectAudioTrack*)obj;
6443}
6444
6445void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient::binderDied(const wp<IBinder>& who) {
6446 pBaseClass->mAudioFlinger.clear();
6447 ALOGW("AudioFlinger server died!");
6448}
6449
6450void AudioFlinger::DirectAudioTrack::AudioFlingerDirectTrackClient
6451 ::ioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2) {
6452 ALOGV("ioConfigChanged() event %d", event);
6453 if (event == AudioSystem::EFFECT_CONFIG_CHANGED) {
6454 ALOGV("Received notification for change in effect module");
6455 // Seek to current media time - flush the decoded buffers with the driver
6456 pBaseClass->mEffectConfigChanged = true;
6457 // Signal effects thread to re-apply effects
6458 ALOGV("Signalling Effects Thread");
6459 pBaseClass->mEffectCv.signal();
6460
6461 }
6462 ALOGV("ioConfigChanged Out");
6463}
6464
6465void AudioFlinger::DirectAudioTrack::acquireWakeLock()
6466{
6467 Mutex::Autolock _l(pmLock);
6468
6469 if (mPowerManager == 0) {
6470 // use checkService() to avoid blocking if power service is not up yet
6471 sp<IBinder> binder =
6472 defaultServiceManager()->checkService(String16("power"));
6473 if (binder == 0) {
6474 ALOGW("Thread %s cannot connect to the power manager service", lockName);
6475 } else {
6476 mPowerManager = interface_cast<IPowerManager>(binder);
6477 binder->linkToDeath(mDeathRecipient);
6478 }
6479 }
6480 if (mPowerManager != 0 && mWakeLockToken == 0) {
6481 sp<IBinder> binder = new BBinder();
6482 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
6483 binder,
6484 String16(lockName));
6485 if (status == NO_ERROR) {
6486 mWakeLockToken = binder;
6487 }
6488 ALOGV("acquireWakeLock() status %d", status);
6489 }
6490}
6491
6492void AudioFlinger::DirectAudioTrack::releaseWakeLock()
6493{
6494 Mutex::Autolock _l(pmLock);
6495
6496 if (mWakeLockToken != 0) {
6497 ALOGV("releaseWakeLock()");
6498 if (mPowerManager != 0) {
6499 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
6500 }
6501 mWakeLockToken.clear();
6502 }
6503}
6504
6505void AudioFlinger::DirectAudioTrack::clearPowerManager()
6506{
vivek mehta2192bc92012-12-04 11:46:08 -08006507 releaseWakeLock();
Mingming Yin9b3dd172013-01-10 18:42:38 -08006508 Mutex::Autolock _l(pmLock);
vivek mehta2192bc92012-12-04 11:46:08 -08006509 mPowerManager.clear();
6510}
6511
6512void AudioFlinger::DirectAudioTrack::PMDeathRecipient::binderDied(const wp<IBinder>& who)
6513{
6514 parentClass->clearPowerManager();
6515 ALOGW("power manager service died !!!");
6516}
6517#endif
6518
6519// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520
6521AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
6522 : BnAudioTrack(),
6523 mTrack(track)
6524{
6525}
6526
6527AudioFlinger::TrackHandle::~TrackHandle() {
6528 // just stop the track on deletion, associated resources
6529 // will be freed from the main thread once all pending buffers have
6530 // been played. Unless it's not in the active track list, in which
6531 // case we free everything now...
6532 mTrack->destroy();
6533}
6534
Glenn Kasten90716c52012-01-26 13:40:12 -08006535sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
6536 return mTrack->getCblk();
6537}
6538
Glenn Kasten3acbd052012-02-28 10:39:56 -08006539status_t AudioFlinger::TrackHandle::start() {
6540 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541}
6542
6543void AudioFlinger::TrackHandle::stop() {
6544 mTrack->stop();
6545}
6546
6547void AudioFlinger::TrackHandle::flush() {
6548 mTrack->flush();
6549}
6550
6551void AudioFlinger::TrackHandle::mute(bool e) {
6552 mTrack->mute(e);
6553}
6554
6555void AudioFlinger::TrackHandle::pause() {
6556 mTrack->pause();
6557}
6558
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
6560{
6561 return mTrack->attachAuxEffect(EffectId);
6562}
6563
John Grossman4ff14ba2012-02-08 16:37:41 -08006564status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
6565 sp<IMemory>* buffer) {
6566 if (!mTrack->isTimedTrack())
6567 return INVALID_OPERATION;
6568
6569 PlaybackThread::TimedTrack* tt =
6570 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6571 return tt->allocateTimedBuffer(size, buffer);
6572}
6573
6574status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
6575 int64_t pts) {
6576 if (!mTrack->isTimedTrack())
6577 return INVALID_OPERATION;
6578
6579 PlaybackThread::TimedTrack* tt =
6580 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6581 return tt->queueTimedBuffer(buffer, pts);
6582}
6583
6584status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
6585 const LinearTransform& xform, int target) {
6586
6587 if (!mTrack->isTimedTrack())
6588 return INVALID_OPERATION;
6589
6590 PlaybackThread::TimedTrack* tt =
6591 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
6592 return tt->setMediaTimeTransform(
6593 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
6594}
6595
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596status_t AudioFlinger::TrackHandle::onTransact(
6597 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6598{
6599 return BnAudioTrack::onTransact(code, data, reply, flags);
6600}
6601
6602// ----------------------------------------------------------------------------
6603
6604sp<IAudioRecord> AudioFlinger::openRecord(
6605 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006606 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006608 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006609 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08006611 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006612 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 int *sessionId,
6614 status_t *status)
6615{
6616 sp<RecordThread::RecordTrack> recordTrack;
6617 sp<RecordHandle> recordHandle;
6618 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 status_t lStatus;
6620 RecordThread *thread;
6621 size_t inFrameCount;
6622 int lSessionId;
6623
6624 // check calling permissions
6625 if (!recordingAllowed()) {
6626 lStatus = PERMISSION_DENIED;
6627 goto Exit;
6628 }
6629
6630 // add client to list
6631 { // scope for mLock
6632 Mutex::Autolock _l(mLock);
6633 thread = checkRecordThread_l(input);
6634 if (thread == NULL) {
6635 lStatus = BAD_VALUE;
6636 goto Exit;
6637 }
6638
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006639 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640
6641 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07006642 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 lSessionId = *sessionId;
6644 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006645 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646 if (sessionId != NULL) {
6647 *sessionId = lSessionId;
6648 }
6649 }
6650 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07006651 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
6652 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006653 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006654 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 // remove local strong reference to Client before deleting the RecordTrack so that the Client
6656 // destructor is called by the TrackBase destructor with mLock held
6657 client.clear();
6658 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 goto Exit;
6660 }
6661
6662 // return to handle to client
6663 recordHandle = new RecordHandle(recordTrack);
6664 lStatus = NO_ERROR;
6665
6666Exit:
6667 if (status) {
6668 *status = lStatus;
6669 }
6670 return recordHandle;
6671}
6672
6673// ----------------------------------------------------------------------------
6674
6675AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
6676 : BnAudioRecord(),
6677 mRecordTrack(recordTrack)
6678{
6679}
6680
6681AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006682 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006683 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684}
6685
Glenn Kasten90716c52012-01-26 13:40:12 -08006686sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6687 return mRecordTrack->getCblk();
6688}
6689
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07006690status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006691 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006692 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693}
6694
6695void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006696 stop_nonvirtual();
6697}
6698
6699void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006700 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701 mRecordTrack->stop();
6702}
6703
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704status_t AudioFlinger::RecordHandle::onTransact(
6705 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6706{
6707 return BnAudioRecord::onTransact(code, data, reply, flags);
6708}
6709
6710// ----------------------------------------------------------------------------
6711
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006712AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6713 AudioStreamIn *input,
6714 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006715 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006716 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006717 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006718 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006719 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006720 // mRsmpInIndex and mInputBytes set by readInputParameters()
vivek mehta2192bc92012-12-04 11:46:08 -08006721 mReqChannelCount(getInputChannelCount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006722 mReqSampleRate(sampleRate)
6723 // mBytesRead is only meaningful while active, and so is cleared in start()
6724 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725{
Glenn Kasten480b4682012-02-28 12:30:08 -08006726 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006727
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728 readInputParameters();
6729}
6730
6731
6732AudioFlinger::RecordThread::~RecordThread()
6733{
6734 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006735 delete mResampler;
6736 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737}
6738
6739void AudioFlinger::RecordThread::onFirstRef()
6740{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006741 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742}
6743
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006744status_t AudioFlinger::RecordThread::readyToRun()
6745{
6746 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006747 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006748 return status;
6749}
6750
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751bool AudioFlinger::RecordThread::threadLoop()
6752{
6753 AudioBufferProvider::Buffer buffer;
6754 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006755 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756
Eric Laurent44d98482010-09-30 16:12:31 -07006757 nsecs_t lastWarning = 0;
6758
Glenn Kastene4e2a372012-07-23 12:55:09 -07006759 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006760 acquireWakeLock();
6761
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006762 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006763 bool readOnce = false;
6764
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 // start recording
6766 while (!exitPending()) {
6767
6768 processConfigEvents();
6769
6770 { // scope for mLock
6771 Mutex::Autolock _l(mLock);
6772 checkForNewParameters_l();
6773 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006774 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775
6776 if (exitPending()) break;
6777
Eric Laurentfeb0db62011-07-22 09:04:31 -07006778 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006779 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 // go to sleep
6781 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006782 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006783 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784 continue;
6785 }
6786 if (mActiveTrack != 0) {
6787 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006788 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789 mActiveTrack.clear();
6790 mStartStopCond.broadcast();
6791 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6792 if (mReqChannelCount != mActiveTrack->channelCount()) {
6793 mActiveTrack.clear();
6794 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006795 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 // record start succeeds only if first read from audio input
6797 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006798 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 mActiveTrack->mState = TrackBase::ACTIVE;
6800 } else {
6801 mActiveTrack.clear();
6802 }
6803 mStartStopCond.broadcast();
6804 }
6805 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006806 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6807 removeTrack_l(mActiveTrack);
6808 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 }
6810 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006811 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 }
6813
6814 if (mActiveTrack != 0) {
6815 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6816 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006817 unlockEffectChains(effectChains);
6818 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006819 continue;
6820 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006821 for (size_t i = 0; i < effectChains.size(); i ++) {
6822 effectChains[i]->process_l();
6823 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006824
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006826 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006827 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006829 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006830 // no resampling
6831 while (framesOut) {
6832 size_t framesIn = mFrameCount - mRsmpInIndex;
6833 if (framesIn) {
6834 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6835 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6836 if (framesIn > framesOut)
6837 framesIn = framesOut;
6838 mRsmpInIndex += framesIn;
6839 framesOut -= framesIn;
6840 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006841 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 memcpy(dst, src, framesIn * mFrameSize);
6843 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006845 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6846 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006848 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6849 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 }
6851 }
6852 }
6853 if (framesOut && mFrameCount == mRsmpInIndex) {
6854 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006855 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006856 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 framesOut = 0;
6858 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006859 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860 mRsmpInIndex = 0;
6861 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006862 if (mBytesRead <= 0) {
6863 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6864 {
6865 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 // Force input into standby so that it tries to
6867 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006868 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006869 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870 }
6871 mRsmpInIndex = mFrameCount;
6872 framesOut = 0;
6873 buffer.frameCount = 0;
6874 }
6875 }
6876 }
6877 } else {
6878 // resampling
6879
6880 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6881 // alter output frame count as if we were expecting stereo samples
6882 if (mChannelCount == 1 && mReqChannelCount == 1) {
6883 framesOut >>= 1;
6884 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006885 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6887 // are 32 bit aligned which should be always true.
6888 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006889 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006891 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6892 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006894 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895 }
6896
6897 }
Eric Laurenta011e352012-03-29 15:51:43 -07006898 if (mFramestoDrop == 0) {
6899 mActiveTrack->releaseBuffer(&buffer);
6900 } else {
6901 if (mFramestoDrop > 0) {
6902 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006903 if (mFramestoDrop <= 0) {
6904 clearSyncStartEvent();
6905 }
6906 } else {
6907 mFramestoDrop += buffer.frameCount;
6908 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6909 mSyncStartEvent->isCancelled()) {
6910 ALOGW("Synced record %s, session %d, trigger session %d",
6911 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6912 mActiveTrack->sessionId(),
6913 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6914 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006915 }
6916 }
6917 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006918 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919 }
6920 // client isn't retrieving buffers fast enough
6921 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006922 if (!mActiveTrack->setOverflow()) {
6923 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006924 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006925 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006926 lastWarning = now;
6927 }
6928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929 // Release the processor for a while before asking for a new buffer.
6930 // This will give the application more chance to read from the buffer and
6931 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006932 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 }
6934 }
Eric Laurentec437d82011-07-26 20:54:46 -07006935 // enable changes in effect chain
6936 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006937 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 }
6939
Glenn Kastene4e2a372012-07-23 12:55:09 -07006940 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941
Glenn Kasten33e6e352012-07-16 15:56:57 -07006942 {
6943 Mutex::Autolock _l(mLock);
6944 mActiveTrack.clear();
6945 mStartStopCond.broadcast();
6946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947
Eric Laurentfeb0db62011-07-22 09:04:31 -07006948 releaseWakeLock();
6949
Steve Block3856b092011-10-20 11:56:00 +01006950 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 return false;
6952}
6953
Glenn Kastene4e2a372012-07-23 12:55:09 -07006954void AudioFlinger::RecordThread::standby()
6955{
6956 if (!mStandby) {
6957 inputStandBy();
6958 mStandby = true;
6959 }
6960}
6961
6962void AudioFlinger::RecordThread::inputStandBy()
6963{
6964 mInput->stream->common.standby(&mInput->stream->common);
6965}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006966
6967sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6968 const sp<AudioFlinger::Client>& client,
6969 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006970 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006971 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006972 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006973 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006974 IAudioFlinger::track_flags_t flags,
6975 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006976 status_t *status)
6977{
6978 sp<RecordTrack> track;
6979 status_t lStatus;
6980
6981 lStatus = initCheck();
6982 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006983 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006984 goto Exit;
6985 }
6986
Glenn Kasten1879fff2012-07-11 15:36:59 -07006987 // FIXME use flags and tid similar to createTrack_l()
6988
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006989 { // scope for mLock
6990 Mutex::Autolock _l(mLock);
6991
6992 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006993 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006994
Glenn Kasten7378ca52012-01-20 13:44:40 -08006995 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 lStatus = NO_MEMORY;
6997 goto Exit;
6998 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006999 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007000
Eric Laurent59bd0da2011-08-01 09:52:20 -07007001 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07007002 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007003 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07007004 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
7005 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007006 }
7007 lStatus = NO_ERROR;
7008
7009Exit:
7010 if (status) {
7011 *status = lStatus;
7012 }
7013 return track;
7014}
7015
Eric Laurenta011e352012-03-29 15:51:43 -07007016status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08007017 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07007018 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019{
Glenn Kasten58912562012-04-03 10:45:00 -07007020 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007021 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07007023
7024 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07007025 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07007026 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
7027 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
7028 triggerSession,
7029 recordTrack->sessionId(),
7030 syncStartEventCallback,
7031 this);
Eric Laurent29864602012-05-08 18:57:51 -07007032 // Sync event can be cancelled by the trigger session if the track is not in a
7033 // compatible state in which case we start record immediately
7034 if (mSyncStartEvent->isCancelled()) {
7035 clearSyncStartEvent();
7036 } else {
7037 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
7038 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
7039 }
Eric Laurenta011e352012-03-29 15:51:43 -07007040 }
7041
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08007043 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044 if (mActiveTrack != 0) {
7045 if (recordTrack != mActiveTrack.get()) {
7046 status = -EBUSY;
7047 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
7048 mActiveTrack->mState = TrackBase::ACTIVE;
7049 }
7050 return status;
7051 }
7052
7053 recordTrack->mState = TrackBase::IDLE;
7054 mActiveTrack = recordTrack;
7055 mLock.unlock();
7056 status_t status = AudioSystem::startInput(mId);
7057 mLock.lock();
7058 if (status != NO_ERROR) {
7059 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07007060 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 return status;
7062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063 mRsmpInIndex = mFrameCount;
7064 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08007065 if (mResampler != NULL) {
7066 mResampler->reset();
7067 }
7068 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01007070 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07007071 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08007073 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 mActiveTrack.clear();
7075 status = INVALID_OPERATION;
7076 goto startError;
7077 }
7078 mStartStopCond.wait(mLock);
7079 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007080 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 status = BAD_VALUE;
7082 goto startError;
7083 }
Steve Block3856b092011-10-20 11:56:00 +01007084 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 return status;
7086 }
7087startError:
7088 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07007089 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090 return status;
7091}
7092
Eric Laurenta011e352012-03-29 15:51:43 -07007093void AudioFlinger::RecordThread::clearSyncStartEvent()
7094{
7095 if (mSyncStartEvent != 0) {
7096 mSyncStartEvent->cancel();
7097 }
7098 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07007099 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07007100}
7101
7102void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7103{
7104 sp<SyncEvent> strongEvent = event.promote();
7105
7106 if (strongEvent != 0) {
7107 RecordThread *me = (RecordThread *)strongEvent->cookie();
7108 me->handleSyncStartEvent(strongEvent);
7109 }
7110}
7111
7112void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
7113{
Eric Laurent29864602012-05-08 18:57:51 -07007114 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07007115 // TODO: use actual buffer filling status instead of 2 buffers when info is available
7116 // from audio HAL
7117 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07007118 }
7119}
7120
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007121bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01007122 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007123 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
7124 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07007126 recordTrack->mState = TrackBase::PAUSING;
7127 // do not wait for mStartStopCond if exiting
7128 if (exitPending()) {
7129 return true;
7130 }
7131 mStartStopCond.wait(mLock);
7132 // if we have been restarted, recordTrack == mActiveTrack.get() here
7133 if (exitPending() || recordTrack != mActiveTrack.get()) {
7134 ALOGV("Record stopped OK");
7135 return true;
7136 }
7137 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138}
7139
Glenn Kasten106e8a42012-08-02 13:37:12 -07007140bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07007141{
7142 return false;
7143}
7144
7145status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
7146{
Glenn Kasten7aa25592012-08-02 16:37:07 -07007147#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 -07007148 if (!isValidSyncEvent(event)) {
7149 return BAD_VALUE;
7150 }
7151
Glenn Kasten510a3d62012-07-16 14:24:34 -07007152 int eventSession = event->triggerSession();
7153 status_t ret = NAME_NOT_FOUND;
7154
Eric Laurenta011e352012-03-29 15:51:43 -07007155 Mutex::Autolock _l(mLock);
7156
Glenn Kasten510a3d62012-07-16 14:24:34 -07007157 for (size_t i = 0; i < mTracks.size(); i++) {
7158 sp<RecordTrack> track = mTracks[i];
7159 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07007160 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007161 ret = NO_ERROR;
7162 }
Eric Laurenta011e352012-03-29 15:51:43 -07007163 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007164 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07007165#else
7166 return BAD_VALUE;
7167#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07007168}
7169
7170void AudioFlinger::RecordThread::RecordTrack::destroy()
7171{
7172 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
7173 sp<RecordTrack> keep(this);
7174 {
7175 sp<ThreadBase> thread = mThread.promote();
7176 if (thread != 0) {
7177 if (mState == ACTIVE || mState == RESUMING) {
7178 AudioSystem::stopInput(thread->id());
7179 }
7180 AudioSystem::releaseInput(thread->id());
7181 Mutex::Autolock _l(thread->mLock);
7182 RecordThread *recordThread = (RecordThread *) thread.get();
7183 recordThread->destroyTrack_l(this);
7184 }
7185 }
7186}
7187
7188// destroyTrack_l() must be called with ThreadBase::mLock held
7189void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7190{
7191 track->mState = TrackBase::TERMINATED;
7192 // active tracks are removed by threadLoop()
7193 if (mActiveTrack != track) {
7194 removeTrack_l(track);
7195 }
7196}
7197
7198void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7199{
7200 mTracks.remove(track);
7201 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07007202}
7203
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07007204void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007206 dumpInternals(fd, args);
7207 dumpTracks(fd, args);
7208 dumpEffectChains(fd, args);
7209}
7210
7211void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7212{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 const size_t SIZE = 256;
7214 char buffer[SIZE];
7215 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216
7217 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
7218 result.append(buffer);
7219
7220 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
7222 result.append(buffer);
7223 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
7224 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08007225 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 result.append(buffer);
7227 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
7228 result.append(buffer);
7229 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
7230 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07007232 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007233 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07007234
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235 write(fd, result.string(), result.size());
7236
7237 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007238}
7239
7240void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
7241{
7242 const size_t SIZE = 256;
7243 char buffer[SIZE];
7244 String8 result;
7245
7246 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
7247 result.append(buffer);
7248 RecordTrack::appendDumpHeader(result);
7249 for (size_t i = 0; i < mTracks.size(); ++i) {
7250 sp<RecordTrack> track = mTracks[i];
7251 if (track != 0) {
7252 track->dump(buffer, SIZE);
7253 result.append(buffer);
7254 }
7255 }
7256
7257 if (mActiveTrack != 0) {
7258 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
7259 result.append(buffer);
7260 RecordTrack::appendDumpHeader(result);
7261 mActiveTrack->dump(buffer, SIZE);
7262 result.append(buffer);
7263
7264 }
7265 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266}
7267
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007268// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08007269status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270{
7271 size_t framesReq = buffer->frameCount;
7272 size_t framesReady = mFrameCount - mRsmpInIndex;
7273 int channelCount;
7274
7275 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007276 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07007277 if (mBytesRead <= 0) {
7278 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
7279 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280 // Force input into standby so that it tries to
7281 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07007282 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007283 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 }
Glenn Kastene0feee32011-12-13 11:53:26 -08007285 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 buffer->frameCount = 0;
7287 return NOT_ENOUGH_DATA;
7288 }
7289 mRsmpInIndex = 0;
7290 framesReady = mFrameCount;
7291 }
7292
7293 if (framesReq > framesReady) {
7294 framesReq = framesReady;
7295 }
7296
7297 if (mChannelCount == 1 && mReqChannelCount == 2) {
7298 channelCount = 1;
7299 } else {
7300 channelCount = 2;
7301 }
7302 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
7303 buffer->frameCount = framesReq;
7304 return NO_ERROR;
7305}
7306
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08007307// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
7309{
7310 mRsmpInIndex += buffer->frameCount;
7311 buffer->frameCount = 0;
7312}
7313
7314bool AudioFlinger::RecordThread::checkForNewParameters_l()
7315{
7316 bool reconfig = false;
7317
7318 while (!mNewParameters.isEmpty()) {
7319 status_t status = NO_ERROR;
7320 String8 keyValuePair = mNewParameters[0];
7321 AudioParameter param = AudioParameter(keyValuePair);
7322 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08007323 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 int reqSamplingRate = mReqSampleRate;
7325 int reqChannelCount = mReqChannelCount;
7326
7327 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7328 reqSamplingRate = value;
7329 reconfig = true;
7330 }
7331 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08007332 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333 reconfig = true;
7334 }
7335 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
vivek mehta2192bc92012-12-04 11:46:08 -08007336 reqChannelCount = getInputChannelCount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 reconfig = true;
7338 }
7339 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7340 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08007341 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 // if frame count is changed after track creation
7343 if (mActiveTrack != 0) {
7344 status = INVALID_OPERATION;
7345 } else {
7346 reconfig = true;
7347 }
7348 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007349 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7350 // forward device change to effects that have requested to be
7351 // aware of attached audio device.
7352 for (size_t i = 0; i < mEffectChains.size(); i++) {
7353 mEffectChains[i]->setDevice_l(value);
7354 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07007355
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007356 // store input device and output device but do not forward output device to audio HAL.
7357 // Note that status is ignored by the caller for output device
7358 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07007359 if (audio_is_output_devices(value)) {
7360 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007361 status = BAD_VALUE;
7362 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007363 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007364 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07007365 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07007366 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7367 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07007368 for (size_t i = 0; i < mTracks.size(); i++) {
7369 sp<RecordTrack> track = mTracks[i];
7370 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7371 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7372 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07007373 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007374 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007375 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07007376 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7377 mAudioSource != (audio_source_t)value) {
7378 // forward device change to effects that have requested to be
7379 // aware of attached audio device.
7380 for (size_t i = 0; i < mEffectChains.size(); i++) {
7381 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7382 }
7383 mAudioSource = (audio_source_t)value;
7384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007386 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07007388 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007389 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7390 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391 }
7392 if (reconfig) {
7393 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007394 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07007395 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07007396 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007397 getInputChannelCount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08007398 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 status = NO_ERROR;
7400 }
7401 if (status == NO_ERROR) {
7402 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07007403 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404 }
7405 }
7406 }
7407
7408 mNewParameters.removeAt(0);
7409
7410 mParamStatus = status;
7411 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07007412 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
7413 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08007414 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 }
7416 return reconfig;
7417}
7418
7419String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7420{
Dima Zavinfce7a472011-04-19 22:30:36 -07007421 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007422 String8 out_s8 = String8();
7423
7424 Mutex::Autolock _l(mLock);
7425 if (initCheck() != NO_ERROR) {
7426 return out_s8;
7427 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007428
Dima Zavin799a70e2011-04-18 16:57:27 -07007429 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07007430 out_s8 = String8(s);
7431 free(s);
7432 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433}
7434
7435void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
7436 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08007437 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438
7439 switch (event) {
7440 case AudioSystem::INPUT_OPENED:
7441 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007442 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 desc.samplingRate = mSampleRate;
7444 desc.format = mFormat;
7445 desc.frameCount = mFrameCount;
7446 desc.latency = 0;
7447 param2 = &desc;
7448 break;
7449
7450 case AudioSystem::INPUT_CLOSED:
7451 default:
7452 break;
7453 }
7454 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
7455}
7456
7457void AudioFlinger::RecordThread::readInputParameters()
7458{
Glenn Kastene9dd0172012-01-27 18:08:45 -08007459 delete mRsmpInBuffer;
7460 // mRsmpInBuffer is always assigned a new[] below
7461 delete mRsmpOutBuffer;
7462 mRsmpOutBuffer = NULL;
7463 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08007464 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465
Dima Zavin799a70e2011-04-18 16:57:27 -07007466 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07007467 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
vivek mehta2192bc92012-12-04 11:46:08 -08007468 mChannelCount = (uint16_t)getInputChannelCount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07007469 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08007470 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07007471 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07007473 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
7475
Glenn Kasten53d76db2012-03-08 12:32:47 -08007476 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477 {
7478 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007479 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
7480 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 if (mChannelCount == 1 && mReqChannelCount == 2) {
7482 channelCount = 1;
7483 } else {
7484 channelCount = 2;
7485 }
7486 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
7487 mResampler->setSampleRate(mSampleRate);
7488 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
7489 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
7490
7491 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
7492 if (mChannelCount == 1 && mReqChannelCount == 1) {
7493 mFrameCount >>= 1;
7494 }
7495
7496 }
7497 mRsmpInIndex = mFrameCount;
7498}
7499
7500unsigned int AudioFlinger::RecordThread::getInputFramesLost()
7501{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007502 Mutex::Autolock _l(mLock);
7503 if (initCheck() != NO_ERROR) {
7504 return 0;
7505 }
7506
Dima Zavin799a70e2011-04-18 16:57:27 -07007507 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508}
7509
Glenn Kasten106e8a42012-08-02 13:37:12 -07007510uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007511{
7512 Mutex::Autolock _l(mLock);
7513 uint32_t result = 0;
7514 if (getEffectChain_l(sessionId) != 0) {
7515 result = EFFECT_SESSION;
7516 }
7517
Glenn Kasten510a3d62012-07-16 14:24:34 -07007518 for (size_t i = 0; i < mTracks.size(); ++i) {
7519 if (sessionId == mTracks[i]->sessionId()) {
7520 result |= TRACK_SESSION;
7521 break;
7522 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007523 }
7524
7525 return result;
7526}
7527
Glenn Kasten106e8a42012-08-02 13:37:12 -07007528KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07007529{
Glenn Kasten510a3d62012-07-16 14:24:34 -07007530 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007531 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07007532 for (size_t j = 0; j < mTracks.size(); ++j) {
7533 sp<RecordThread::RecordTrack> track = mTracks[j];
7534 int sessionId = track->sessionId();
7535 if (ids.indexOfKey(sessionId) < 0) {
7536 ids.add(sessionId, true);
7537 }
7538 }
7539 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07007540}
7541
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007542AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7543{
7544 Mutex::Autolock _l(mLock);
7545 AudioStreamIn *input = mInput;
7546 mInput = NULL;
7547 return input;
7548}
7549
7550// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08007551audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007552{
7553 if (mInput == NULL) {
7554 return NULL;
7555 }
7556 return &mInput->stream->common;
7557}
7558
7559
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560// ----------------------------------------------------------------------------
7561
Eric Laurenta4c5a552012-03-29 10:12:40 -07007562audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
7563{
7564 if (!settingsAllowed()) {
7565 return 0;
7566 }
7567 Mutex::Autolock _l(mLock);
7568 return loadHwModule_l(name);
7569}
7570
7571// loadHwModule_l() must be called with AudioFlinger::mLock held
7572audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
7573{
7574 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
7575 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
7576 ALOGW("loadHwModule() module %s already loaded", name);
7577 return mAudioHwDevs.keyAt(i);
7578 }
7579 }
7580
Eric Laurenta4c5a552012-03-29 10:12:40 -07007581 audio_hw_device_t *dev;
7582
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007583 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007584 if (rc) {
7585 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
7586 return 0;
7587 }
7588
7589 mHardwareStatus = AUDIO_HW_INIT;
7590 rc = dev->init_check(dev);
7591 mHardwareStatus = AUDIO_HW_IDLE;
7592 if (rc) {
7593 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
7594 return 0;
7595 }
7596
John Grossmanee578c02012-07-23 17:05:46 -07007597 // Check and cache this HAL's level of support for master mute and master
7598 // volume. If this is the first HAL opened, and it supports the get
7599 // methods, use the initial values provided by the HAL as the current
7600 // master mute and volume settings.
7601
7602 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
7603 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07007604 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07007605
madmack2f8d3672013-01-14 21:19:20 -05007606#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007607 if (0 == mAudioHwDevs.size()) {
7608 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
7609 if (NULL != dev->get_master_volume) {
7610 float mv;
7611 if (OK == dev->get_master_volume(dev, &mv)) {
7612 mMasterVolume = mv;
7613 }
7614 }
7615
7616 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
7617 if (NULL != dev->get_master_mute) {
7618 bool mm;
7619 if (OK == dev->get_master_mute(dev, &mm)) {
7620 mMasterMute = mm;
7621 }
7622 }
7623 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007624#endif
John Grossmanee578c02012-07-23 17:05:46 -07007625
Eric Laurenta4c5a552012-03-29 10:12:40 -07007626 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07007627 if ((NULL != dev->set_master_volume) &&
7628 (OK == dev->set_master_volume(dev, mMasterVolume))) {
7629 flags = static_cast<AudioHwDevice::Flags>(flags |
7630 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
7631 }
7632
madmack2f8d3672013-01-14 21:19:20 -05007633#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
John Grossmanee578c02012-07-23 17:05:46 -07007634 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
7635 if ((NULL != dev->set_master_mute) &&
7636 (OK == dev->set_master_mute(dev, mMasterMute))) {
7637 flags = static_cast<AudioHwDevice::Flags>(flags |
7638 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
7639 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007640#endif
John Grossmanee578c02012-07-23 17:05:46 -07007641
Eric Laurenta4c5a552012-03-29 10:12:40 -07007642 mHardwareStatus = AUDIO_HW_IDLE;
7643 }
7644
7645 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007646 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007647
7648 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007649 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007650
7651 return handle;
7652
7653}
7654
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07007655// ----------------------------------------------------------------------------
7656
7657int32_t AudioFlinger::getPrimaryOutputSamplingRate()
7658{
7659 Mutex::Autolock _l(mLock);
7660 PlaybackThread *thread = primaryPlaybackThread_l();
7661 return thread != NULL ? thread->sampleRate() : 0;
7662}
7663
7664int32_t AudioFlinger::getPrimaryOutputFrameCount()
7665{
7666 Mutex::Autolock _l(mLock);
7667 PlaybackThread *thread = primaryPlaybackThread_l();
7668 return thread != NULL ? thread->frameCountHAL() : 0;
7669}
7670
7671// ----------------------------------------------------------------------------
7672
Eric Laurenta4c5a552012-03-29 10:12:40 -07007673audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7674 audio_devices_t *pDevices,
7675 uint32_t *pSamplingRate,
7676 audio_format_t *pFormat,
7677 audio_channel_mask_t *pChannelMask,
7678 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007679 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007680{
7681 status_t status;
7682 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007683 struct audio_config config = {
7684 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7685 channel_mask: pChannelMask ? *pChannelMask : 0,
7686 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7687 };
7688 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007689 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690
Eric Laurenta4c5a552012-03-29 10:12:40 -07007691 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7692 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007693 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007694 config.sample_rate,
7695 config.format,
7696 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007697 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698
7699 if (pDevices == NULL || *pDevices == 0) {
7700 return 0;
7701 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007702
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 Mutex::Autolock _l(mLock);
7704
Eric Laurenta4c5a552012-03-29 10:12:40 -07007705 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007706 if (outHwDev == NULL)
7707 return 0;
7708
John Grossmanee578c02012-07-23 17:05:46 -07007709 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007710 audio_io_handle_t id = nextUniqueId();
7711
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007712 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007713
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007714#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007715 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007716 id,
7717 *pDevices,
7718 (audio_output_flags_t)flags,
7719 &config,
7720 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007721#else
7722 status = hwDevHal->open_output_stream(hwDevHal,
7723 *pDevices,
7724 (int *)&config.format,
7725 &config.channel_mask,
7726 &config.sample_rate,
7727 &outStream);
7728 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7729 flags = (audio_output_flags_t)newflags;
7730#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007731
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007732 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007733 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007734 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007735 config.sample_rate,
7736 config.format,
7737 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738 status);
7739
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007740 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007741 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
vivek mehta2192bc92012-12-04 11:46:08 -08007742#ifdef QCOM_HARDWARE
7743 if (flags & AUDIO_OUTPUT_FLAG_LPA || flags & AUDIO_OUTPUT_FLAG_TUNNEL ) {
7744 AudioSessionDescriptor *desc = new AudioSessionDescriptor(hwDevHal, outStream, flags);
7745 desc->mActive = true;
7746 //TODO: no stream type
7747 //desc->mStreamType = streamType;
7748 desc->mVolumeLeft = 1.0;
7749 desc->mVolumeRight = 1.0;
7750 desc->device = *pDevices;
7751 mDirectAudioTracks.add(id, desc);
7752 } else
7753#endif
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007754 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007755 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7756 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007758 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 } else {
7760 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007761 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 }
vivek mehta2192bc92012-12-04 11:46:08 -08007763#ifdef QCOM_HARDWARE
7764 if (thread != NULL)
7765#endif
7766 mPlaybackThreads.add(id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767
Dorian Snyderf32d5702013-03-01 14:25:46 -08007768#ifdef QCOM_HARDWARE
7769 // if the device is a A2DP, then this is an A2DP Output
7770 if ( true == audio_is_a2dp_device((audio_devices_t) *pDevices) )
7771 {
7772 mA2DPHandle = id;
7773 ALOGV("A2DP device activated. The handle is set to %d", mA2DPHandle);
7774 }
7775#endif
7776
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007777 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7778 if (pFormat != NULL) *pFormat = config.format;
7779 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
vivek mehta2192bc92012-12-04 11:46:08 -08007780#ifdef QCOM_HARDWARE
7781 if (thread != NULL) {
7782#endif
7783 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
7784 // notify client processes of the new output creation
7785 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7786#ifdef QCOM_HARDWARE
7787 }
7788 else {
7789 *pLatencyMs = 0;
7790 if ((flags & AUDIO_OUTPUT_FLAG_LPA) || (flags & AUDIO_OUTPUT_FLAG_TUNNEL)) {
7791 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(id);
7792 *pLatencyMs = desc->stream->get_latency(desc->stream);
7793 }
7794 }
7795#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007796 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007797 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007798 ALOGI("Using module %d has the primary audio interface", module);
7799 mPrimaryHardwareDev = outHwDev;
7800
7801 AutoMutex lock(mHardwareLock);
7802 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007803 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007804 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 return id;
7807 }
7808
7809 return 0;
7810}
7811
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007812audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7813 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814{
7815 Mutex::Autolock _l(mLock);
7816 MixerThread *thread1 = checkMixerThread_l(output1);
7817 MixerThread *thread2 = checkMixerThread_l(output2);
7818
7819 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007820 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007821 return 0;
7822 }
7823
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007824 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7826 thread->addOutputTrack(thread2);
7827 mPlaybackThreads.add(id, thread);
7828 // notify client processes of the new output creation
7829 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7830 return id;
7831}
7832
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007833status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834{
Glenn Kastend96c5722012-04-25 13:44:49 -07007835 return closeOutput_nonvirtual(output);
7836}
7837
7838status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7839{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840 // keep strong reference on the playback thread so that
7841 // it is not destroyed while exit() is executed
vivek mehta2192bc92012-12-04 11:46:08 -08007842#ifdef QCOM_HARDWARE
7843 AudioSessionDescriptor *desc = mDirectAudioTracks.valueFor(output);
7844 if (desc) {
7845 ALOGV("Closing DirectTrack output %d", output);
7846 desc->mActive = false;
7847 desc->stream->common.standby(&desc->stream->common);
7848 desc->hwDev->close_output_stream(desc->hwDev, desc->stream);
7849 desc->trackRefPtr = NULL;
7850 mDirectAudioTracks.removeItem(output);
7851 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
7852 delete desc;
7853 return NO_ERROR;
7854 }
7855#endif
7856
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007857 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007858 {
7859 Mutex::Autolock _l(mLock);
7860 thread = checkPlaybackThread_l(output);
7861 if (thread == NULL) {
7862 return BAD_VALUE;
7863 }
7864
Steve Block3856b092011-10-20 11:56:00 +01007865 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007867 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007869 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7871 dupThread->removeOutputTrack((MixerThread *)thread.get());
7872 }
7873 }
7874 }
Glenn Kastena1117922012-01-26 10:53:32 -08007875 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 mPlaybackThreads.removeItem(output);
Dorian Snyderf32d5702013-03-01 14:25:46 -08007877#ifdef QCOM_HARDWARE
7878 if (mA2DPHandle == output)
7879 {
7880 mA2DPHandle = -1;
7881 ALOGV("A2DP OutputClosed Notifying Client");
7882 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &mA2DPHandle);
7883 }
7884#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 }
7886 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007887 // The thread entity (active unit of execution) is no longer running here,
7888 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007890 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007891 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007892 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007893 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007894 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007895 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 }
7897 return NO_ERROR;
7898}
7899
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007900status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901{
7902 Mutex::Autolock _l(mLock);
7903 PlaybackThread *thread = checkPlaybackThread_l(output);
7904
7905 if (thread == NULL) {
7906 return BAD_VALUE;
7907 }
7908
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 thread->suspend();
7911
7912 return NO_ERROR;
7913}
7914
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007915status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916{
7917 Mutex::Autolock _l(mLock);
7918 PlaybackThread *thread = checkPlaybackThread_l(output);
7919
7920 if (thread == NULL) {
7921 return BAD_VALUE;
7922 }
7923
Steve Block3856b092011-10-20 11:56:00 +01007924 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925
7926 thread->restore();
7927
7928 return NO_ERROR;
7929}
7930
Eric Laurenta4c5a552012-03-29 10:12:40 -07007931audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7932 audio_devices_t *pDevices,
7933 uint32_t *pSamplingRate,
7934 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007935 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007936{
7937 status_t status;
7938 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007939 struct audio_config config = {
7940 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7941 channel_mask: pChannelMask ? *pChannelMask : 0,
7942 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7943 };
7944 uint32_t reqSamplingRate = config.sample_rate;
7945 audio_format_t reqFormat = config.format;
7946 audio_channel_mask_t reqChannels = config.channel_mask;
7947 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007948 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949
7950 if (pDevices == NULL || *pDevices == 0) {
7951 return 0;
7952 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007953
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 Mutex::Autolock _l(mLock);
7955
Eric Laurenta4c5a552012-03-29 10:12:40 -07007956 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007957 if (inHwDev == NULL)
7958 return 0;
7959
John Grossmanee578c02012-07-23 17:05:46 -07007960 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007961 audio_io_handle_t id = nextUniqueId();
7962
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007963#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007964 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007965 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007966#else
7967 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7968 (int *)&config.format,
7969 &config.channel_mask,
7970 &config.sample_rate, (audio_in_acoustics_t)0,
7971 &inStream);
7972#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007973 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007974 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007975 config.sample_rate,
7976 config.format,
7977 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 status);
7979
7980 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7981 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7982 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007983 if (status == BAD_VALUE &&
7984 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7985 (config.sample_rate <= 2 * reqSamplingRate) &&
vivek mehta2192bc92012-12-04 11:46:08 -08007986 (getInputChannelCount(config.channel_mask) <= FCC_2) && (getInputChannelCount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007987 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007988 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007989#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007990 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007991#else
7992 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7993 (int *)&config.format,
7994 &config.channel_mask,
7995 &config.sample_rate, (audio_in_acoustics_t)0,
7996 &inStream);
7997#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007998 }
7999
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07008000 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07008001 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
8002
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008003 // Start record thread
8004 // RecorThread require both input and output device indication to forward to audio
8005 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008006 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008007 thread = new RecordThread(this,
8008 input,
8009 reqSamplingRate,
8010 reqChannels,
8011 id,
8012 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01008014 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08008015 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07008016 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07008017 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019 // notify client processes of the new input creation
8020 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
8021 return id;
8022 }
8023
8024 return 0;
8025}
8026
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008027status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008028{
Glenn Kastend96c5722012-04-25 13:44:49 -07008029 return closeInput_nonvirtual(input);
8030}
8031
8032status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
8033{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008034 // keep strong reference on the record thread so that
8035 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008036 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 {
8038 Mutex::Autolock _l(mLock);
8039 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07008040 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008041 return BAD_VALUE;
8042 }
8043
Steve Block3856b092011-10-20 11:56:00 +01008044 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08008045 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 mRecordThreads.removeItem(input);
8047 }
8048 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08008049 // The thread entity (active unit of execution) is no longer running here,
8050 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008052 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08008053 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008054 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07008055 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07008056 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057
8058 return NO_ERROR;
8059}
8060
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008061status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062{
8063 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008064 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065
8066 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8067 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07008068 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07008069 }
Dorian Snyderf32d5702013-03-01 14:25:46 -08008070#ifdef QCOM_HARDWARE
8071 if ( mA2DPHandle == output ) {
8072 ALOGV("A2DP Activated and hence notifying the client");
8073 audioConfigChanged_l(AudioSystem::A2DP_OUTPUT_STATE, mA2DPHandle, &output);
8074 }
8075#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076
8077 return NO_ERROR;
8078}
8079
8080
8081int AudioFlinger::newAudioSessionId()
8082{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008083 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084}
8085
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008086void AudioFlinger::acquireAudioSessionId(int audioSession)
8087{
8088 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008089 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008090 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008091 size_t num = mAudioSessionRefs.size();
8092 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008093 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008094 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8095 ref->mCnt++;
8096 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008097 return;
8098 }
8099 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08008100 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
8101 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008102}
8103
8104void AudioFlinger::releaseAudioSessionId(int audioSession)
8105{
8106 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08008107 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01008108 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008109 size_t num = mAudioSessionRefs.size();
8110 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008111 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008112 if (ref->mSessionid == audioSession && ref->mPid == caller) {
8113 ref->mCnt--;
8114 ALOGV(" decremented refcount to %d", ref->mCnt);
8115 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008116 mAudioSessionRefs.removeAt(i);
8117 delete ref;
8118 purgeStaleEffects_l();
8119 }
8120 return;
8121 }
8122 }
Steve Block5ff1dd52012-01-05 23:22:43 +00008123 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008124}
8125
8126void AudioFlinger::purgeStaleEffects_l() {
8127
Steve Block3856b092011-10-20 11:56:00 +01008128 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008129
8130 Vector< sp<EffectChain> > chains;
8131
8132 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8133 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
8134 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8135 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07008136 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
8137 chains.push(ec);
8138 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008139 }
8140 }
8141 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8142 sp<RecordThread> t = mRecordThreads.valueAt(i);
8143 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
8144 sp<EffectChain> ec = t->mEffectChains[j];
8145 chains.push(ec);
8146 }
8147 }
8148
8149 for (size_t i = 0; i < chains.size(); i++) {
8150 sp<EffectChain> ec = chains[i];
8151 int sessionid = ec->sessionId();
8152 sp<ThreadBase> t = ec->mThread.promote();
8153 if (t == 0) {
8154 continue;
8155 }
8156 size_t numsessionrefs = mAudioSessionRefs.size();
8157 bool found = false;
8158 for (size_t k = 0; k < numsessionrefs; k++) {
8159 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08008160 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01008161 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008162 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008163 found = true;
8164 break;
8165 }
8166 }
8167 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008168 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008169 // remove all effects from the chain
8170 while (ec->mEffects.size()) {
8171 sp<EffectModule> effect = ec->mEffects[0];
8172 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008173 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008174 if (effect->purgeHandles()) {
8175 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008176 }
8177 AudioSystem::unregisterEffect(effect->id());
8178 }
8179 }
8180 }
8181 return;
8182}
8183
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008185AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186{
Glenn Kastena1117922012-01-26 10:53:32 -08008187 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188}
8189
8190// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008191AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008192{
8193 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08008194 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195}
8196
8197// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008198AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199{
Glenn Kastena1117922012-01-26 10:53:32 -08008200 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008201}
8202
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008203uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07008204{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008205 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206}
8207
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08008208AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008209{
8210 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8211 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008212 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07008213 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008214 return thread;
8215 }
8216 }
8217 return NULL;
8218}
8219
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008220audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008221{
8222 PlaybackThread *thread = primaryPlaybackThread_l();
8223
8224 if (thread == NULL) {
8225 return 0;
8226 }
8227
Eric Laurentf1c04f92012-08-28 14:26:53 -07008228 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008229}
8230
Eric Laurenta011e352012-03-29 15:51:43 -07008231sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
8232 int triggerSession,
8233 int listenerSession,
8234 sync_event_callback_t callBack,
8235 void *cookie)
8236{
8237 Mutex::Autolock _l(mLock);
8238
8239 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
8240 status_t playStatus = NAME_NOT_FOUND;
8241 status_t recStatus = NAME_NOT_FOUND;
8242 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8243 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
8244 if (playStatus == NO_ERROR) {
8245 return event;
8246 }
8247 }
8248 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8249 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
8250 if (recStatus == NO_ERROR) {
8251 return event;
8252 }
8253 }
8254 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
8255 mPendingSyncEvents.add(event);
8256 } else {
8257 ALOGV("createSyncEvent() invalid event %d", event->type());
8258 event.clear();
8259 }
8260 return event;
8261}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008262
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263// ----------------------------------------------------------------------------
8264// Effect management
8265// ----------------------------------------------------------------------------
8266
8267
Glenn Kastenf587ba52012-01-26 16:25:10 -08008268status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008269{
8270 Mutex::Autolock _l(mLock);
8271 return EffectQueryNumberEffects(numEffects);
8272}
8273
Glenn Kastenf587ba52012-01-26 16:25:10 -08008274status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008275{
8276 Mutex::Autolock _l(mLock);
8277 return EffectQueryEffect(index, descriptor);
8278}
8279
Glenn Kasten5e92a782012-01-30 07:40:52 -08008280status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08008281 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008282{
8283 Mutex::Autolock _l(mLock);
8284 return EffectGetDescriptor(pUuid, descriptor);
8285}
8286
8287
Mathias Agopian65ab4712010-07-14 17:59:35 -07008288sp<IEffect> AudioFlinger::createEffect(pid_t pid,
8289 effect_descriptor_t *pDesc,
8290 const sp<IEffectClient>& effectClient,
8291 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008292 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 int sessionId,
8294 status_t *status,
8295 int *id,
8296 int *enabled)
8297{
8298 status_t lStatus = NO_ERROR;
8299 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008300 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008301
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008302 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008303 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304
8305 if (pDesc == NULL) {
8306 lStatus = BAD_VALUE;
8307 goto Exit;
8308 }
8309
Eric Laurent84e9a102010-09-23 16:10:16 -07008310 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008311 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008312 lStatus = PERMISSION_DENIED;
8313 goto Exit;
8314 }
8315
Dima Zavinfce7a472011-04-19 22:30:36 -07008316 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07008317 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08008318 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008319 lStatus = PERMISSION_DENIED;
8320 goto Exit;
8321 }
8322
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008323 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07008324 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008325 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07008326 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07008327 lStatus = BAD_VALUE;
8328 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07008329 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07008330 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008331 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07008332 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008333 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07008334 }
8335 }
8336
Mathias Agopian65ab4712010-07-14 17:59:35 -07008337 {
8338 Mutex::Autolock _l(mLock);
8339
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340
8341 if (!EffectIsNullUuid(&pDesc->uuid)) {
8342 // if uuid is specified, request effect descriptor
8343 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
8344 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008345 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346 goto Exit;
8347 }
8348 } else {
8349 // if uuid is not specified, look for an available implementation
8350 // of the required type in effect factory
8351 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008352 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008353 lStatus = BAD_VALUE;
8354 goto Exit;
8355 }
8356 uint32_t numEffects = 0;
8357 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008358 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 bool found = false;
8360
8361 lStatus = EffectQueryNumberEffects(&numEffects);
8362 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008363 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364 goto Exit;
8365 }
8366 for (uint32_t i = 0; i < numEffects; i++) {
8367 lStatus = EffectQueryEffect(i, &desc);
8368 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008369 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008370 continue;
8371 }
8372 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
8373 // If matching type found save effect descriptor. If the session is
8374 // 0 and the effect is not auxiliary, continue enumeration in case
8375 // an auxiliary version of this effect type is available
8376 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08008377 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07008378 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008379 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8380 break;
8381 }
8382 }
8383 }
8384 if (!found) {
8385 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00008386 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 goto Exit;
8388 }
8389 // For same effect type, chose auxiliary version over insert version if
8390 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07008391 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08008393 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394 }
8395 }
8396
8397 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07008398 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8400 lStatus = INVALID_OPERATION;
8401 goto Exit;
8402 }
8403
Eric Laurent59255e42011-07-27 19:49:51 -07008404 // check recording permission for visualizer
8405 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
8406 !recordingAllowed()) {
8407 lStatus = PERMISSION_DENIED;
8408 goto Exit;
8409 }
8410
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08008412 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413
8414 // If output is not specified try to find a matching audio session ID in one of the
8415 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07008416 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
8417 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008418 // Note: io is never 0 when creating an effect on an input
8419 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008420 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07008421 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
8422 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008423 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07008424 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07008425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008427 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008428 for (size_t i = 0; i < mRecordThreads.size(); i++) {
8429 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
8430 io = mRecordThreads.keyAt(i);
8431 break;
8432 }
8433 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008434 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008435 // If no output thread contains the requested session ID, default to
8436 // first output. The effect chain will be moved to the correct output
8437 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008438 if (io == 0 && mPlaybackThreads.size()) {
8439 io = mPlaybackThreads.keyAt(0);
8440 }
Steve Block3856b092011-10-20 11:56:00 +01008441 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008442 }
8443 ThreadBase *thread = checkRecordThread_l(io);
8444 if (thread == NULL) {
8445 thread = checkPlaybackThread_l(io);
8446 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00008447 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008448 lStatus = BAD_VALUE;
8449 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07008450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008451 }
Eric Laurent84e9a102010-09-23 16:10:16 -07008452
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008453 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008455 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07008456 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
8457 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008458 if (handle != 0 && id != NULL) {
8459 *id = handle->id();
8460 }
8461 }
8462
8463Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008464 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 *status = lStatus;
8466 }
8467 return handle;
8468}
8469
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008470status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
8471 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07008472{
Steve Block3856b092011-10-20 11:56:00 +01008473 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07008474 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008475 Mutex::Autolock _l(mLock);
8476 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008477 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008478 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479 }
Eric Laurentde070132010-07-13 04:45:46 -07008480 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
8481 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008482 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008483 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008484 }
Eric Laurentde070132010-07-13 04:45:46 -07008485 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
8486 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008487 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07008488 return BAD_VALUE;
8489 }
8490
8491 Mutex::Autolock _dl(dstThread->mLock);
8492 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07008493 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07008494
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 return NO_ERROR;
8496}
8497
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008498// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07008499status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07008500 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07008501 AudioFlinger::PlaybackThread *dstThread,
8502 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07008503{
Steve Block3856b092011-10-20 11:56:00 +01008504 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008505 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07008506
Eric Laurent59255e42011-07-27 19:49:51 -07008507 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008508 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008509 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07008510 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07008511 return INVALID_OPERATION;
8512 }
8513
Eric Laurent39e94f82010-07-28 01:32:47 -07008514 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07008515 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07008516 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07008517 // removed.
8518 srcThread->removeEffectChain_l(chain);
8519
8520 // transfer all effects one by one so that new effect chain is created on new thread with
8521 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08008522 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07008523 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008524 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07008525 sp<EffectModule> effect = chain->getEffectFromId_l(0);
8526 while (effect != 0) {
8527 srcThread->removeEffect_l(effect);
8528 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07008529 // removeEffect_l() has stopped the effect if it was active so it must be restarted
8530 if (effect->state() == EffectModule::ACTIVE ||
8531 effect->state() == EffectModule::STOPPING) {
8532 effect->start();
8533 }
Eric Laurent39e94f82010-07-28 01:32:47 -07008534 // if the move request is not received from audio policy manager, the effect must be
8535 // re-registered with the new strategy and output
8536 if (dstChain == 0) {
8537 dstChain = effect->chain().promote();
8538 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008539 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07008540 srcThread->addEffect_l(effect);
8541 return NO_INIT;
8542 }
8543 strategy = dstChain->strategy();
8544 }
8545 if (reRegister) {
8546 AudioSystem::unregisterEffect(effect->id());
8547 AudioSystem::registerEffect(&effect->desc(),
8548 dstOutput,
8549 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07008550 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07008551 effect->id());
8552 }
Eric Laurentde070132010-07-13 04:45:46 -07008553 effect = chain->getEffectFromId_l(0);
8554 }
8555
8556 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557}
8558
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008559
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008561sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07008562 const sp<AudioFlinger::Client>& client,
8563 const sp<IEffectClient>& effectClient,
8564 int32_t priority,
8565 int sessionId,
8566 effect_descriptor_t *desc,
8567 int *enabled,
8568 status_t *status
8569 )
8570{
8571 sp<EffectModule> effect;
8572 sp<EffectHandle> handle;
8573 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008574 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07008575 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576 bool effectCreated = false;
8577 bool effectRegistered = false;
8578
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008579 lStatus = initCheck();
8580 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008581 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582 goto Exit;
8583 }
8584
8585 // Do not allow effects with session ID 0 on direct output or duplicating threads
8586 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07008587 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008588 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07008589 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 lStatus = BAD_VALUE;
8591 goto Exit;
8592 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008593 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08008594 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008595 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008596 desc->name, desc->flags, mType);
8597 lStatus = BAD_VALUE;
8598 goto Exit;
8599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600
Steve Block3856b092011-10-20 11:56:00 +01008601 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008602
8603 { // scope for mLock
8604 Mutex::Autolock _l(mLock);
8605
8606 // check for existing effect chain with the requested audio session
8607 chain = getEffectChain_l(sessionId);
8608 if (chain == 0) {
8609 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008610 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008611 chain = new EffectChain(this, sessionId);
8612 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07008613 chain->setStrategy(getStrategyForSession_l(sessionId));
8614 chainCreated = true;
vivek mehta2192bc92012-12-04 11:46:08 -08008615#ifdef QCOM_HARDWARE
8616 if(sessionId == mAudioFlinger->mLPASessionId) {
8617 // Clear reference to previous effect chain if any
8618 if(mAudioFlinger->mLPAEffectChain.get()) {
8619 mAudioFlinger->mLPAEffectChain.clear();
8620 }
8621 ALOGV("New EffectChain is created for LPA session ID %d", sessionId);
8622 mAudioFlinger->mLPAEffectChain = chain;
8623 chain->setLPAFlag(true);
8624 // For LPA, the volume will be applied in DSP. No need for volume
8625 // control in the Effect chain, so setting it to unity.
8626 uint32_t volume = 0x1000000; // Equals to 1.0 in 8.24 format
8627 chain->setVolume_l(&volume,&volume);
8628 }
8629#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008630 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07008631 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632 }
8633
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08008634 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008635
8636 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008637 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008638 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07008639 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008640 if (lStatus != NO_ERROR) {
8641 goto Exit;
8642 }
8643 effectRegistered = true;
8644 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07008645 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008646 lStatus = effect->status();
8647 if (lStatus != NO_ERROR) {
8648 goto Exit;
8649 }
Eric Laurentcab11242010-07-15 12:50:15 -07008650 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651 if (lStatus != NO_ERROR) {
8652 goto Exit;
8653 }
8654 effectCreated = true;
8655
Eric Laurentf1c04f92012-08-28 14:26:53 -07008656 effect->setDevice(mOutDevice);
8657 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008658 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008659 effect->setAudioSource(mAudioSource);
vivek mehta2192bc92012-12-04 11:46:08 -08008660#ifdef QCOM_HARDWARE
8661 if(chain == mAudioFlinger->mLPAEffectChain) {
8662 effect->setLPAFlag(true);
8663 }
8664#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665 }
8666 // create effect handle and connect it to effect module
8667 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008668 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08008669 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 *enabled = (int)effect->isEnabled();
8671 }
8672 }
8673
8674Exit:
8675 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07008676 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008677 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07008678 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679 }
8680 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07008681 AudioSystem::unregisterEffect(effect->id());
8682 }
8683 if (chainCreated) {
8684 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008685 }
8686 handle.clear();
8687 }
8688
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008689 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 *status = lStatus;
8691 }
8692 return handle;
8693}
8694
Eric Laurent717e1282012-06-29 16:36:52 -07008695sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
8696{
8697 Mutex::Autolock _l(mLock);
8698 return getEffect_l(sessionId, effectId);
8699}
8700
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008701sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8702{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008703 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008704 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008705}
8706
Eric Laurentde070132010-07-13 04:45:46 -07008707// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8708// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008709status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008710{
8711 // check for existing effect chain with the requested audio session
8712 int sessionId = effect->sessionId();
8713 sp<EffectChain> chain = getEffectChain_l(sessionId);
8714 bool chainCreated = false;
8715
8716 if (chain == 0) {
8717 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008718 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008719 chain = new EffectChain(this, sessionId);
8720 addEffectChain_l(chain);
8721 chain->setStrategy(getStrategyForSession_l(sessionId));
8722 chainCreated = true;
8723 }
Steve Block3856b092011-10-20 11:56:00 +01008724 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008725
8726 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008727 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008728 this, effect->desc().name, chain.get());
8729 return BAD_VALUE;
8730 }
8731
8732 status_t status = chain->addEffect_l(effect);
8733 if (status != NO_ERROR) {
8734 if (chainCreated) {
8735 removeEffectChain_l(chain);
8736 }
8737 return status;
8738 }
8739
Eric Laurentf1c04f92012-08-28 14:26:53 -07008740 effect->setDevice(mOutDevice);
8741 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008742 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008743 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008744 return NO_ERROR;
8745}
8746
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008747void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008748
Steve Block3856b092011-10-20 11:56:00 +01008749 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008751 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8752 detachAuxEffect_l(effect->id());
8753 }
8754
8755 sp<EffectChain> chain = effect->chain().promote();
8756 if (chain != 0) {
8757 // remove effect chain if removing last effect
8758 if (chain->removeEffect_l(effect) == 0) {
8759 removeEffectChain_l(chain);
8760 }
8761 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008762 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008763 }
8764}
8765
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008766void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008767 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008768{
8769 effectChains = mEffectChains;
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08008770#ifdef QCOM_HARDWARE
8771 mAudioFlinger->mAllChainsLocked = true;
8772#endif
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008773 for (size_t i = 0; i < mEffectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008774#ifdef QCOM_HARDWARE
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08008775 if (mEffectChains[i] != mAudioFlinger->mLPAEffectChain) {
vivek mehta2192bc92012-12-04 11:46:08 -08008776#endif
8777 mEffectChains[i]->lock();
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08008778#ifdef QCOM_HARDWARE
8779 } else {
8780 mAudioFlinger-> mAllChainsLocked = false;
8781 }
8782#endif
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008783 }
8784}
8785
8786void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008787 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008788{
8789 for (size_t i = 0; i < effectChains.size(); i++) {
vivek mehta2192bc92012-12-04 11:46:08 -08008790#ifdef QCOM_HARDWARE
Haynes Mathew George30fd2a32013-02-21 20:06:04 -08008791 if (mAudioFlinger-> mAllChainsLocked || mEffectChains[i] != mAudioFlinger->mLPAEffectChain)
vivek mehta2192bc92012-12-04 11:46:08 -08008792#endif
8793 effectChains[i]->unlock();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008794 }
8795}
8796
8797sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8798{
8799 Mutex::Autolock _l(mLock);
8800 return getEffectChain_l(sessionId);
8801}
8802
Glenn Kasten106e8a42012-08-02 13:37:12 -07008803sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008804{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008805 size_t size = mEffectChains.size();
8806 for (size_t i = 0; i < size; i++) {
8807 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008808 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008809 }
8810 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008811 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008812}
8813
Glenn Kastenf78aee72012-01-04 11:00:47 -08008814void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008815{
8816 Mutex::Autolock _l(mLock);
8817 size_t size = mEffectChains.size();
8818 for (size_t i = 0; i < size; i++) {
8819 mEffectChains[i]->setMode_l(mode);
8820 }
8821}
8822
8823void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008824 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008825 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008826
Mathias Agopian65ab4712010-07-14 17:59:35 -07008827 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008828 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829 // delete the effect module if removing last handle on it
8830 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008831 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008832 removeEffect_l(effect);
8833 AudioSystem::unregisterEffect(effect->id());
8834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 }
8836}
8837
8838status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8839{
8840 int session = chain->sessionId();
8841 int16_t *buffer = mMixBuffer;
8842 bool ownsBuffer = false;
8843
Steve Block3856b092011-10-20 11:56:00 +01008844 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008845 if (session > 0) {
8846 // Only one effect chain can be present in direct output thread and it uses
8847 // the mix buffer as input
8848 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008849 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850 buffer = new int16_t[numSamples];
8851 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008852 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853 ownsBuffer = true;
8854 }
8855
8856 // Attach all tracks with same session ID to this chain.
8857 for (size_t i = 0; i < mTracks.size(); ++i) {
8858 sp<Track> track = mTracks[i];
8859 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008860 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008861 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008862 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863 }
8864 }
8865
8866 // indicate all active tracks in the chain
8867 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8868 sp<Track> track = mActiveTracks[i].promote();
8869 if (track == 0) continue;
8870 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008871 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008872 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873 }
8874 }
8875 }
8876
8877 chain->setInBuffer(buffer, ownsBuffer);
8878 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008879 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008880 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008881 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8882 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008884 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8885 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008886 // Effect chain for other sessions are inserted at beginning of effect
8887 // chains list to be processed before output mix effects. Relative order between other
8888 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008889 size_t size = mEffectChains.size();
8890 size_t i = 0;
8891 for (i = 0; i < size; i++) {
8892 if (mEffectChains[i]->sessionId() < session) break;
8893 }
8894 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008895 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008896
8897 return NO_ERROR;
8898}
8899
8900size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8901{
8902 int session = chain->sessionId();
8903
Steve Block3856b092011-10-20 11:56:00 +01008904 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905
8906 for (size_t i = 0; i < mEffectChains.size(); i++) {
8907 if (chain == mEffectChains[i]) {
8908 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008909 // detach all active tracks from the chain
8910 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8911 sp<Track> track = mActiveTracks[i].promote();
8912 if (track == 0) continue;
8913 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008914 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008915 chain.get(), session);
8916 chain->decActiveTrackCnt();
8917 }
8918 }
8919
Mathias Agopian65ab4712010-07-14 17:59:35 -07008920 // detach all tracks with same session ID from this chain
8921 for (size_t i = 0; i < mTracks.size(); ++i) {
8922 sp<Track> track = mTracks[i];
8923 if (session == track->sessionId()) {
8924 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008925 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926 }
8927 }
Eric Laurentde070132010-07-13 04:45:46 -07008928 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929 }
8930 }
8931 return mEffectChains.size();
8932}
8933
Eric Laurentde070132010-07-13 04:45:46 -07008934status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8935 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936{
8937 Mutex::Autolock _l(mLock);
8938 return attachAuxEffect_l(track, EffectId);
8939}
8940
Eric Laurentde070132010-07-13 04:45:46 -07008941status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8942 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008943{
8944 status_t status = NO_ERROR;
8945
8946 if (EffectId == 0) {
8947 track->setAuxBuffer(0, NULL);
8948 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008949 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8950 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951 if (effect != 0) {
8952 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8953 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8954 } else {
8955 status = INVALID_OPERATION;
8956 }
8957 } else {
8958 status = BAD_VALUE;
8959 }
8960 }
8961 return status;
8962}
8963
8964void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8965{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008966 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967 sp<Track> track = mTracks[i];
8968 if (track->auxEffectId() == effectId) {
8969 attachAuxEffect_l(track, 0);
8970 }
8971 }
8972}
8973
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008974status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8975{
8976 // only one chain per input thread
8977 if (mEffectChains.size() != 0) {
8978 return INVALID_OPERATION;
8979 }
Steve Block3856b092011-10-20 11:56:00 +01008980 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008981
8982 chain->setInBuffer(NULL);
8983 chain->setOutBuffer(NULL);
8984
Eric Laurent59255e42011-07-27 19:49:51 -07008985 checkSuspendOnAddEffectChain_l(chain);
8986
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008987 mEffectChains.add(chain);
8988
8989 return NO_ERROR;
8990}
8991
8992size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8993{
Steve Block3856b092011-10-20 11:56:00 +01008994 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008995 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008996 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8997 chain.get(), mEffectChains.size(), this);
8998 if (mEffectChains.size() == 1) {
8999 mEffectChains.removeAt(0);
9000 }
9001 return 0;
9002}
9003
Mathias Agopian65ab4712010-07-14 17:59:35 -07009004// ----------------------------------------------------------------------------
9005// EffectModule implementation
9006// ----------------------------------------------------------------------------
9007
9008#undef LOG_TAG
9009#define LOG_TAG "AudioFlinger::EffectModule"
9010
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009011AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012 const wp<AudioFlinger::EffectChain>& chain,
9013 effect_descriptor_t *desc,
9014 int id,
9015 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07009016 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
9017 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07009018 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07009019 // mConfig is set by configure() and not used before then
9020 mEffectInterface(NULL),
9021 mStatus(NO_INIT), mState(IDLE),
9022 // mMaxDisableWaitCnt is set by configure() and not used before then
9023 // mDisableWaitCnt is set by process() and updateState() and not used before then
9024 mSuspended(false)
vivek mehta2192bc92012-12-04 11:46:08 -08009025#ifdef QCOM_HARDWARE
9026 ,mIsForLPA(false)
9027#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028{
Steve Block3856b092011-10-20 11:56:00 +01009029 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031
9032 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009033 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034
9035 if (mStatus != NO_ERROR) {
9036 return;
9037 }
9038 lStatus = init();
9039 if (lStatus < 0) {
9040 mStatus = lStatus;
9041 goto Error;
9042 }
9043
Steve Block3856b092011-10-20 11:56:00 +01009044 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009045 return;
9046Error:
9047 EffectRelease(mEffectInterface);
9048 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01009049 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009050}
9051
9052AudioFlinger::EffectModule::~EffectModule()
9053{
Steve Block3856b092011-10-20 11:56:00 +01009054 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009056 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9057 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
9058 sp<ThreadBase> thread = mThread.promote();
9059 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009060 audio_stream_t *stream = thread->stream();
9061 if (stream != NULL) {
9062 stream->remove_audio_effect(stream, mEffectInterface);
9063 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009064 }
9065 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009066 // release effect engine
9067 EffectRelease(mEffectInterface);
9068 }
9069}
9070
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009071status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072{
9073 status_t status;
9074
9075 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009076 int priority = handle->priority();
9077 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009078 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009079 size_t i;
9080 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009081 EffectHandle *h = mHandles[i];
9082 if (h == NULL || h->destroyed_l()) continue;
9083 // first non destroyed handle is considered in control
9084 if (controlHandle == NULL)
9085 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009086 if (h->priority() <= priority) break;
9087 }
9088 // if inserted in first place, move effect control from previous owner to this handle
9089 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07009090 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009091 if (controlHandle != NULL) {
9092 enabled = controlHandle->enabled();
9093 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 }
Eric Laurent59255e42011-07-27 19:49:51 -07009095 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009096 status = NO_ERROR;
9097 } else {
9098 status = ALREADY_EXISTS;
9099 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009100 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101 mHandles.insertAt(handle, i);
9102 return status;
9103}
9104
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009105size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009106{
9107 Mutex::Autolock _l(mLock);
9108 size_t size = mHandles.size();
9109 size_t i;
9110 for (i = 0; i < size; i++) {
9111 if (mHandles[i] == handle) break;
9112 }
9113 if (i == size) {
9114 return size;
9115 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009116 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07009117
Mathias Agopian65ab4712010-07-14 17:59:35 -07009118 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009120 if (i == 0) {
9121 EffectHandle *h = controlHandle_l();
9122 if (h != NULL) {
9123 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124 }
9125 }
9126
Eric Laurentec437d82011-07-26 20:54:46 -07009127 // Prevent calls to process() and other functions on effect interface from now on.
9128 // The effect engine will be released by the destructor when the last strong reference on
9129 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009130 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07009131 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07009132 }
9133
Eric Laurente65c8912012-07-20 15:57:23 -07009134 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009135}
9136
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009137// must be called with EffectModule::mLock held
9138AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07009139{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009140 // the first valid handle in the list has control over the module
9141 for (size_t i = 0; i < mHandles.size(); i++) {
9142 EffectHandle *h = mHandles[i];
9143 if (h != NULL && !h->destroyed_l()) {
9144 return h;
9145 }
9146 }
9147
9148 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07009149}
9150
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009151size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152{
vivek mehta2192bc92012-12-04 11:46:08 -08009153#ifdef QCOM_HARDWARE
9154 setEnabled(false);
9155#endif
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009156 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009157 // keep a strong reference on this EffectModule to avoid calling the
9158 // destructor before we exit
9159 sp<EffectModule> keep(this);
9160 {
9161 sp<ThreadBase> thread = mThread.promote();
9162 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08009163 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164 }
9165 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009166 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009167}
9168
9169void AudioFlinger::EffectModule::updateState() {
9170 Mutex::Autolock _l(mLock);
9171
9172 switch (mState) {
9173 case RESTART:
9174 reset_l();
9175 // FALL THROUGH
9176
9177 case STARTING:
9178 // clear auxiliary effect input buffer for next accumulation
9179 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9180 memset(mConfig.inputCfg.buffer.raw,
9181 0,
9182 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
9183 }
9184 start_l();
9185 mState = ACTIVE;
9186 break;
9187 case STOPPING:
9188 stop_l();
9189 mDisableWaitCnt = mMaxDisableWaitCnt;
9190 mState = STOPPED;
9191 break;
9192 case STOPPED:
9193 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
9194 // turn off sequence.
9195 if (--mDisableWaitCnt == 0) {
9196 reset_l();
9197 mState = IDLE;
9198 }
9199 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009200 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201 break;
9202 }
9203}
9204
9205void AudioFlinger::EffectModule::process()
9206{
9207 Mutex::Autolock _l(mLock);
9208
Eric Laurentec437d82011-07-26 20:54:46 -07009209 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210 mConfig.inputCfg.buffer.raw == NULL ||
9211 mConfig.outputCfg.buffer.raw == NULL) {
9212 return;
9213 }
9214
Eric Laurent8f45bd72010-08-31 13:50:07 -07009215 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009216 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
9217 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08009218 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009219 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07009220 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009221 }
9222
9223 // do the actual processing in the effect engine
9224 int ret = (*mEffectInterface)->process(mEffectInterface,
9225 &mConfig.inputCfg.buffer,
9226 &mConfig.outputCfg.buffer);
9227
9228 // force transition to IDLE state when engine is ready
9229 if (mState == STOPPED && ret == -ENODATA) {
9230 mDisableWaitCnt = 1;
9231 }
9232
9233 // clear auxiliary effect input buffer for next accumulation
9234 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08009235 memset(mConfig.inputCfg.buffer.raw, 0,
9236 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237 }
9238 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08009239 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9240 // If an insert effect is idle and input buffer is different from output buffer,
9241 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07009243 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08009244 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
9245 int16_t *in = mConfig.inputCfg.buffer.s16;
9246 int16_t *out = mConfig.outputCfg.buffer.s16;
9247 for (size_t i = 0; i < frameCnt; i++) {
9248 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009250 }
9251 }
9252}
9253
9254void AudioFlinger::EffectModule::reset_l()
9255{
9256 if (mEffectInterface == NULL) {
9257 return;
9258 }
9259 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
9260}
9261
vivek mehta2192bc92012-12-04 11:46:08 -08009262#ifndef QCOM_HARDWARE
Mathias Agopian65ab4712010-07-14 17:59:35 -07009263status_t AudioFlinger::EffectModule::configure()
9264{
vivek mehta2192bc92012-12-04 11:46:08 -08009265#else
9266status_t AudioFlinger::EffectModule::configure(bool isForLPA, int sampleRate, int channelCount, int frameCount)
9267{
9268 uint32_t channels;
9269
9270 // Acquire lock here to make sure that any other thread does not delete
9271 // the effect handle and release the effect module.
9272 Mutex::Autolock _l(mLock);
9273#endif
9274
Mathias Agopian65ab4712010-07-14 17:59:35 -07009275 if (mEffectInterface == NULL) {
9276 return NO_INIT;
9277 }
9278
9279 sp<ThreadBase> thread = mThread.promote();
9280 if (thread == 0) {
9281 return DEAD_OBJECT;
9282 }
9283
9284 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07009285 audio_channel_mask_t channelMask = thread->channelMask();
vivek mehta2192bc92012-12-04 11:46:08 -08009286#ifdef QCOM_HARDWARE
9287 mIsForLPA = isForLPA;
9288 if(isForLPA) {
9289 if (channelCount == 1) {
9290 channels = AUDIO_CHANNEL_OUT_MONO;
9291 } else {
9292 channels = AUDIO_CHANNEL_OUT_STEREO;
9293 }
9294 ALOGV("%s: LPA ON - channels %d", __func__, channels);
9295 } else {
9296 if (thread->channelCount() == 1) {
9297 channels = AUDIO_CHANNEL_OUT_MONO;
9298 } else {
9299 channels = AUDIO_CHANNEL_OUT_STEREO;
9300 }
9301 }
9302#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009303
9304 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07009305 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009306 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07009307 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009308 }
Glenn Kasten254af182012-07-03 14:59:05 -07009309 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07009310 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
9311 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
vivek mehta2192bc92012-12-04 11:46:08 -08009312#ifdef QCOM_HARDWARE
9313 if(isForLPA){
9314 mConfig.inputCfg.samplingRate = sampleRate;
9315 ALOGV("%s: LPA ON - sampleRate %d", __func__, sampleRate);
9316 } else
9317#endif
9318 mConfig.inputCfg.samplingRate = thread->sampleRate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009319 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
9320 mConfig.inputCfg.bufferProvider.cookie = NULL;
9321 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
9322 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
9323 mConfig.outputCfg.bufferProvider.cookie = NULL;
9324 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
9325 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
9326 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
9327 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07009328 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07009329 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07009330 // - in other sessions:
9331 // last effect in the chain accumulates in output buffer: input buffer != output buffer
9332 // other effect: overwrites output buffer: input buffer == output buffer
9333 // Auxiliary effect:
9334 // accumulates in output buffer: input buffer != output buffer
9335 // Therefore: accumulate <=> input buffer != output buffer
9336 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
9337 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
9338 } else {
9339 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
9340 }
9341 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
9342 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
vivek mehta2192bc92012-12-04 11:46:08 -08009343#ifdef QCOM_HARDWARE
9344 if(isForLPA) {
9345 mConfig.inputCfg.buffer.frameCount = frameCount;
9346 ALOGV("%s: LPA ON - frameCount %d", __func__, frameCount);
9347 } else
9348#endif
9349 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009350 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
9351
Steve Block3856b092011-10-20 11:56:00 +01009352 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07009353 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
9354
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009356 uint32_t size = sizeof(int);
9357 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08009358 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07009359 sizeof(effect_config_t),
9360 &mConfig,
9361 &size,
9362 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009363 if (status == 0) {
9364 status = cmdStatus;
9365 }
9366
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07009367 if (status == 0 &&
9368 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
9369 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
9370 effect_param_t *p = (effect_param_t *)buf32;
9371
9372 p->psize = sizeof(uint32_t);
9373 p->vsize = sizeof(uint32_t);
9374 size = sizeof(int);
9375 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
9376
9377 uint32_t latency = 0;
9378 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
9379 if (pbt != NULL) {
9380 latency = pbt->latency_l();
9381 }
9382
9383 *((int32_t *)p->data + 1)= latency;
9384 (*mEffectInterface)->command(mEffectInterface,
9385 EFFECT_CMD_SET_PARAM,
9386 sizeof(effect_param_t) + 8,
9387 &buf32,
9388 &size,
9389 &cmdStatus);
9390 }
9391
Mathias Agopian65ab4712010-07-14 17:59:35 -07009392 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
9393 (1000 * mConfig.outputCfg.buffer.frameCount);
9394
9395 return status;
9396}
9397
9398status_t AudioFlinger::EffectModule::init()
9399{
9400 Mutex::Autolock _l(mLock);
9401 if (mEffectInterface == NULL) {
9402 return NO_INIT;
9403 }
9404 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009405 uint32_t size = sizeof(status_t);
9406 status_t status = (*mEffectInterface)->command(mEffectInterface,
9407 EFFECT_CMD_INIT,
9408 0,
9409 NULL,
9410 &size,
9411 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009412 if (status == 0) {
9413 status = cmdStatus;
9414 }
9415 return status;
9416}
9417
Eric Laurentec35a142011-10-05 17:42:25 -07009418status_t AudioFlinger::EffectModule::start()
9419{
9420 Mutex::Autolock _l(mLock);
9421 return start_l();
9422}
9423
Mathias Agopian65ab4712010-07-14 17:59:35 -07009424status_t AudioFlinger::EffectModule::start_l()
9425{
9426 if (mEffectInterface == NULL) {
9427 return NO_INIT;
9428 }
9429 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009430 uint32_t size = sizeof(status_t);
9431 status_t status = (*mEffectInterface)->command(mEffectInterface,
9432 EFFECT_CMD_ENABLE,
9433 0,
9434 NULL,
9435 &size,
9436 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009437 if (status == 0) {
9438 status = cmdStatus;
9439 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009440 if (status == 0 &&
9441 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9442 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9443 sp<ThreadBase> thread = mThread.promote();
9444 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009445 audio_stream_t *stream = thread->stream();
9446 if (stream != NULL) {
9447 stream->add_audio_effect(stream, mEffectInterface);
9448 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009449 }
9450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009451 return status;
9452}
9453
Eric Laurentec437d82011-07-26 20:54:46 -07009454status_t AudioFlinger::EffectModule::stop()
9455{
9456 Mutex::Autolock _l(mLock);
9457 return stop_l();
9458}
9459
Mathias Agopian65ab4712010-07-14 17:59:35 -07009460status_t AudioFlinger::EffectModule::stop_l()
9461{
9462 if (mEffectInterface == NULL) {
9463 return NO_INIT;
9464 }
9465 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009466 uint32_t size = sizeof(status_t);
9467 status_t status = (*mEffectInterface)->command(mEffectInterface,
9468 EFFECT_CMD_DISABLE,
9469 0,
9470 NULL,
9471 &size,
9472 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009473 if (status == 0) {
9474 status = cmdStatus;
9475 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009476 if (status == 0 &&
9477 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
9478 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
9479 sp<ThreadBase> thread = mThread.promote();
9480 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07009481 audio_stream_t *stream = thread->stream();
9482 if (stream != NULL) {
9483 stream->remove_audio_effect(stream, mEffectInterface);
9484 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009485 }
9486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009487 return status;
9488}
9489
Eric Laurent25f43952010-07-28 05:40:18 -07009490status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
9491 uint32_t cmdSize,
9492 void *pCmdData,
9493 uint32_t *replySize,
9494 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009495{
9496 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01009497// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009498
Eric Laurentec437d82011-07-26 20:54:46 -07009499 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009500 return NO_INIT;
9501 }
Eric Laurent25f43952010-07-28 05:40:18 -07009502 status_t status = (*mEffectInterface)->command(mEffectInterface,
9503 cmdCode,
9504 cmdSize,
9505 pCmdData,
9506 replySize,
9507 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009508 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07009509 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009510 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009511 EffectHandle *h = mHandles[i];
9512 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009513 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
9514 }
9515 }
9516 }
9517 return status;
9518}
9519
9520status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
9521{
9522 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009523 return setEnabled_l(enabled);
9524}
9525
9526// must be called with EffectModule::mLock held
9527status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
9528{
vivek mehta2192bc92012-12-04 11:46:08 -08009529#ifdef QCOM_HARDWARE
9530 bool effectStateChanged = false;
9531#endif
Steve Block3856b092011-10-20 11:56:00 +01009532 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009533
9534 if (enabled != isEnabled()) {
vivek mehta2192bc92012-12-04 11:46:08 -08009535#ifdef QCOM_HARDWARE
9536 effectStateChanged = true;
9537#endif
Eric Laurentdb7c0792011-08-10 10:37:50 -07009538 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
9539 if (enabled && status != NO_ERROR) {
9540 return status;
9541 }
9542
Mathias Agopian65ab4712010-07-14 17:59:35 -07009543 switch (mState) {
9544 // going from disabled to enabled
9545 case IDLE:
9546 mState = STARTING;
9547 break;
9548 case STOPPED:
9549 mState = RESTART;
9550 break;
9551 case STOPPING:
9552 mState = ACTIVE;
9553 break;
9554
9555 // going from enabled to disabled
9556 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009557 mState = STOPPED;
9558 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009559 case STARTING:
9560 mState = IDLE;
9561 break;
9562 case ACTIVE:
9563 mState = STOPPING;
9564 break;
Eric Laurentec437d82011-07-26 20:54:46 -07009565 case DESTROYED:
9566 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07009567 }
9568 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009569 EffectHandle *h = mHandles[i];
9570 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009571 h->setEnabled(enabled);
9572 }
9573 }
9574 }
vivek mehta2192bc92012-12-04 11:46:08 -08009575#ifdef QCOM_HARDWARE
9576 /*
9577 Send notification event to LPA Player when an effect for
9578 LPA output is enabled or disabled.
9579 */
9580 if (effectStateChanged && mIsForLPA) {
9581 sp<ThreadBase> thread = mThread.promote();
9582 thread->effectConfigChanged();
9583 }
9584#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07009585 return NO_ERROR;
9586}
9587
Glenn Kastenc59c0042012-02-02 14:06:11 -08009588bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07009589{
9590 switch (mState) {
9591 case RESTART:
9592 case STARTING:
9593 case ACTIVE:
9594 return true;
9595 case IDLE:
9596 case STOPPING:
9597 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07009598 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07009599 default:
9600 return false;
9601 }
9602}
9603
Glenn Kastenc59c0042012-02-02 14:06:11 -08009604bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07009605{
9606 switch (mState) {
9607 case RESTART:
9608 case ACTIVE:
9609 case STOPPING:
9610 case STOPPED:
9611 return true;
9612 case IDLE:
9613 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07009614 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07009615 default:
9616 return false;
9617 }
9618}
9619
Mathias Agopian65ab4712010-07-14 17:59:35 -07009620status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
9621{
9622 Mutex::Autolock _l(mLock);
9623 status_t status = NO_ERROR;
9624
9625 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
9626 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07009627 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07009628 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
9629 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009630 status_t cmdStatus;
9631 uint32_t volume[2];
9632 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07009633 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009634 volume[0] = *left;
9635 volume[1] = *right;
9636 if (controller) {
9637 pVolume = volume;
9638 }
Eric Laurent25f43952010-07-28 05:40:18 -07009639 status = (*mEffectInterface)->command(mEffectInterface,
9640 EFFECT_CMD_SET_VOLUME,
9641 size,
9642 volume,
9643 &size,
9644 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009645 if (controller && status == NO_ERROR && size == sizeof(volume)) {
9646 *left = volume[0];
9647 *right = volume[1];
9648 }
9649 }
9650 return status;
9651}
9652
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009653status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009654{
Eric Laurentf1c04f92012-08-28 14:26:53 -07009655 if (device == AUDIO_DEVICE_NONE) {
9656 return NO_ERROR;
9657 }
9658
Mathias Agopian65ab4712010-07-14 17:59:35 -07009659 Mutex::Autolock _l(mLock);
9660 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07009661 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07009662 status_t cmdStatus;
9663 uint32_t size = sizeof(status_t);
9664 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
9665 EFFECT_CMD_SET_INPUT_DEVICE;
9666 status = (*mEffectInterface)->command(mEffectInterface,
9667 cmd,
9668 sizeof(uint32_t),
9669 &device,
9670 &size,
9671 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009672 }
9673 return status;
9674}
9675
Glenn Kastenf78aee72012-01-04 11:00:47 -08009676status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009677{
9678 Mutex::Autolock _l(mLock);
9679 status_t status = NO_ERROR;
9680 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009681 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07009682 uint32_t size = sizeof(status_t);
9683 status = (*mEffectInterface)->command(mEffectInterface,
9684 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08009685 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07009686 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07009687 &size,
9688 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009689 if (status == NO_ERROR) {
9690 status = cmdStatus;
9691 }
9692 }
9693 return status;
9694}
9695
Eric Laurent57b2dd12012-08-31 17:44:06 -07009696status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
9697{
9698 Mutex::Autolock _l(mLock);
9699 status_t status = NO_ERROR;
9700 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
9701 uint32_t size = 0;
9702 status = (*mEffectInterface)->command(mEffectInterface,
9703 EFFECT_CMD_SET_AUDIO_SOURCE,
9704 sizeof(audio_source_t),
9705 &source,
9706 &size,
9707 NULL);
9708 }
9709 return status;
9710}
9711
Eric Laurent59255e42011-07-27 19:49:51 -07009712void AudioFlinger::EffectModule::setSuspended(bool suspended)
9713{
9714 Mutex::Autolock _l(mLock);
9715 mSuspended = suspended;
9716}
Glenn Kastena3a85482012-01-04 11:01:11 -08009717
9718bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07009719{
9720 Mutex::Autolock _l(mLock);
9721 return mSuspended;
9722}
9723
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009724bool AudioFlinger::EffectModule::purgeHandles()
9725{
9726 bool enabled = false;
9727 Mutex::Autolock _l(mLock);
9728 for (size_t i = 0; i < mHandles.size(); i++) {
9729 EffectHandle *handle = mHandles[i];
9730 if (handle != NULL && !handle->destroyed_l()) {
9731 handle->effect().clear();
9732 if (handle->hasControl()) {
9733 enabled = handle->enabled();
9734 }
9735 }
9736 }
9737 return enabled;
9738}
9739
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009740void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009741{
9742 const size_t SIZE = 256;
9743 char buffer[SIZE];
9744 String8 result;
9745
9746 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
9747 result.append(buffer);
9748
9749 bool locked = tryLock(mLock);
9750 // failed to lock - AudioFlinger is probably deadlocked
9751 if (!locked) {
9752 result.append("\t\tCould not lock Fx mutex:\n");
9753 }
9754
9755 result.append("\t\tSession Status State Engine:\n");
9756 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
9757 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
9758 result.append(buffer);
9759
9760 result.append("\t\tDescriptor:\n");
9761 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9762 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
9763 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
9764 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9765 result.append(buffer);
9766 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
9767 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
9768 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
9769 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9770 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009771 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009772 mDescriptor.apiVersion,
9773 mDescriptor.flags);
9774 result.append(buffer);
9775 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9776 mDescriptor.name);
9777 result.append(buffer);
9778 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9779 mDescriptor.implementor);
9780 result.append(buffer);
9781
9782 result.append("\t\t- Input configuration:\n");
9783 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9784 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9785 (uint32_t)mConfig.inputCfg.buffer.raw,
9786 mConfig.inputCfg.buffer.frameCount,
9787 mConfig.inputCfg.samplingRate,
9788 mConfig.inputCfg.channels,
9789 mConfig.inputCfg.format);
9790 result.append(buffer);
9791
9792 result.append("\t\t- Output configuration:\n");
9793 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9794 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9795 (uint32_t)mConfig.outputCfg.buffer.raw,
9796 mConfig.outputCfg.buffer.frameCount,
9797 mConfig.outputCfg.samplingRate,
9798 mConfig.outputCfg.channels,
9799 mConfig.outputCfg.format);
9800 result.append(buffer);
9801
9802 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9803 result.append(buffer);
9804 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9805 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009806 EffectHandle *handle = mHandles[i];
9807 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009808 handle->dump(buffer, SIZE);
9809 result.append(buffer);
9810 }
9811 }
9812
9813 result.append("\n");
9814
9815 write(fd, result.string(), result.length());
9816
9817 if (locked) {
9818 mLock.unlock();
9819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009820}
9821
9822// ----------------------------------------------------------------------------
9823// EffectHandle implementation
9824// ----------------------------------------------------------------------------
9825
9826#undef LOG_TAG
9827#define LOG_TAG "AudioFlinger::EffectHandle"
9828
9829AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9830 const sp<AudioFlinger::Client>& client,
9831 const sp<IEffectClient>& effectClient,
9832 int32_t priority)
9833 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009834 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009835 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009836{
Steve Block3856b092011-10-20 11:56:00 +01009837 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009838
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009839 if (client == 0) {
9840 return;
9841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009842 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9843 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9844 if (mCblkMemory != 0) {
9845 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9846
Glenn Kastena0d68332012-01-27 16:47:15 -08009847 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009848 new(mCblk) effect_param_cblk_t();
9849 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009851 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009852 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009853 return;
9854 }
9855}
9856
9857AudioFlinger::EffectHandle::~EffectHandle()
9858{
Steve Block3856b092011-10-20 11:56:00 +01009859 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009860
9861 if (mEffect == 0) {
9862 mDestroyed = true;
9863 return;
9864 }
9865 mEffect->lock();
9866 mDestroyed = true;
9867 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009868 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009869}
9870
9871status_t AudioFlinger::EffectHandle::enable()
9872{
Steve Block3856b092011-10-20 11:56:00 +01009873 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009874 if (!mHasControl) return INVALID_OPERATION;
9875 if (mEffect == 0) return DEAD_OBJECT;
9876
Eric Laurentdb7c0792011-08-10 10:37:50 -07009877 if (mEnabled) {
9878 return NO_ERROR;
9879 }
9880
Eric Laurent59255e42011-07-27 19:49:51 -07009881 mEnabled = true;
9882
9883 sp<ThreadBase> thread = mEffect->thread().promote();
9884 if (thread != 0) {
9885 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9886 }
9887
9888 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9889 if (mEffect->suspended()) {
9890 return NO_ERROR;
9891 }
9892
Eric Laurentdb7c0792011-08-10 10:37:50 -07009893 status_t status = mEffect->setEnabled(true);
9894 if (status != NO_ERROR) {
9895 if (thread != 0) {
9896 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9897 }
9898 mEnabled = false;
9899 }
9900 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009901}
9902
9903status_t AudioFlinger::EffectHandle::disable()
9904{
Steve Block3856b092011-10-20 11:56:00 +01009905 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009906 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009907 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009908
Eric Laurentdb7c0792011-08-10 10:37:50 -07009909 if (!mEnabled) {
9910 return NO_ERROR;
9911 }
Eric Laurent59255e42011-07-27 19:49:51 -07009912 mEnabled = false;
9913
9914 if (mEffect->suspended()) {
9915 return NO_ERROR;
9916 }
9917
9918 status_t status = mEffect->setEnabled(false);
9919
9920 sp<ThreadBase> thread = mEffect->thread().promote();
9921 if (thread != 0) {
9922 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9923 }
9924
9925 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009926}
9927
9928void AudioFlinger::EffectHandle::disconnect()
9929{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009930 disconnect(true);
9931}
9932
Glenn Kasten58123c32012-02-03 10:32:24 -08009933void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009934{
Glenn Kasten58123c32012-02-03 10:32:24 -08009935 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009936 if (mEffect == 0) {
9937 return;
9938 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009939 // restore suspended effects if the disconnected handle was enabled and the last one.
9940 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009941 sp<ThreadBase> thread = mEffect->thread().promote();
9942 if (thread != 0) {
9943 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9944 }
Eric Laurent59255e42011-07-27 19:49:51 -07009945 }
9946
Mathias Agopian65ab4712010-07-14 17:59:35 -07009947 // release sp on module => module destructor can be called now
9948 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009949 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009950 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009951 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009952 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9953 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009954 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009955 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009956 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9957 mClient.clear();
9958 }
9959}
9960
Eric Laurent25f43952010-07-28 05:40:18 -07009961status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9962 uint32_t cmdSize,
9963 void *pCmdData,
9964 uint32_t *replySize,
9965 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009966{
Steve Block3856b092011-10-20 11:56:00 +01009967// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009968// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009969
9970 // only get parameter command is permitted for applications not controlling the effect
9971 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9972 return INVALID_OPERATION;
9973 }
9974 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009975 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009976
9977 // handle commands that are not forwarded transparently to effect engine
9978 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9979 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9980 // no risk to block the whole media server process or mixer threads is we are stuck here
9981 Mutex::Autolock _l(mCblk->lock);
9982 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9983 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9984 mCblk->serverIndex = 0;
9985 mCblk->clientIndex = 0;
9986 return BAD_VALUE;
9987 }
9988 status_t status = NO_ERROR;
9989 while (mCblk->serverIndex < mCblk->clientIndex) {
9990 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009991 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009992 int *p = (int *)(mBuffer + mCblk->serverIndex);
9993 int size = *p++;
9994 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009995 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009996 break;
9997 }
9998 effect_param_t *param = (effect_param_t *)p;
9999 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010000 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -070010001 mCblk->serverIndex += size;
10002 continue;
10003 }
Eric Laurent25f43952010-07-28 05:40:18 -070010004 uint32_t psize = sizeof(effect_param_t) +
10005 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
10006 param->vsize;
10007 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
10008 psize,
10009 p,
10010 &rsize,
10011 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -070010012 // stop at first error encountered
10013 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010014 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -070010015 *(int *)pReplyData = reply;
10016 break;
10017 } else if (reply != NO_ERROR) {
10018 *(int *)pReplyData = reply;
10019 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010020 }
10021 mCblk->serverIndex += size;
10022 }
10023 mCblk->serverIndex = 0;
10024 mCblk->clientIndex = 0;
10025 return status;
10026 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -070010027 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010028 return enable();
10029 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -070010030 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010031 return disable();
10032 }
10033
vivek mehta2192bc92012-12-04 11:46:08 -080010034#ifdef QCOM_HARDWARE
10035 ALOGV("EffectHandle::command: isOnLPA %d", mEffect->isOnLPA());
10036 if(mEffect->isOnLPA() &&
10037 ((cmdCode == EFFECT_CMD_SET_PARAM) || (cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) ||
10038 (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) || (cmdCode == EFFECT_CMD_SET_DEVICE) ||
10039 (cmdCode == EFFECT_CMD_SET_VOLUME) || (cmdCode == EFFECT_CMD_SET_AUDIO_MODE)) ) {
10040 // Notify Direct track for the change in Effect module
10041 // TODO: check if it is required to send mLPAHandle
10042 ALOGV("Notifying Direct Track for the change in effect config");
10043 mClient->audioFlinger()->audioConfigChanged_l(AudioSystem::EFFECT_CONFIG_CHANGED, 0, NULL);
10044 }
10045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010046 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10047}
10048
Eric Laurent59255e42011-07-27 19:49:51 -070010049void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010050{
Steve Block3856b092011-10-20 11:56:00 +010010051 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010052
10053 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -070010054 mEnabled = enabled;
10055
Mathias Agopian65ab4712010-07-14 17:59:35 -070010056 if (signal && mEffectClient != 0) {
10057 mEffectClient->controlStatusChanged(hasControl);
10058 }
10059}
10060
Eric Laurent25f43952010-07-28 05:40:18 -070010061void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
10062 uint32_t cmdSize,
10063 void *pCmdData,
10064 uint32_t replySize,
10065 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010066{
10067 if (mEffectClient != 0) {
10068 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
10069 }
10070}
10071
10072
10073
10074void AudioFlinger::EffectHandle::setEnabled(bool enabled)
10075{
10076 if (mEffectClient != 0) {
10077 mEffectClient->enableStatusChanged(enabled);
10078 }
10079}
10080
10081status_t AudioFlinger::EffectHandle::onTransact(
10082 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10083{
10084 return BnEffect::onTransact(code, data, reply, flags);
10085}
10086
10087
10088void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
10089{
Glenn Kastena0d68332012-01-27 16:47:15 -080010090 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010091
10092 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -080010093 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -070010094 mPriority,
10095 mHasControl,
10096 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -070010097 mCblk ? mCblk->clientIndex : 0,
10098 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070010099 );
10100
10101 if (locked) {
10102 mCblk->lock.unlock();
10103 }
10104}
10105
10106#undef LOG_TAG
10107#define LOG_TAG "AudioFlinger::EffectChain"
10108
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010109AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010110 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010111 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -070010112 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
10113 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
vivek mehta2192bc92012-12-04 11:46:08 -080010114#ifdef QCOM_HARDWARE
10115 ,mIsForLPATrack(false)
10116#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070010117{
Dima Zavinfce7a472011-04-19 22:30:36 -070010118 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -080010119 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010120 return;
10121 }
10122 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
10123 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010124}
10125
10126AudioFlinger::EffectChain::~EffectChain()
10127{
10128 if (mOwnInBuffer) {
10129 delete mInBuffer;
10130 }
10131
10132}
10133
Eric Laurent59255e42011-07-27 19:49:51 -070010134// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010135sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010136{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010137 size_t size = mEffects.size();
10138
10139 for (size_t i = 0; i < size; i++) {
10140 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010141 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010142 }
10143 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010144 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010145}
10146
Eric Laurent59255e42011-07-27 19:49:51 -070010147// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -070010148sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010149{
Mathias Agopian65ab4712010-07-14 17:59:35 -070010150 size_t size = mEffects.size();
10151
10152 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -070010153 // by convention, return first effect if id provided is 0 (0 is never a valid id)
10154 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010155 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -070010156 }
10157 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010158 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010159}
10160
vivek mehta2192bc92012-12-04 11:46:08 -080010161#ifdef QCOM_HARDWARE
10162sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromIndex_l(int idx)
10163{
10164 sp<EffectModule> effect = NULL;
10165 if(idx < 0 || idx >= mEffects.size()) {
10166 ALOGE("EffectChain::getEffectFromIndex_l: invalid index %d", idx);
10167 }
10168 if(mEffects.size() > 0){
10169 effect = mEffects[idx];
10170 }
10171 return effect;
10172}
10173#endif
10174
Eric Laurent59255e42011-07-27 19:49:51 -070010175// getEffectFromType_l() must be called with ThreadBase::mLock held
10176sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
10177 const effect_uuid_t *type)
10178{
Eric Laurent59255e42011-07-27 19:49:51 -070010179 size_t size = mEffects.size();
10180
10181 for (size_t i = 0; i < size; i++) {
10182 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -080010183 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -070010184 }
10185 }
Glenn Kasten090f0192012-01-30 13:00:02 -080010186 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010187}
10188
Eric Laurent91b14c42012-05-30 12:30:29 -070010189void AudioFlinger::EffectChain::clearInputBuffer()
10190{
10191 Mutex::Autolock _l(mLock);
10192 sp<ThreadBase> thread = mThread.promote();
10193 if (thread == 0) {
10194 ALOGW("clearInputBuffer(): cannot promote mixer thread");
10195 return;
10196 }
10197 clearInputBuffer_l(thread);
10198}
10199
10200// Must be called with EffectChain::mLock locked
10201void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
10202{
10203 size_t numSamples = thread->frameCount() * thread->channelCount();
10204 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
10205
10206}
10207
Mathias Agopian65ab4712010-07-14 17:59:35 -070010208// Must be called with EffectChain::mLock locked
10209void AudioFlinger::EffectChain::process_l()
10210{
Eric Laurentdac69112010-09-28 14:09:57 -070010211 sp<ThreadBase> thread = mThread.promote();
10212 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010213 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -070010214 return;
10215 }
Dima Zavinfce7a472011-04-19 22:30:36 -070010216 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
10217 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010218 // always process effects unless no more tracks are on the session and the effect tail
10219 // has been rendered
10220 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -070010221 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -080010222 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -070010223
Eric Laurent544fe9b2011-11-11 15:42:52 -080010224 if (!tracksOnSession && mTailBufferCount == 0) {
10225 doProcess = false;
10226 }
10227
10228 if (activeTrackCnt() == 0) {
10229 // if no track is active and the effect tail has not been rendered,
10230 // the input buffer must be cleared here as the mixer process will not do it
10231 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -070010232 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -080010233 if (mTailBufferCount > 0) {
10234 mTailBufferCount--;
10235 }
10236 }
10237 }
Eric Laurentdac69112010-09-28 14:09:57 -070010238 }
10239
Mathias Agopian65ab4712010-07-14 17:59:35 -070010240 size_t size = mEffects.size();
vivek mehta2192bc92012-12-04 11:46:08 -080010241#ifdef QCOM_HARDWARE
10242 if (doProcess || isForLPATrack()) {
10243#else
Eric Laurent544fe9b2011-11-11 15:42:52 -080010244 if (doProcess) {
vivek mehta2192bc92012-12-04 11:46:08 -080010245#endif
Eric Laurentdac69112010-09-28 14:09:57 -070010246 for (size_t i = 0; i < size; i++) {
10247 mEffects[i]->process();
10248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010249 }
10250 for (size_t i = 0; i < size; i++) {
10251 mEffects[i]->updateState();
10252 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010253}
10254
Eric Laurentcab11242010-07-15 12:50:15 -070010255// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -070010256status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010257{
10258 effect_descriptor_t desc = effect->desc();
10259 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
10260
10261 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -070010262 effect->setChain(this);
10263 sp<ThreadBase> thread = mThread.promote();
10264 if (thread == 0) {
10265 return NO_INIT;
10266 }
10267 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010268
10269 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
10270 // Auxiliary effects are inserted at the beginning of mEffects vector as
10271 // they are processed first and accumulated in chain input buffer
10272 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -070010273
Mathias Agopian65ab4712010-07-14 17:59:35 -070010274 // the input buffer for auxiliary effect contains mono samples in
10275 // 32 bit format. This is to avoid saturation in AudoMixer
10276 // accumulation stage. Saturation is done in EffectModule::process() before
10277 // calling the process in effect engine
10278 size_t numSamples = thread->frameCount();
10279 int32_t *buffer = new int32_t[numSamples];
10280 memset(buffer, 0, numSamples * sizeof(int32_t));
10281 effect->setInBuffer((int16_t *)buffer);
10282 // auxiliary effects output samples to chain input buffer for further processing
10283 // by insert effects
10284 effect->setOutBuffer(mInBuffer);
10285 } else {
10286 // Insert effects are inserted at the end of mEffects vector as they are processed
10287 // after track and auxiliary effects.
10288 // Insert effect order as a function of indicated preference:
10289 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
10290 // another effect is present
10291 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
10292 // last effect claiming first position
10293 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
10294 // first effect claiming last position
10295 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
10296 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
10297 // already present
10298
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010299 size_t size = mEffects.size();
10300 size_t idx_insert = size;
10301 ssize_t idx_insert_first = -1;
10302 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010303
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010304 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010305 effect_descriptor_t d = mEffects[i]->desc();
10306 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
10307 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
10308 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
10309 // check invalid effect chaining combinations
10310 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
10311 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010312 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010313 return INVALID_OPERATION;
10314 }
10315 // remember position of first insert effect and by default
10316 // select this as insert position for new effect
10317 if (idx_insert == size) {
10318 idx_insert = i;
10319 }
10320 // remember position of last insert effect claiming
10321 // first position
10322 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
10323 idx_insert_first = i;
10324 }
10325 // remember position of first insert effect claiming
10326 // last position
10327 if (iPref == EFFECT_FLAG_INSERT_LAST &&
10328 idx_insert_last == -1) {
10329 idx_insert_last = i;
10330 }
10331 }
10332 }
10333
10334 // modify idx_insert from first position if needed
10335 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
10336 if (idx_insert_last != -1) {
10337 idx_insert = idx_insert_last;
10338 } else {
10339 idx_insert = size;
10340 }
10341 } else {
10342 if (idx_insert_first != -1) {
10343 idx_insert = idx_insert_first + 1;
10344 }
10345 }
10346
10347 // always read samples from chain input buffer
10348 effect->setInBuffer(mInBuffer);
10349
10350 // if last effect in the chain, output samples to chain
10351 // output buffer, otherwise to chain input buffer
10352 if (idx_insert == size) {
10353 if (idx_insert != 0) {
10354 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
10355 mEffects[idx_insert-1]->configure();
10356 }
10357 effect->setOutBuffer(mOutBuffer);
10358 } else {
10359 effect->setOutBuffer(mInBuffer);
10360 }
10361 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010362
Steve Block3856b092011-10-20 11:56:00 +010010363 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010364 }
10365 effect->configure();
10366 return NO_ERROR;
10367}
10368
Eric Laurentcab11242010-07-15 12:50:15 -070010369// removeEffect_l() must be called with PlaybackThread::mLock held
10370size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010371{
10372 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010373 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010374 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
10375
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010376 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010377 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -070010378 // calling stop here will remove pre-processing effect from the audio HAL.
10379 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
10380 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -070010381 if (mEffects[i]->state() == EffectModule::ACTIVE ||
10382 mEffects[i]->state() == EffectModule::STOPPING) {
10383 mEffects[i]->stop();
10384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010385 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
10386 delete[] effect->inBuffer();
10387 } else {
10388 if (i == size - 1 && i != 0) {
10389 mEffects[i - 1]->setOutBuffer(mOutBuffer);
10390 mEffects[i - 1]->configure();
10391 }
10392 }
10393 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +010010394 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -070010395 break;
10396 }
10397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010398
10399 return mEffects.size();
10400}
10401
Eric Laurentcab11242010-07-15 12:50:15 -070010402// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -070010403void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010404{
10405 size_t size = mEffects.size();
10406 for (size_t i = 0; i < size; i++) {
10407 mEffects[i]->setDevice(device);
10408 }
10409}
10410
Eric Laurentcab11242010-07-15 12:50:15 -070010411// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -080010412void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010413{
10414 size_t size = mEffects.size();
10415 for (size_t i = 0; i < size; i++) {
10416 mEffects[i]->setMode(mode);
10417 }
10418}
10419
Eric Laurent57b2dd12012-08-31 17:44:06 -070010420// setAudioSource_l() must be called with PlaybackThread::mLock held
10421void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
10422{
10423 size_t size = mEffects.size();
10424 for (size_t i = 0; i < size; i++) {
10425 mEffects[i]->setAudioSource(source);
10426 }
10427}
10428
Eric Laurentcab11242010-07-15 12:50:15 -070010429// setVolume_l() must be called with PlaybackThread::mLock held
10430bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010431{
10432 uint32_t newLeft = *left;
10433 uint32_t newRight = *right;
10434 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -070010435 int ctrlIdx = -1;
10436 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -070010437
Eric Laurentcab11242010-07-15 12:50:15 -070010438 // first update volume controller
10439 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -070010440 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -070010441 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
10442 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -070010443 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -070010444 break;
10445 }
10446 }
10447
10448 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -070010449 if (hasControl) {
10450 *left = mNewLeftVolume;
10451 *right = mNewRightVolume;
10452 }
10453 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -070010454 }
10455
10456 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -070010457 mLeftVolume = newLeft;
10458 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010459
10460 // second get volume update from volume controller
10461 if (ctrlIdx >= 0) {
10462 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -070010463 mNewLeftVolume = newLeft;
10464 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -070010465 }
10466 // then indicate volume to all other effects in chain.
10467 // Pass altered volume to effects before volume controller
10468 // and requested volume to effects after controller
10469 uint32_t lVol = newLeft;
10470 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -070010471
Mathias Agopian65ab4712010-07-14 17:59:35 -070010472 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -070010473 if ((int)i == ctrlIdx) continue;
10474 // this also works for ctrlIdx == -1 when there is no volume controller
10475 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -070010476 lVol = *left;
10477 rVol = *right;
10478 }
10479 mEffects[i]->setVolume(&lVol, &rVol, false);
10480 }
10481 *left = newLeft;
10482 *right = newRight;
10483
10484 return hasControl;
10485}
10486
Glenn Kastenbe5f05e2012-07-18 15:24:02 -070010487void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -070010488{
10489 const size_t SIZE = 256;
10490 char buffer[SIZE];
10491 String8 result;
10492
10493 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
10494 result.append(buffer);
10495
10496 bool locked = tryLock(mLock);
10497 // failed to lock - AudioFlinger is probably deadlocked
10498 if (!locked) {
10499 result.append("\tCould not lock mutex:\n");
10500 }
10501
Eric Laurentcab11242010-07-15 12:50:15 -070010502 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
10503 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -070010504 mEffects.size(),
10505 (uint32_t)mInBuffer,
10506 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -070010507 mActiveTrackCnt);
10508 result.append(buffer);
10509 write(fd, result.string(), result.size());
10510
10511 for (size_t i = 0; i < mEffects.size(); ++i) {
10512 sp<EffectModule> effect = mEffects[i];
10513 if (effect != 0) {
10514 effect->dump(fd, args);
10515 }
10516 }
10517
10518 if (locked) {
10519 mLock.unlock();
10520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -070010521}
10522
Eric Laurent59255e42011-07-27 19:49:51 -070010523// must be called with ThreadBase::mLock held
10524void AudioFlinger::EffectChain::setEffectSuspended_l(
10525 const effect_uuid_t *type, bool suspend)
10526{
10527 sp<SuspendedEffectDesc> desc;
10528 // use effect type UUID timelow as key as there is no real risk of identical
10529 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010530 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010531 if (suspend) {
10532 if (index >= 0) {
10533 desc = mSuspendedEffects.valueAt(index);
10534 } else {
10535 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -080010536 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -070010537 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +010010538 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010539 }
10540 if (desc->mRefCount++ == 0) {
10541 sp<EffectModule> effect = getEffectIfEnabled(type);
10542 if (effect != 0) {
10543 desc->mEffect = effect;
10544 effect->setSuspended(true);
10545 effect->setEnabled(false);
10546 }
10547 }
10548 } else {
10549 if (index < 0) {
10550 return;
10551 }
10552 desc = mSuspendedEffects.valueAt(index);
10553 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010554 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010555 desc->mRefCount = 1;
10556 }
10557 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +010010558 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010559 if (desc->mEffect != 0) {
10560 sp<EffectModule> effect = desc->mEffect.promote();
10561 if (effect != 0) {
10562 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010563 effect->lock();
10564 EffectHandle *handle = effect->controlHandle_l();
10565 if (handle != NULL && !handle->destroyed_l()) {
10566 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -070010567 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -070010568 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -070010569 }
10570 desc->mEffect.clear();
10571 }
10572 mSuspendedEffects.removeItemsAt(index);
10573 }
10574 }
10575}
10576
10577// must be called with ThreadBase::mLock held
10578void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
10579{
10580 sp<SuspendedEffectDesc> desc;
10581
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010582 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -070010583 if (suspend) {
10584 if (index >= 0) {
10585 desc = mSuspendedEffects.valueAt(index);
10586 } else {
10587 desc = new SuspendedEffectDesc();
10588 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +010010589 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -070010590 }
10591 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -080010592 Vector< sp<EffectModule> > effects;
10593 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -070010594 for (size_t i = 0; i < effects.size(); i++) {
10595 setEffectSuspended_l(&effects[i]->desc().type, true);
10596 }
10597 }
10598 } else {
10599 if (index < 0) {
10600 return;
10601 }
10602 desc = mSuspendedEffects.valueAt(index);
10603 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010604 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -070010605 desc->mRefCount = 1;
10606 }
10607 if (--desc->mRefCount == 0) {
10608 Vector<const effect_uuid_t *> types;
10609 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
10610 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
10611 continue;
10612 }
10613 types.add(&mSuspendedEffects.valueAt(i)->mType);
10614 }
10615 for (size_t i = 0; i < types.size(); i++) {
10616 setEffectSuspended_l(types[i], false);
10617 }
Steve Block3856b092011-10-20 11:56:00 +010010618 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -070010619 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
10620 }
10621 }
10622}
10623
Eric Laurent6bffdb82011-09-23 08:40:41 -070010624
10625// The volume effect is used for automated tests only
10626#ifndef OPENSL_ES_H_
10627static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
10628 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
10629const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
10630#endif //OPENSL_ES_H_
10631
Eric Laurentdb7c0792011-08-10 10:37:50 -070010632bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
10633{
10634 // auxiliary effects and visualizer are never suspended on output mix
10635 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
10636 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -070010637 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
10638 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -070010639 return false;
10640 }
10641 return true;
10642}
10643
Glenn Kastend0539712012-01-30 12:56:03 -080010644void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -070010645{
Glenn Kastend0539712012-01-30 12:56:03 -080010646 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -070010647 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -080010648 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
10649 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -070010650 }
Eric Laurent59255e42011-07-27 19:49:51 -070010651 }
Eric Laurent59255e42011-07-27 19:49:51 -070010652}
10653
10654sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
10655 const effect_uuid_t *type)
10656{
Glenn Kasten090f0192012-01-30 13:00:02 -080010657 sp<EffectModule> effect = getEffectFromType_l(type);
10658 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -070010659}
10660
10661void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
10662 bool enabled)
10663{
Glenn Kasten8d6a2442012-02-08 14:04:28 -080010664 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010665 if (enabled) {
10666 if (index < 0) {
10667 // if the effect is not suspend check if all effects are suspended
10668 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
10669 if (index < 0) {
10670 return;
10671 }
Eric Laurentdb7c0792011-08-10 10:37:50 -070010672 if (!isEffectEligibleForSuspend(effect->desc())) {
10673 return;
10674 }
Eric Laurent59255e42011-07-27 19:49:51 -070010675 setEffectSuspended_l(&effect->desc().type, enabled);
10676 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -070010677 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +000010678 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -070010679 return;
10680 }
Eric Laurent59255e42011-07-27 19:49:51 -070010681 }
Steve Block3856b092011-10-20 11:56:00 +010010682 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010683 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010684 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10685 // if effect is requested to suspended but was not yet enabled, supend it now.
10686 if (desc->mEffect == 0) {
10687 desc->mEffect = effect;
10688 effect->setEnabled(false);
10689 effect->setSuspended(true);
10690 }
10691 } else {
10692 if (index < 0) {
10693 return;
10694 }
Steve Block3856b092011-10-20 11:56:00 +010010695 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -070010696 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -070010697 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
10698 desc->mEffect.clear();
10699 effect->setSuspended(false);
10700 }
10701}
10702
Mathias Agopian65ab4712010-07-14 17:59:35 -070010703#undef LOG_TAG
10704#define LOG_TAG "AudioFlinger"
10705
10706// ----------------------------------------------------------------------------
10707
10708status_t AudioFlinger::onTransact(
10709 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
10710{
10711 return BnAudioFlinger::onTransact(code, data, reply, flags);
10712}
10713
Mathias Agopian65ab4712010-07-14 17:59:35 -070010714}; // namespace android