blob: 14f74b56d4553a684dd79494245b445e5d10d213 [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
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
Glenn Kastenfc7992b2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kasten2662ac92012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211 rc = BAD_VALUE;
212 goto out;
213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 return 0;
215
216out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 *dev = NULL;
218 return rc;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700226 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 mMasterMute(false),
229 mNextUniqueId(1),
230 mMode(AUDIO_MODE_INVALID),
231 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700233}
234
235void AudioFlinger::onFirstRef()
236{
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700238
Eric Laurent93575202011-01-18 18:39:02 -0800239 Mutex::Autolock _l(mLock);
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 char val_str[PROPERTY_VALUE_MAX] = { 0 };
243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244 uint32_t int_val;
245 if (1 == sscanf(val_str, "%u", &int_val)) {
246 mStandbyTimeInNsecs = milliseconds(int_val);
247 ALOGI("Using %u mSec as standby time.", int_val);
248 } else {
249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250 ALOGI("Using default %u mSec as standby time.",
251 (uint32_t)(mStandbyTimeInNsecs / 1000000));
252 }
253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
258AudioFlinger::~AudioFlinger()
259{
260 while (!mRecordThreads.isEmpty()) {
Glenn Kasten2662ac92012-07-30 10:59:30 -0700261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264 while (!mPlaybackThreads.isEmpty()) {
Glenn Kasten2662ac92012-07-30 10:59:30 -0700265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700268
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
John Grossmanee578c02012-07-23 17:05:46 -0700283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
294 } else {
295 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
297 if (audioHwDevice != NULL) {
298 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299 }
300 }
301 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700302 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
John Grossmanee578c02012-07-23 17:05:46 -0700303 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
304 audio_hw_device_t *dev = audioHwDevice->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700305 if ((dev->get_supported_devices(dev) & devices) == devices)
John Grossmanee578c02012-07-23 17:05:46 -0700306 return audioHwDevice;
Dima Zavin799a70e2011-04-18 16:57:27 -0700307 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700308
Dima Zavin799a70e2011-04-18 16:57:27 -0700309 return NULL;
310}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700312void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313{
314 const size_t SIZE = 256;
315 char buffer[SIZE];
316 String8 result;
317
318 result.append("Clients:\n");
319 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800320 sp<Client> client = mClients.valueAt(i).promote();
321 if (client != 0) {
322 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
323 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 }
325 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700326
327 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800328 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700329 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
330 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800331 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700332 result.append(buffer);
333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335}
336
337
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700338void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800343 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344
John Grossman4ff14ba2012-02-08 16:37:41 -0800345 snprintf(buffer, SIZE, "Hardware status: %d\n"
346 "Standby Time mSec: %u\n",
347 hardwareStatus,
348 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349 result.append(buffer);
350 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351}
352
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700353void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354{
355 const size_t SIZE = 256;
356 char buffer[SIZE];
357 String8 result;
358 snprintf(buffer, SIZE, "Permission Denial: "
359 "can't dump AudioFlinger from pid=%d, uid=%d\n",
360 IPCThreadState::self()->getCallingPid(),
361 IPCThreadState::self()->getCallingUid());
362 result.append(buffer);
363 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364}
365
366static bool tryLock(Mutex& mutex)
367{
368 bool locked = false;
369 for (int i = 0; i < kDumpLockRetries; ++i) {
370 if (mutex.tryLock() == NO_ERROR) {
371 locked = true;
372 break;
373 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800374 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 }
376 return locked;
377}
378
379status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
380{
Glenn Kasten44deb052012-02-05 18:09:08 -0800381 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 dumpPermissionDenial(fd, args);
383 } else {
384 // get state of hardware lock
385 bool hardwareLocked = tryLock(mHardwareLock);
386 if (!hardwareLocked) {
387 String8 result(kHardwareLockedString);
388 write(fd, result.string(), result.size());
389 } else {
390 mHardwareLock.unlock();
391 }
392
393 bool locked = tryLock(mLock);
394
395 // failed to lock - AudioFlinger is probably deadlocked
396 if (!locked) {
397 String8 result(kDeadlockedString);
398 write(fd, result.string(), result.size());
399 }
400
401 dumpClients(fd, args);
402 dumpInternals(fd, args);
403
404 // dump playback threads
405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
406 mPlaybackThreads.valueAt(i)->dump(fd, args);
407 }
408
409 // dump record threads
410 for (size_t i = 0; i < mRecordThreads.size(); i++) {
411 mRecordThreads.valueAt(i)->dump(fd, args);
412 }
413
Dima Zavin799a70e2011-04-18 16:57:27 -0700414 // dump all hardware devs
415 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700416 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700417 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418 }
419 if (locked) mLock.unlock();
420 }
421 return NO_ERROR;
422}
423
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800424sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
425{
426 // If pid is already in the mClients wp<> map, then use that entry
427 // (for which promote() is always != 0), otherwise create a new entry and Client.
428 sp<Client> client = mClients.valueFor(pid).promote();
429 if (client == 0) {
430 client = new Client(this, pid);
431 mClients.add(pid, client);
432 }
433
434 return client;
435}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436
437// IAudioFlinger interface
438
439
440sp<IAudioTrack> AudioFlinger::createTrack(
441 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800442 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800444 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700445 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800447 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800449 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800450 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 int *sessionId,
452 status_t *status)
453{
454 sp<PlaybackThread::Track> track;
455 sp<TrackHandle> trackHandle;
456 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 status_t lStatus;
458 int lSessionId;
459
Glenn Kasten263709e2012-01-06 08:40:01 -0800460 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
461 // but if someone uses binder directly they could bypass that and cause us to crash
462 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
468 {
469 Mutex::Autolock _l(mLock);
470 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700471 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000473 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 lStatus = BAD_VALUE;
475 goto Exit;
476 }
477
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800478 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479
Steve Block3856b092011-10-20 11:56:00 +0100480 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700481 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700482 // check if an effect chain with the same session ID is present on another
483 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700484 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700485 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
486 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700487 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 if (sessions & PlaybackThread::EFFECT_SESSION) {
489 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700490 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700491 }
Eric Laurentde070132010-07-13 04:45:46 -0700492 }
493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494 lSessionId = *sessionId;
495 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700496 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700497 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 if (sessionId != NULL) {
499 *sessionId = lSessionId;
500 }
501 }
Steve Block3856b092011-10-20 11:56:00 +0100502 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503
504 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800505 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700506
507 // move effect chain to this output thread if an effect on same session was waiting
508 // for a track to be created
509 if (lStatus == NO_ERROR && effectThread != NULL) {
510 Mutex::Autolock _dl(thread->mLock);
511 Mutex::Autolock _sl(effectThread->mLock);
512 moveEffectChain_l(lSessionId, effectThread, thread, true);
513 }
Eric Laurenta011e352012-03-29 15:51:43 -0700514
515 // Look for sync events awaiting for a session to be used.
516 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
517 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
518 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700519 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700520 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700521 } else {
522 mPendingSyncEvents[i]->cancel();
523 }
Eric Laurenta011e352012-03-29 15:51:43 -0700524 mPendingSyncEvents.removeAt(i);
525 i--;
526 }
527 }
528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 }
530 if (lStatus == NO_ERROR) {
531 trackHandle = new TrackHandle(track);
532 } else {
533 // remove local strong reference to Client before deleting the Track so that the Client
534 // destructor is called by the TrackBase destructor with mLock held
535 client.clear();
536 track.clear();
537 }
538
539Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700540 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 *status = lStatus;
542 }
543 return trackHandle;
544}
545
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800546uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000551 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 return 0;
553 }
554 return thread->sampleRate();
555}
556
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800557int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000562 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 return 0;
564 }
565 return thread->channelCount();
566}
567
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800568audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000573 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800574 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 }
576 return thread->format();
577}
578
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800579size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580{
581 Mutex::Autolock _l(mLock);
582 PlaybackThread *thread = checkPlaybackThread_l(output);
583 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000584 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 return 0;
586 }
Glenn Kasten58912562012-04-03 10:45:00 -0700587 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
588 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 return thread->frameCount();
590}
591
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800592uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593{
594 Mutex::Autolock _l(mLock);
595 PlaybackThread *thread = checkPlaybackThread_l(output);
596 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000597 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 return 0;
599 }
600 return thread->latency();
601}
602
603status_t AudioFlinger::setMasterVolume(float value)
604{
Eric Laurenta1884f92011-08-23 08:25:03 -0700605 status_t ret = initCheck();
606 if (ret != NO_ERROR) {
607 return ret;
608 }
609
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 // check calling permissions
611 if (!settingsAllowed()) {
612 return PERMISSION_DENIED;
613 }
614
Eric Laurenta4c5a552012-03-29 10:12:40 -0700615 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700616 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700617
John Grossmanee578c02012-07-23 17:05:46 -0700618 // Set master volume in the HALs which support it.
619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
620 AutoMutex lock(mHardwareLock);
621 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800622
John Grossmanee578c02012-07-23 17:05:46 -0700623 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
624 if (dev->canSetMasterVolume()) {
625 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800626 }
John Grossmanee578c02012-07-23 17:05:46 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
John Grossmanee578c02012-07-23 17:05:46 -0700630 // Now set the master volume in each playback thread. Playback threads
631 // assigned to HALs which do not have master volume support will apply
632 // master volume during the mix operation. Threads with HALs which do
633 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800634 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700635 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
637 return NO_ERROR;
638}
639
Glenn Kastenf78aee72012-01-04 11:00:47 -0800640status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641{
Eric Laurenta1884f92011-08-23 08:25:03 -0700642 status_t ret = initCheck();
643 if (ret != NO_ERROR) {
644 return ret;
645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646
647 // check calling permissions
648 if (!settingsAllowed()) {
649 return PERMISSION_DENIED;
650 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800651 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000652 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 return BAD_VALUE;
654 }
655
656 { // scope for the lock
657 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700658 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700660 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 mHardwareStatus = AUDIO_HW_IDLE;
662 }
663
664 if (NO_ERROR == ret) {
665 Mutex::Autolock _l(mLock);
666 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800667 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700668 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669 }
670
671 return ret;
672}
673
674status_t AudioFlinger::setMicMute(bool state)
675{
Eric Laurenta1884f92011-08-23 08:25:03 -0700676 status_t ret = initCheck();
677 if (ret != NO_ERROR) {
678 return ret;
679 }
680
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
686 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700687 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700689 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 mHardwareStatus = AUDIO_HW_IDLE;
691 return ret;
692}
693
694bool AudioFlinger::getMicMute() const
695{
Eric Laurenta1884f92011-08-23 08:25:03 -0700696 status_t ret = initCheck();
697 if (ret != NO_ERROR) {
698 return false;
699 }
700
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800702 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700703 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700705 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mHardwareStatus = AUDIO_HW_IDLE;
707 return state;
708}
709
710status_t AudioFlinger::setMasterMute(bool muted)
711{
John Grossmand8f178d2012-07-20 14:51:35 -0700712 status_t ret = initCheck();
713 if (ret != NO_ERROR) {
714 return ret;
715 }
716
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 // check calling permissions
718 if (!settingsAllowed()) {
719 return PERMISSION_DENIED;
720 }
721
John Grossmanee578c02012-07-23 17:05:46 -0700722 Mutex::Autolock _l(mLock);
723 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700724
John Grossmanee578c02012-07-23 17:05:46 -0700725 // Set master mute in the HALs which support it.
726 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
727 AutoMutex lock(mHardwareLock);
728 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700729
John Grossmanee578c02012-07-23 17:05:46 -0700730 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
731 if (dev->canSetMasterMute()) {
732 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700733 }
John Grossmanee578c02012-07-23 17:05:46 -0700734 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700735 }
736
John Grossmanee578c02012-07-23 17:05:46 -0700737 // Now set the master mute in each playback thread. Playback threads
738 // assigned to HALs which do not have master mute support will apply master
739 // mute during the mix operation. Threads with HALs which do support master
740 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800741 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700742 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743
744 return NO_ERROR;
745}
746
747float AudioFlinger::masterVolume() const
748{
Glenn Kasten98067102011-12-13 11:47:54 -0800749 Mutex::Autolock _l(mLock);
750 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751}
752
753bool AudioFlinger::masterMute() const
754{
Glenn Kasten98067102011-12-13 11:47:54 -0800755 Mutex::Autolock _l(mLock);
756 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757}
758
John Grossman4ff14ba2012-02-08 16:37:41 -0800759float AudioFlinger::masterVolume_l() const
760{
John Grossman4ff14ba2012-02-08 16:37:41 -0800761 return mMasterVolume;
762}
763
John Grossmand8f178d2012-07-20 14:51:35 -0700764bool AudioFlinger::masterMute_l() const
765{
John Grossmanee578c02012-07-23 17:05:46 -0700766 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700767}
768
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800769status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
770 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771{
772 // check calling permissions
773 if (!settingsAllowed()) {
774 return PERMISSION_DENIED;
775 }
776
Glenn Kasten263709e2012-01-06 08:40:01 -0800777 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000778 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 return BAD_VALUE;
780 }
781
782 AutoMutex lock(mLock);
783 PlaybackThread *thread = NULL;
784 if (output) {
785 thread = checkPlaybackThread_l(output);
786 if (thread == NULL) {
787 return BAD_VALUE;
788 }
789 }
790
791 mStreamTypes[stream].volume = value;
792
793 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800794 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700795 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797 } else {
798 thread->setStreamVolume(stream, value);
799 }
800
801 return NO_ERROR;
802}
803
Glenn Kastenfff6d712012-01-12 16:38:12 -0800804status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
806 // check calling permissions
807 if (!settingsAllowed()) {
808 return PERMISSION_DENIED;
809 }
810
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700812 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000813 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return BAD_VALUE;
815 }
816
Eric Laurent93575202011-01-18 18:39:02 -0800817 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 mStreamTypes[stream].mute = muted;
819 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700820 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821
822 return NO_ERROR;
823}
824
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800825float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826{
Glenn Kasten263709e2012-01-06 08:40:01 -0800827 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 return 0.0f;
829 }
830
831 AutoMutex lock(mLock);
832 float volume;
833 if (output) {
834 PlaybackThread *thread = checkPlaybackThread_l(output);
835 if (thread == NULL) {
836 return 0.0f;
837 }
838 volume = thread->streamVolume(stream);
839 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800840 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 }
842
843 return volume;
844}
845
Glenn Kastenfff6d712012-01-12 16:38:12 -0800846bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847{
Glenn Kasten263709e2012-01-06 08:40:01 -0800848 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return true;
850 }
851
Glenn Kasten6637baa2012-01-09 09:40:36 -0800852 AutoMutex lock(mLock);
853 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854}
855
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800856status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800858 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
860 // check calling permissions
861 if (!settingsAllowed()) {
862 return PERMISSION_DENIED;
863 }
864
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 // ioHandle == 0 means the parameters are global to the audio hardware interface
866 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700867 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700868 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800869 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700870 AutoMutex lock(mHardwareLock);
871 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
872 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
873 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
874 status_t result = dev->set_parameters(dev, keyValuePairs.string());
875 final_result = result ?: final_result;
876 }
877 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800878 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
880 AudioParameter param = AudioParameter(keyValuePairs);
881 String8 value;
882 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700883 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
884 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 for (size_t i = 0; i < mRecordThreads.size(); i++) {
886 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Glenn Kasten510a3d62012-07-16 14:24:34 -0700887 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
888 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
889 // collect all of the thread's session IDs
890 KeyedVector<int, bool> ids = thread->sessionIds();
891 // suspend effects associated with those session IDs
892 for (size_t j = 0; j < ids.size(); ++j) {
893 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700894 thread->setEffectSuspended(FX_IID_AEC,
895 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700896 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700897 thread->setEffectSuspended(FX_IID_NS,
898 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700899 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700900 }
901 }
Eric Laurentbee53372011-08-29 12:42:48 -0700902 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700903 }
904 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700905 String8 screenState;
906 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
907 bool isOff = screenState == "off";
908 if (isOff != (gScreenState & 1)) {
909 gScreenState = ((gScreenState & ~1) + 2) | isOff;
910 }
911 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914
915 // hold a strong ref on thread in case closeOutput() or closeInput() is called
916 // and the thread is exited once the lock is released
917 sp<ThreadBase> thread;
918 {
919 Mutex::Autolock _l(mLock);
920 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700921 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800923 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700924 // indicate output device change to all input threads for pre processing
925 AudioParameter param = AudioParameter(keyValuePairs);
926 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700927 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
928 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700929 for (size_t i = 0; i < mRecordThreads.size(); i++) {
930 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
931 }
932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 }
934 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800935 if (thread != 0) {
936 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 }
938 return BAD_VALUE;
939}
940
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800941String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800943// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
945
Eric Laurenta4c5a552012-03-29 10:12:40 -0700946 Mutex::Autolock _l(mLock);
947
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700949 String8 out_s8;
950
Dima Zavin799a70e2011-04-18 16:57:27 -0700951 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800952 char *s;
953 {
954 AutoMutex lock(mHardwareLock);
955 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700956 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800957 s = dev->get_parameters(dev, keys.string());
958 mHardwareStatus = AUDIO_HW_IDLE;
959 }
John Grossmanef7740b2012-02-09 11:28:36 -0800960 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700961 free(s);
962 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700963 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 }
965
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
967 if (playbackThread != NULL) {
968 return playbackThread->getParameters(keys);
969 }
970 RecordThread *recordThread = checkRecordThread_l(ioHandle);
971 if (recordThread != NULL) {
972 return recordThread->getParameters(keys);
973 }
974 return String8("");
975}
976
Glenn Kastendd8104c2012-07-02 12:42:44 -0700977size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
978 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979{
Eric Laurenta1884f92011-08-23 08:25:03 -0700980 status_t ret = initCheck();
981 if (ret != NO_ERROR) {
982 return 0;
983 }
984
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800985 AutoMutex lock(mHardwareLock);
986 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700987 struct audio_config config = {
988 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700989 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700990 format: format,
991 };
John Grossmanee578c02012-07-23 17:05:46 -0700992 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
993 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800994 mHardwareStatus = AUDIO_HW_IDLE;
995 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996}
997
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800998unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 Mutex::Autolock _l(mLock);
1001
1002 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1003 if (recordThread != NULL) {
1004 return recordThread->getInputFramesLost();
1005 }
1006 return 0;
1007}
1008
1009status_t AudioFlinger::setVoiceVolume(float value)
1010{
Eric Laurenta1884f92011-08-23 08:25:03 -07001011 status_t ret = initCheck();
1012 if (ret != NO_ERROR) {
1013 return ret;
1014 }
1015
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 // check calling permissions
1017 if (!settingsAllowed()) {
1018 return PERMISSION_DENIED;
1019 }
1020
1021 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001022 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001023 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001024 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 mHardwareStatus = AUDIO_HW_IDLE;
1026
1027 return ret;
1028}
1029
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001030status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1031 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032{
1033 status_t status;
1034
1035 Mutex::Autolock _l(mLock);
1036
1037 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1038 if (playbackThread != NULL) {
1039 return playbackThread->getRenderPosition(halFrames, dspFrames);
1040 }
1041
1042 return BAD_VALUE;
1043}
1044
1045void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1046{
1047
1048 Mutex::Autolock _l(mLock);
1049
Glenn Kastenbb001922012-02-03 11:10:26 -08001050 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 if (mNotificationClients.indexOfKey(pid) < 0) {
1052 sp<NotificationClient> notificationClient = new NotificationClient(this,
1053 client,
1054 pid);
Steve Block3856b092011-10-20 11:56:00 +01001055 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056
1057 mNotificationClients.add(pid, notificationClient);
1058
1059 sp<IBinder> binder = client->asBinder();
1060 binder->linkToDeath(notificationClient);
1061
1062 // the config change is always sent from playback or record threads to avoid deadlock
1063 // with AudioSystem::gLock
1064 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1065 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1066 }
1067
1068 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1069 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1070 }
1071 }
1072}
1073
1074void AudioFlinger::removeNotificationClient(pid_t pid)
1075{
1076 Mutex::Autolock _l(mLock);
1077
Glenn Kastena3b09252012-01-20 09:19:01 -08001078 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001081 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001084 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001085 ALOGV(" pid %d @ %d", ref->mPid, i);
1086 if (ref->mPid == pid) {
1087 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001088 mAudioSessionRefs.removeAt(i);
1089 delete ref;
1090 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001091 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001092 } else {
1093 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001094 }
1095 }
1096 if (removed) {
1097 purgeStaleEffects_l();
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099}
1100
1101// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001102void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103{
1104 size_t size = mNotificationClients.size();
1105 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001106 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1107 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 }
1109}
1110
1111// removeClient_l() must be called with AudioFlinger::mLock held
1112void AudioFlinger::removeClient_l(pid_t pid)
1113{
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 mClients.removeItem(pid);
1116}
1117
Eric Laurent717e1282012-06-29 16:36:52 -07001118// getEffectThread_l() must be called with AudioFlinger::mLock held
1119sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1120{
1121 sp<PlaybackThread> thread;
1122
1123 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1124 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1125 ALOG_ASSERT(thread == 0);
1126 thread = mPlaybackThreads.valueAt(i);
1127 }
1128 }
1129
1130 return thread;
1131}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132
1133// ----------------------------------------------------------------------------
1134
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001135AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001136 audio_devices_t device, type_t type)
Glenn Kasten2662ac92012-07-30 10:59:30 -07001137 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001138 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001139 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001140 // mChannelMask
1141 mChannelCount(0),
1142 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1143 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001144 mStandby(false), mDevice(device), mId(id),
Glenn Kasten2662ac92012-07-30 10:59:30 -07001145 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001146 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147{
1148}
1149
1150AudioFlinger::ThreadBase::~ThreadBase()
1151{
1152 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001153 // do not lock the mutex in destructor
1154 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001155 if (mPowerManager != 0) {
1156 sp<IBinder> binder = mPowerManager->asBinder();
1157 binder->unlinkToDeath(mDeathRecipient);
1158 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159}
1160
1161void AudioFlinger::ThreadBase::exit()
1162{
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001165 // This lock prevents the following race in thread (uniprocessor for illustration):
1166 // if (!exitPending()) {
1167 // // context switch from here to exit()
1168 // // exit() calls requestExit(), what exitPending() observes
1169 // // exit() calls signal(), which is dropped since no waiters
1170 // // context switch back from exit() to here
1171 // mWaitWorkCV.wait(...);
1172 // // now thread is hung
1173 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001174 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 requestExit();
1176 mWaitWorkCV.signal();
1177 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001178 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1179 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 requestExitAndWait();
1181}
1182
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1184{
1185 status_t status;
1186
Steve Block3856b092011-10-20 11:56:00 +01001187 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 Mutex::Autolock _l(mLock);
1189
1190 mNewParameters.add(keyValuePairs);
1191 mWaitWorkCV.signal();
1192 // wait condition with timeout in case the thread loop has exited
1193 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001194 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 status = mParamStatus;
1196 mWaitWorkCV.signal();
1197 } else {
1198 status = TIMED_OUT;
1199 }
1200 return status;
1201}
1202
1203void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1204{
1205 Mutex::Autolock _l(mLock);
1206 sendConfigEvent_l(event, param);
1207}
1208
1209// sendConfigEvent_l() must be called with ThreadBase::mLock held
1210void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1211{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001212 ConfigEvent configEvent;
1213 configEvent.mEvent = event;
1214 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001216 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mWaitWorkCV.signal();
1218}
1219
1220void AudioFlinger::ThreadBase::processConfigEvents()
1221{
1222 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001223 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001224 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001225 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 mConfigEvents.removeAt(0);
1227 // release mLock before locking AudioFlinger mLock: lock order is always
1228 // AudioFlinger then ThreadBase to avoid cross deadlock
1229 mLock.unlock();
1230 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001231 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 mLock.lock();
1234 }
1235 mLock.unlock();
1236}
1237
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001238void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239{
1240 const size_t SIZE = 256;
1241 char buffer[SIZE];
1242 String8 result;
1243
1244 bool locked = tryLock(mLock);
1245 if (!locked) {
1246 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1247 write(fd, buffer, strlen(buffer));
1248 }
1249
Eric Laurent612bbb52012-03-14 15:03:26 -07001250 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1251 result.append(buffer);
1252 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1253 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1255 result.append(buffer);
1256 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1257 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001258 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1259 result.append(buffer);
1260 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261 result.append(buffer);
1262 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1263 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001264 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1265 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1267 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001268 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 result.append(buffer);
1270
1271 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1272 result.append(buffer);
1273 result.append(" Index Command");
1274 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1275 snprintf(buffer, SIZE, "\n %02d ", i);
1276 result.append(buffer);
1277 result.append(mNewParameters[i]);
1278 }
1279
1280 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1281 result.append(buffer);
1282 snprintf(buffer, SIZE, " Index event param\n");
1283 result.append(buffer);
1284 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001285 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 result.append(buffer);
1287 }
1288 result.append("\n");
1289
1290 write(fd, result.string(), result.size());
1291
1292 if (locked) {
1293 mLock.unlock();
1294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295}
1296
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001297void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001298{
1299 const size_t SIZE = 256;
1300 char buffer[SIZE];
1301 String8 result;
1302
1303 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1304 write(fd, buffer, strlen(buffer));
1305
1306 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1307 sp<EffectChain> chain = mEffectChains[i];
1308 if (chain != 0) {
1309 chain->dump(fd, args);
1310 }
1311 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001312}
1313
Eric Laurentfeb0db62011-07-22 09:04:31 -07001314void AudioFlinger::ThreadBase::acquireWakeLock()
1315{
1316 Mutex::Autolock _l(mLock);
1317 acquireWakeLock_l();
1318}
1319
1320void AudioFlinger::ThreadBase::acquireWakeLock_l()
1321{
1322 if (mPowerManager == 0) {
1323 // use checkService() to avoid blocking if power service is not up yet
1324 sp<IBinder> binder =
1325 defaultServiceManager()->checkService(String16("power"));
1326 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001327 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001328 } else {
1329 mPowerManager = interface_cast<IPowerManager>(binder);
1330 binder->linkToDeath(mDeathRecipient);
1331 }
1332 }
1333 if (mPowerManager != 0) {
1334 sp<IBinder> binder = new BBinder();
1335 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1336 binder,
1337 String16(mName));
1338 if (status == NO_ERROR) {
1339 mWakeLockToken = binder;
1340 }
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001342 }
1343}
1344
1345void AudioFlinger::ThreadBase::releaseWakeLock()
1346{
1347 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001348 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001349}
1350
1351void AudioFlinger::ThreadBase::releaseWakeLock_l()
1352{
1353 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001354 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001355 if (mPowerManager != 0) {
1356 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1357 }
1358 mWakeLockToken.clear();
1359 }
1360}
1361
1362void AudioFlinger::ThreadBase::clearPowerManager()
1363{
1364 Mutex::Autolock _l(mLock);
1365 releaseWakeLock_l();
1366 mPowerManager.clear();
1367}
1368
1369void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1370{
1371 sp<ThreadBase> thread = mThread.promote();
1372 if (thread != 0) {
1373 thread->clearPowerManager();
1374 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001375 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001376}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001377
Eric Laurent59255e42011-07-27 19:49:51 -07001378void AudioFlinger::ThreadBase::setEffectSuspended(
1379 const effect_uuid_t *type, bool suspend, int sessionId)
1380{
1381 Mutex::Autolock _l(mLock);
1382 setEffectSuspended_l(type, suspend, sessionId);
1383}
1384
1385void AudioFlinger::ThreadBase::setEffectSuspended_l(
1386 const effect_uuid_t *type, bool suspend, int sessionId)
1387{
Glenn Kasten090f0192012-01-30 13:00:02 -08001388 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001389 if (chain != 0) {
1390 if (type != NULL) {
1391 chain->setEffectSuspended_l(type, suspend);
1392 } else {
1393 chain->setEffectSuspendedAll_l(suspend);
1394 }
1395 }
1396
1397 updateSuspendedSessions_l(type, suspend, sessionId);
1398}
1399
1400void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1401{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001402 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001403 if (index < 0) {
1404 return;
1405 }
1406
Glenn Kasten0a7af182012-07-09 16:09:19 -07001407 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1408 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001409
1410 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001411 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001412 for (int j = 0; j < desc->mRefCount; j++) {
1413 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1414 chain->setEffectSuspendedAll_l(true);
1415 } else {
Steve Block3856b092011-10-20 11:56:00 +01001416 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001417 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001418 chain->setEffectSuspended_l(&desc->mType, true);
1419 }
1420 }
1421 }
1422}
1423
Eric Laurent59255e42011-07-27 19:49:51 -07001424void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1425 bool suspend,
1426 int sessionId)
1427{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001428 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001429
1430 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1431
1432 if (suspend) {
1433 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001434 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001435 } else {
1436 mSuspendedSessions.add(sessionId, sessionEffects);
1437 }
1438 } else {
1439 if (index < 0) {
1440 return;
1441 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001442 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001443 }
1444
1445
1446 int key = EffectChain::kKeyForSuspendAll;
1447 if (type != NULL) {
1448 key = type->timeLow;
1449 }
1450 index = sessionEffects.indexOfKey(key);
1451
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001452 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001453 if (suspend) {
1454 if (index >= 0) {
1455 desc = sessionEffects.valueAt(index);
1456 } else {
1457 desc = new SuspendedSessionDesc();
1458 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001459 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001460 }
1461 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001463 }
1464 desc->mRefCount++;
1465 } else {
1466 if (index < 0) {
1467 return;
1468 }
1469 desc = sessionEffects.valueAt(index);
1470 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001471 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001472 sessionEffects.removeItemsAt(index);
1473 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001474 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001475 sessionId);
1476 mSuspendedSessions.removeItem(sessionId);
1477 }
1478 }
1479 }
1480 if (!sessionEffects.isEmpty()) {
1481 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1482 }
1483}
1484
1485void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1486 bool enabled,
1487 int sessionId)
1488{
1489 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001490 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1491}
Eric Laurent59255e42011-07-27 19:49:51 -07001492
Eric Laurenta85a74a2011-10-19 11:44:54 -07001493void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1494 bool enabled,
1495 int sessionId)
1496{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001497 if (mType != RECORD) {
1498 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1499 // another session. This gives the priority to well behaved effect control panels
1500 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001501 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1502 // global effects
1503 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001504 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1505 }
1506 }
Eric Laurent59255e42011-07-27 19:49:51 -07001507
1508 sp<EffectChain> chain = getEffectChain_l(sessionId);
1509 if (chain != 0) {
1510 chain->checkSuspendOnEffectEnabled(effect, enabled);
1511 }
1512}
1513
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514// ----------------------------------------------------------------------------
1515
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001516AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1517 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001518 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001519 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001520 type_t type)
1521 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001522 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001523 // mStreamTypes[] initialized in constructor body
1524 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001525 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001526 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001527 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001528 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001529 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001530 // index 0 is reserved for normal mixer's submix
1531 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532{
Glenn Kasten480b4682012-02-28 12:30:08 -08001533 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001534
John Grossmanee578c02012-07-23 17:05:46 -07001535 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1536 // it would be safer to explicitly pass initial masterVolume/masterMute as
1537 // parameter.
1538 //
1539 // If the HAL we are using has support for master volume or master mute,
1540 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1541 // and the mute set to false).
1542 mMasterVolume = audioFlinger->masterVolume_l();
1543 mMasterMute = audioFlinger->masterMute_l();
1544 if (mOutput && mOutput->audioHwDev) {
1545 if (mOutput->audioHwDev->canSetMasterVolume()) {
1546 mMasterVolume = 1.0;
1547 }
1548
1549 if (mOutput->audioHwDev->canSetMasterMute()) {
1550 mMasterMute = false;
1551 }
1552 }
1553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 readOutputParameters();
1555
Glenn Kasten263709e2012-01-06 08:40:01 -08001556 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001557 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1558 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1559 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001560 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1561 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001563 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1564 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565}
1566
1567AudioFlinger::PlaybackThread::~PlaybackThread()
1568{
1569 delete [] mMixBuffer;
1570}
1571
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001572void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573{
1574 dumpInternals(fd, args);
1575 dumpTracks(fd, args);
1576 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577}
1578
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001579void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580{
1581 const size_t SIZE = 256;
1582 char buffer[SIZE];
1583 String8 result;
1584
Glenn Kasten58912562012-04-03 10:45:00 -07001585 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1586 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1587 const stream_type_t *st = &mStreamTypes[i];
1588 if (i > 0) {
1589 result.appendFormat(", ");
1590 }
1591 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1592 if (st->mute) {
1593 result.append("M");
1594 }
1595 }
1596 result.append("\n");
1597 write(fd, result.string(), result.length());
1598 result.clear();
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1601 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001602 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 for (size_t i = 0; i < mTracks.size(); ++i) {
1604 sp<Track> track = mTracks[i];
1605 if (track != 0) {
1606 track->dump(buffer, SIZE);
1607 result.append(buffer);
1608 }
1609 }
1610
1611 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1612 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001613 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001615 sp<Track> track = mActiveTracks[i].promote();
1616 if (track != 0) {
1617 track->dump(buffer, SIZE);
1618 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 }
1620 }
1621 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001622
1623 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1624 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1625 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1626 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627}
1628
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001629void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630{
1631 const size_t SIZE = 256;
1632 char buffer[SIZE];
1633 String8 result;
1634
1635 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1636 result.append(buffer);
1637 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1638 result.append(buffer);
1639 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1640 result.append(buffer);
1641 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1642 result.append(buffer);
1643 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1644 result.append(buffer);
1645 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1646 result.append(buffer);
1647 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1648 result.append(buffer);
1649 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001650 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651
1652 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653}
1654
1655// Thread virtuals
1656status_t AudioFlinger::PlaybackThread::readyToRun()
1657{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001658 status_t status = initCheck();
1659 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001660 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001661 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001662 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001664 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665}
1666
1667void AudioFlinger::PlaybackThread::onFirstRef()
1668{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001669 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670}
1671
1672// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001673sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001675 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001677 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001678 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 int frameCount,
1680 const sp<IMemory>& sharedBuffer,
1681 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001682 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001683 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 status_t *status)
1685{
1686 sp<Track> track;
1687 status_t lStatus;
1688
Glenn Kasten73d22752012-03-19 13:38:30 -07001689 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1690
1691 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001692 if (flags & IAudioFlinger::TRACK_FAST) {
1693 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001694 // not timed
1695 (!isTimed) &&
1696 // either of these use cases:
1697 (
1698 // use case 1: shared buffer with any frame count
1699 (
1700 (sharedBuffer != 0)
1701 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001702 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001703 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001704 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001705 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001706 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001707 )
1708 ) &&
1709 // PCM data
1710 audio_is_linear_pcm(format) &&
1711 // mono or stereo
1712 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1713 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001714#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001715 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001716 (sampleRate == mSampleRate) &&
1717#endif
1718 // normal mixer has an associated fast mixer
1719 hasFastMixer() &&
1720 // there are sufficient fast track slots available
1721 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001722 // FIXME test that MixerThread for this fast track has a capable output HAL
1723 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001724 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001725 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1726 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001727 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001728 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001729 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001730 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001731 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001732 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001733 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001734 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1735 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1736 audio_is_linear_pcm(format),
1737 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001738 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001739 // For compatibility with AudioTrack calculation, buffer depth is forced
1740 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1741 // This is probably too conservative, but legacy application code may depend on it.
1742 // If you change this calculation, also review the start threshold which is related.
1743 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1744 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1745 if (minBufCount < 2) {
1746 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001747 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001748 int minFrameCount = mNormalFrameCount * minBufCount;
1749 if (frameCount < minFrameCount) {
1750 frameCount = minFrameCount;
1751 }
1752 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001753 }
1754
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001756 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1757 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001758 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001759 "for output %p with format %d",
1760 sampleRate, format, channelMask, mOutput, mFormat);
1761 lStatus = BAD_VALUE;
1762 goto Exit;
1763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765 } else {
1766 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1767 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001768 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 lStatus = BAD_VALUE;
1770 goto Exit;
1771 }
1772 }
1773
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001774 lStatus = initCheck();
1775 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001776 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 goto Exit;
1778 }
1779
1780 { // scope for mLock
1781 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001782
1783 // all tracks in same audio session must share the same routing strategy otherwise
1784 // conflicts will happen when tracks are moved from one output to another by audio policy
1785 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001786 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001787 for (size_t i = 0; i < mTracks.size(); ++i) {
1788 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001789 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001790 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001791 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001792 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001793 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001794 lStatus = BAD_VALUE;
1795 goto Exit;
1796 }
1797 }
1798 }
1799
John Grossman4ff14ba2012-02-08 16:37:41 -08001800 if (!isTimed) {
1801 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001802 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001803 } else {
1804 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1805 channelMask, frameCount, sharedBuffer, sessionId);
1806 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001807 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 lStatus = NO_MEMORY;
1809 goto Exit;
1810 }
1811 mTracks.add(track);
1812
1813 sp<EffectChain> chain = getEffectChain_l(sessionId);
1814 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001815 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001817 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001818 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 }
1820 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001821
Glenn Kasten3acbd052012-02-28 10:39:56 -08001822 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1823 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1824 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1825 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001826 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001827 if (err != 0) {
1828 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001829 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001830 }
1831 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 lStatus = NO_ERROR;
1834
1835Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001836 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 *status = lStatus;
1838 }
1839 return track;
1840}
1841
Eric Laurente737cda2012-05-22 18:55:44 -07001842uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1843{
1844 if (mFastMixer != NULL) {
1845 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1846 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1847 }
1848 return latency;
1849}
1850
1851uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1852{
1853 return latency;
1854}
1855
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856uint32_t AudioFlinger::PlaybackThread::latency() const
1857{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001858 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001859 return latency_l();
1860}
1861uint32_t AudioFlinger::PlaybackThread::latency_l() const
1862{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001863 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001864 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001865 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 return 0;
1867 }
1868}
1869
Glenn Kasten6637baa2012-01-09 09:40:36 -08001870void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001872 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001873 // Don't apply master volume in SW if our HAL can do it for us.
1874 if (mOutput && mOutput->audioHwDev &&
1875 mOutput->audioHwDev->canSetMasterVolume()) {
1876 mMasterVolume = 1.0;
1877 } else {
1878 mMasterVolume = value;
1879 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880}
1881
Glenn Kasten6637baa2012-01-09 09:40:36 -08001882void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001884 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001885 // Don't apply master mute in SW if our HAL can do it for us.
1886 if (mOutput && mOutput->audioHwDev &&
1887 mOutput->audioHwDev->canSetMasterMute()) {
1888 mMasterMute = false;
1889 } else {
1890 mMasterMute = muted;
1891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892}
1893
Glenn Kasten6637baa2012-01-09 09:40:36 -08001894void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001896 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898}
1899
Glenn Kasten6637baa2012-01-09 09:40:36 -08001900void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001902 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904}
1905
Glenn Kastenfff6d712012-01-12 16:38:12 -08001906float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001908 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 return mStreamTypes[stream].volume;
1910}
1911
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912// addTrack_l() must be called with ThreadBase::mLock held
1913status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1914{
1915 status_t status = ALREADY_EXISTS;
1916
1917 // set retry count for buffer fill
1918 track->mRetryCount = kMaxTrackStartupRetries;
1919 if (mActiveTracks.indexOf(track) < 0) {
1920 // the track is newly added, make sure it fills up all its
1921 // buffers before playing. This is to ensure the client will
1922 // effectively get the latency it requested.
1923 track->mFillingUpStatus = Track::FS_FILLING;
1924 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001925 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 mActiveTracks.add(track);
1927 if (track->mainBuffer() != mMixBuffer) {
1928 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1929 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001930 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001931 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 }
1933 }
1934
1935 status = NO_ERROR;
1936 }
1937
Steve Block3856b092011-10-20 11:56:00 +01001938 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 mWaitWorkCV.broadcast();
1940
1941 return status;
1942}
1943
1944// destroyTrack_l() must be called with ThreadBase::mLock held
1945void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1946{
1947 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001948 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001950 removeTrack_l(track);
1951 }
1952}
1953
1954void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1955{
Eric Laurent29864602012-05-08 18:57:51 -07001956 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001957 mTracks.remove(track);
1958 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001959 // redundant as track is about to be destroyed, for dumpsys only
1960 track->mName = -1;
1961 if (track->isFastTrack()) {
1962 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001963 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001964 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1965 mFastTrackAvailMask |= 1 << index;
1966 // redundant as track is about to be destroyed, for dumpsys only
1967 track->mFastIndex = -1;
1968 }
Eric Laurentb469b942011-05-09 12:09:06 -07001969 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1970 if (chain != 0) {
1971 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973}
1974
1975String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1976{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001977 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001978 char *s;
1979
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001980 Mutex::Autolock _l(mLock);
1981 if (initCheck() != NO_ERROR) {
1982 return out_s8;
1983 }
1984
Dima Zavin799a70e2011-04-18 16:57:27 -07001985 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001986 out_s8 = String8(s);
1987 free(s);
1988 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989}
1990
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001991// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1993 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001994 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995
Steve Block3856b092011-10-20 11:56:00 +01001996 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
1998 switch (event) {
1999 case AudioSystem::OUTPUT_OPENED:
2000 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002001 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 desc.samplingRate = mSampleRate;
2003 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002004 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 desc.latency = latency();
2006 param2 = &desc;
2007 break;
2008
2009 case AudioSystem::STREAM_CONFIG_CHANGED:
2010 param2 = &param;
2011 case AudioSystem::OUTPUT_CLOSED:
2012 default:
2013 break;
2014 }
2015 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2016}
2017
2018void AudioFlinger::PlaybackThread::readOutputParameters()
2019{
Dima Zavin799a70e2011-04-18 16:57:27 -07002020 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002021 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2022 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002023 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002024 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002025 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002026 if (mFrameCount & 15) {
2027 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2028 mFrameCount);
2029 }
2030
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002031 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002032 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002033 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002034 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002035 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2036 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2037 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2038 maxNormalFrameCount = maxNormalFrameCount & ~15;
2039 if (maxNormalFrameCount < minNormalFrameCount) {
2040 maxNormalFrameCount = minNormalFrameCount;
2041 }
2042 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2043 if (multiplier <= 1.0) {
2044 multiplier = 1.0;
2045 } else if (multiplier <= 2.0) {
2046 if (2 * mFrameCount <= maxNormalFrameCount) {
2047 multiplier = 2.0;
2048 } else {
2049 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2050 }
2051 } else {
2052 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2053 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2054 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2055 // FIXME this rounding up should not be done if no HAL SRC
2056 uint32_t truncMult = (uint32_t) multiplier;
2057 if ((truncMult & 1)) {
2058 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2059 ++truncMult;
2060 }
2061 }
2062 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002063 }
Glenn Kasten58912562012-04-03 10:45:00 -07002064 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002065 mNormalFrameCount = multiplier * mFrameCount;
2066 // round up to nearest 16 frames to satisfy AudioMixer
2067 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002068 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069
Glenn Kastene9dd0172012-01-27 18:08:45 -08002070 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002071 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2072 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073
Eric Laurentde070132010-07-13 04:45:46 -07002074 // force reconfiguration of effect chains and engines to take new buffer size and audio
2075 // parameters into account
2076 // Note that mLock is not held when readOutputParameters() is called from the constructor
2077 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2078 // matter.
2079 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2080 Vector< sp<EffectChain> > effectChains = mEffectChains;
2081 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002082 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084}
2085
Eric Laurente737cda2012-05-22 18:55:44 -07002086
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2088{
Glenn Kastena0d68332012-01-27 16:47:15 -08002089 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 return BAD_VALUE;
2091 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002092 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002093 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 return INVALID_OPERATION;
2095 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002096 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097
Dima Zavin799a70e2011-04-18 16:57:27 -07002098 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099}
2100
Glenn Kasten106e8a42012-08-02 13:37:12 -07002101uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102{
2103 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002104 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002106 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 }
2108
2109 for (size_t i = 0; i < mTracks.size(); ++i) {
2110 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002111 if (sessionId == track->sessionId() &&
2112 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002113 result |= TRACK_SESSION;
2114 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 }
2116 }
2117
Eric Laurent39e94f82010-07-28 01:32:47 -07002118 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119}
2120
Eric Laurentde070132010-07-13 04:45:46 -07002121uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2122{
Dima Zavinfce7a472011-04-19 22:30:36 -07002123 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002124 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002125 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2126 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002127 }
2128 for (size_t i = 0; i < mTracks.size(); i++) {
2129 sp<Track> track = mTracks[i];
2130 if (sessionId == track->sessionId() &&
2131 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002132 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002133 }
2134 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002135 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002136}
2137
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138
Glenn Kastenaed850d2012-01-26 09:46:34 -08002139AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002140{
2141 Mutex::Autolock _l(mLock);
2142 return mOutput;
2143}
2144
2145AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2146{
2147 Mutex::Autolock _l(mLock);
2148 AudioStreamOut *output = mOutput;
2149 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002150 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2151 // must push a NULL and wait for ack
2152 mOutputSink.clear();
2153 mPipeSink.clear();
2154 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002155 return output;
2156}
2157
2158// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002159audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002160{
2161 if (mOutput == NULL) {
2162 return NULL;
2163 }
2164 return &mOutput->stream->common;
2165}
2166
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002167uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002168{
Eric Laurentab9071b2012-06-04 13:45:29 -07002169 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002170}
2171
Eric Laurenta011e352012-03-29 15:51:43 -07002172status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2173{
2174 if (!isValidSyncEvent(event)) {
2175 return BAD_VALUE;
2176 }
2177
2178 Mutex::Autolock _l(mLock);
2179
2180 for (size_t i = 0; i < mTracks.size(); ++i) {
2181 sp<Track> track = mTracks[i];
2182 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002183 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002184 return NO_ERROR;
2185 }
2186 }
2187
2188 return NAME_NOT_FOUND;
2189}
2190
Glenn Kasten106e8a42012-08-02 13:37:12 -07002191bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002192{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002193 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002194}
2195
Eric Laurent44a957f2012-05-15 15:26:05 -07002196void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2197{
2198 size_t count = tracksToRemove.size();
2199 if (CC_UNLIKELY(count)) {
2200 for (size_t i = 0 ; i < count ; i++) {
2201 const sp<Track>& track = tracksToRemove.itemAt(i);
2202 if ((track->sharedBuffer() != 0) &&
2203 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2204 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2205 }
2206 }
2207 }
2208
2209}
2210
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211// ----------------------------------------------------------------------------
2212
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002213AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002214 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002215 : PlaybackThread(audioFlinger, output, id, device, type),
2216 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002217 // mFastMixer below
2218 mFastMixerFutex(0)
2219 // mOutputSink below
2220 // mPipeSink below
2221 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002223 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002224 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002225 "mFrameCount=%d, mNormalFrameCount=%d",
2226 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2227 mNormalFrameCount);
2228 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2229
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002231 if (mChannelCount != FCC_2) {
2232 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 }
Glenn Kasten58912562012-04-03 10:45:00 -07002234
2235 // create an NBAIO sink for the HAL output stream, and negotiate
2236 mOutputSink = new AudioStreamOutSink(output->stream);
2237 size_t numCounterOffers = 0;
2238 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2239 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2240 ALOG_ASSERT(index == 0);
2241
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002242 // initialize fast mixer depending on configuration
2243 bool initFastMixer;
2244 switch (kUseFastMixer) {
2245 case FastMixer_Never:
2246 initFastMixer = false;
2247 break;
2248 case FastMixer_Always:
2249 initFastMixer = true;
2250 break;
2251 case FastMixer_Static:
2252 case FastMixer_Dynamic:
2253 initFastMixer = mFrameCount < mNormalFrameCount;
2254 break;
2255 }
2256 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002257
2258 // create a MonoPipe to connect our submix to FastMixer
2259 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002260 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2261 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2262 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2263 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002264 const NBAIO_Format offers[1] = {format};
2265 size_t numCounterOffers = 0;
2266 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2267 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002268 monoPipe->setAvgFrames((mScreenState & 1) ?
2269 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002270 mPipeSink = monoPipe;
2271
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002272#ifdef TEE_SINK_FRAMES
2273 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2274 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2275 numCounterOffers = 0;
2276 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2277 ALOG_ASSERT(index == 0);
2278 mTeeSink = teeSink;
2279 PipeReader *teeSource = new PipeReader(*teeSink);
2280 numCounterOffers = 0;
2281 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2282 ALOG_ASSERT(index == 0);
2283 mTeeSource = teeSource;
2284#endif
2285
Glenn Kasten58912562012-04-03 10:45:00 -07002286 // create fast mixer and configure it initially with just one fast track for our submix
2287 mFastMixer = new FastMixer();
2288 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002289#ifdef STATE_QUEUE_DUMP
2290 sq->setObserverDump(&mStateQueueObserverDump);
2291 sq->setMutatorDump(&mStateQueueMutatorDump);
2292#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002293 FastMixerState *state = sq->begin();
2294 FastTrack *fastTrack = &state->mFastTracks[0];
2295 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2296 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2297 fastTrack->mVolumeProvider = NULL;
2298 fastTrack->mGeneration++;
2299 state->mFastTracksGen++;
2300 state->mTrackMask = 1;
2301 // fast mixer will use the HAL output sink
2302 state->mOutputSink = mOutputSink.get();
2303 state->mOutputSinkGen++;
2304 state->mFrameCount = mFrameCount;
2305 state->mCommand = FastMixerState::COLD_IDLE;
2306 // already done in constructor initialization list
2307 //mFastMixerFutex = 0;
2308 state->mColdFutexAddr = &mFastMixerFutex;
2309 state->mColdGen++;
2310 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002311 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002312 sq->end();
2313 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2314
2315 // start the fast mixer
2316 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002317 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002318 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002319 if (err != 0) {
2320 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002321 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002322 }
Glenn Kasten58912562012-04-03 10:45:00 -07002323
Glenn Kastenc15d6652012-05-30 14:52:57 -07002324#ifdef AUDIO_WATCHDOG
2325 // create and start the watchdog
2326 mAudioWatchdog = new AudioWatchdog();
2327 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2328 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2329 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002330 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002331 if (err != 0) {
2332 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002333 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002334 }
2335#endif
2336
Glenn Kasten58912562012-04-03 10:45:00 -07002337 } else {
2338 mFastMixer = NULL;
2339 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002340
2341 switch (kUseFastMixer) {
2342 case FastMixer_Never:
2343 case FastMixer_Dynamic:
2344 mNormalSink = mOutputSink;
2345 break;
2346 case FastMixer_Always:
2347 mNormalSink = mPipeSink;
2348 break;
2349 case FastMixer_Static:
2350 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2351 break;
2352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353}
2354
2355AudioFlinger::MixerThread::~MixerThread()
2356{
Glenn Kasten58912562012-04-03 10:45:00 -07002357 if (mFastMixer != NULL) {
2358 FastMixerStateQueue *sq = mFastMixer->sq();
2359 FastMixerState *state = sq->begin();
2360 if (state->mCommand == FastMixerState::COLD_IDLE) {
2361 int32_t old = android_atomic_inc(&mFastMixerFutex);
2362 if (old == -1) {
2363 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2364 }
2365 }
2366 state->mCommand = FastMixerState::EXIT;
2367 sq->end();
2368 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2369 mFastMixer->join();
2370 // Though the fast mixer thread has exited, it's state queue is still valid.
2371 // We'll use that extract the final state which contains one remaining fast track
2372 // corresponding to our sub-mix.
2373 state = sq->begin();
2374 ALOG_ASSERT(state->mTrackMask == 1);
2375 FastTrack *fastTrack = &state->mFastTracks[0];
2376 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2377 delete fastTrack->mBufferProvider;
2378 sq->end(false /*didModify*/);
2379 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002380 if (mAudioWatchdog != 0) {
2381 mAudioWatchdog->requestExit();
2382 mAudioWatchdog->requestExitAndWait();
2383 mAudioWatchdog.clear();
2384 }
Glenn Kasten58912562012-04-03 10:45:00 -07002385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 delete mAudioMixer;
2387}
2388
Glenn Kasten83efdd02012-02-24 07:21:32 -08002389class CpuStats {
2390public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002391 CpuStats();
2392 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002393#ifdef DEBUG_CPU_USAGE
2394private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002395 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2396 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2397
2398 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2399
2400 int mCpuNum; // thread's current CPU number
2401 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002402#endif
2403};
2404
Glenn Kasten190a46f2012-03-06 11:27:10 -08002405CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002406#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002407 : mCpuNum(-1), mCpukHz(-1)
2408#endif
2409{
2410}
2411
2412void CpuStats::sample(const String8 &title) {
2413#ifdef DEBUG_CPU_USAGE
2414 // get current thread's delta CPU time in wall clock ns
2415 double wcNs;
2416 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2417
2418 // record sample for wall clock statistics
2419 if (valid) {
2420 mWcStats.sample(wcNs);
2421 }
2422
2423 // get the current CPU number
2424 int cpuNum = sched_getcpu();
2425
2426 // get the current CPU frequency in kHz
2427 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2428
2429 // check if either CPU number or frequency changed
2430 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2431 mCpuNum = cpuNum;
2432 mCpukHz = cpukHz;
2433 // ignore sample for purposes of cycles
2434 valid = false;
2435 }
2436
2437 // if no change in CPU number or frequency, then record sample for cycle statistics
2438 if (valid && mCpukHz > 0) {
2439 double cycles = wcNs * cpukHz * 0.000001;
2440 mHzStats.sample(cycles);
2441 }
2442
2443 unsigned n = mWcStats.n();
2444 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002445 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002446 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002447 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2448 double perLoop = elapsed / (double) n;
2449 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002450 double perLoop1k = perLoop * 0.001;
2451 double mean = mWcStats.mean();
2452 double stddev = mWcStats.stddev();
2453 double minimum = mWcStats.minimum();
2454 double maximum = mWcStats.maximum();
2455 double meanCycles = mHzStats.mean();
2456 double stddevCycles = mHzStats.stddev();
2457 double minCycles = mHzStats.minimum();
2458 double maxCycles = mHzStats.maximum();
2459 mCpuUsage.resetElapsed();
2460 mWcStats.reset();
2461 mHzStats.reset();
2462 ALOGD("CPU usage for %s over past %.1f secs\n"
2463 " (%u mixer loops at %.1f mean ms per loop):\n"
2464 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2465 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2466 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2467 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002468 elapsed * .000000001, n, perLoop * .000001,
2469 mean * .001,
2470 stddev * .001,
2471 minimum * .001,
2472 maximum * .001,
2473 mean / perLoop100,
2474 stddev / perLoop100,
2475 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002476 maximum / perLoop100,
2477 meanCycles / perLoop1k,
2478 stddevCycles / perLoop1k,
2479 minCycles / perLoop1k,
2480 maxCycles / perLoop1k);
2481
Glenn Kasten83efdd02012-02-24 07:21:32 -08002482 }
2483 }
2484#endif
2485};
2486
Glenn Kasten37d825e2012-02-24 07:21:48 -08002487void AudioFlinger::PlaybackThread::checkSilentMode_l()
2488{
2489 if (!mMasterMute) {
2490 char value[PROPERTY_VALUE_MAX];
2491 if (property_get("ro.audio.silent", value, "0") > 0) {
2492 char *endptr;
2493 unsigned long ul = strtoul(value, &endptr, 0);
2494 if (*endptr == '\0' && ul != 0) {
2495 ALOGD("Silence is golden");
2496 // The setprop command will not allow a property to be changed after
2497 // the first time it is set, so we don't have to worry about un-muting.
2498 setMasterMute_l(true);
2499 }
2500 }
2501 }
2502}
2503
Glenn Kasten000f0e32012-03-01 17:10:56 -08002504bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505{
2506 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002507
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002509
2510 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002512
Glenn Kasten000f0e32012-03-01 17:10:56 -08002513 // DUPLICATING
2514 // FIXME could this be made local to while loop?
2515 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002516
Glenn Kasten66fcab92012-02-24 14:59:21 -08002517 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002518 sleepTime = idleSleepTime;
2519
Glenn Kasten9f34a362012-03-20 16:46:41 -07002520 if (mType == MIXER) {
2521 sleepTimeShift = 0;
2522 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002523
Glenn Kasten83efdd02012-02-24 07:21:32 -08002524 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002525 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526
Eric Laurentfeb0db62011-07-22 09:04:31 -07002527 acquireWakeLock();
2528
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 while (!exitPending())
2530 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002531 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002532
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002533 Vector< sp<EffectChain> > effectChains;
2534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 processConfigEvents();
2536
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 { // scope for mLock
2538
2539 Mutex::Autolock _l(mLock);
2540
2541 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002542 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 }
2544
Glenn Kastenfa26a852012-03-06 11:28:04 -08002545 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002546
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002548 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002549 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002551
2552 threadLoop_standby();
2553
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 mStandby = true;
2555 mBytesWritten = 0;
2556 }
2557
Glenn Kasten3e074702012-02-28 18:40:35 -08002558 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 // we're about to wait, flush the binder command buffer
2560 IPCThreadState::self()->flushCommands();
2561
Glenn Kastenfa26a852012-03-06 11:28:04 -08002562 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 if (exitPending()) break;
2565
Eric Laurentfeb0db62011-07-22 09:04:31 -07002566 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002568 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002570 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002571 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572
Eric Laurentda747442012-04-25 18:53:13 -07002573 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002574 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575
Glenn Kasten37d825e2012-02-24 07:21:48 -08002576 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577
Glenn Kasten000f0e32012-03-01 17:10:56 -08002578 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002580 if (mType == MIXER) {
2581 sleepTimeShift = 0;
2582 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002583
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584 continue;
2585 }
2586 }
2587
Glenn Kasten81028042012-04-30 18:15:12 -07002588 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002589 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590
2591 // prevent any changes in effect chain list and in each effect chain
2592 // during mixing and effect process as the audio buffers could be deleted
2593 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002594 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596
Glenn Kastenfec279f2012-03-08 07:47:15 -08002597 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002598 threadLoop_mix();
2599 } else {
2600 threadLoop_sleepTime();
2601 }
2602
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002603 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002604 sleepTime = suspendSleepTimeUs();
2605 }
2606
2607 // only process effects if we're going to write
2608 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002609 for (size_t i = 0; i < effectChains.size(); i ++) {
2610 effectChains[i]->process_l();
2611 }
2612 }
2613
2614 // enable changes in effect chain
2615 unlockEffectChains(effectChains);
2616
2617 // sleepTime == 0 means we must write to audio hardware
2618 if (sleepTime == 0) {
2619
2620 threadLoop_write();
2621
2622if (mType == MIXER) {
2623 // write blocked detection
2624 nsecs_t now = systemTime();
2625 nsecs_t delta = now - mLastWriteTime;
2626 if (!mStandby && delta > maxPeriod) {
2627 mNumDelayedWrites++;
2628 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002629#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002630 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002631#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002632 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2633 ns2ms(delta), mNumDelayedWrites, this);
2634 lastWarning = now;
2635 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636 }
2637}
2638
2639 mStandby = false;
2640 } else {
2641 usleep(sleepTime);
2642 }
2643
Glenn Kasten58912562012-04-03 10:45:00 -07002644 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002645 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002646 // same lock. This will also mutate and push a new fast mixer state.
2647 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002648 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002649
Glenn Kastenfa26a852012-03-06 11:28:04 -08002650 // FIXME I don't understand the need for this here;
2651 // it was in the original code but maybe the
2652 // assignment in saveOutputTracks() makes this unnecessary?
2653 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002654
2655 // Effect chains will be actually deleted here if they were removed from
2656 // mEffectChains list during mixing or effects processing
2657 effectChains.clear();
2658
2659 // FIXME Note that the above .clear() is no longer necessary since effectChains
2660 // is now local to this block, but will keep it for now (at least until merge done).
2661 }
2662
Glenn Kasten9f34a362012-03-20 16:46:41 -07002663 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2664 if (mType == MIXER || mType == DIRECT) {
2665 // put output stream into standby mode
2666 if (!mStandby) {
2667 mOutput->stream->common.standby(&mOutput->stream->common);
2668 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002669 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002670
2671 releaseWakeLock();
2672
2673 ALOGV("Thread %p type %d exiting", this, mType);
2674 return false;
2675}
2676
Glenn Kasten58912562012-04-03 10:45:00 -07002677void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2678{
Glenn Kasten58912562012-04-03 10:45:00 -07002679 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2680}
2681
2682void AudioFlinger::MixerThread::threadLoop_write()
2683{
2684 // FIXME we should only do one push per cycle; confirm this is true
2685 // Start the fast mixer if it's not already running
2686 if (mFastMixer != NULL) {
2687 FastMixerStateQueue *sq = mFastMixer->sq();
2688 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002689 if (state->mCommand != FastMixerState::MIX_WRITE &&
2690 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002691 if (state->mCommand == FastMixerState::COLD_IDLE) {
2692 int32_t old = android_atomic_inc(&mFastMixerFutex);
2693 if (old == -1) {
2694 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2695 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002696 if (mAudioWatchdog != 0) {
2697 mAudioWatchdog->resume();
2698 }
Glenn Kasten58912562012-04-03 10:45:00 -07002699 }
2700 state->mCommand = FastMixerState::MIX_WRITE;
2701 sq->end();
2702 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002703 if (kUseFastMixer == FastMixer_Dynamic) {
2704 mNormalSink = mPipeSink;
2705 }
Glenn Kasten58912562012-04-03 10:45:00 -07002706 } else {
2707 sq->end(false /*didModify*/);
2708 }
2709 }
2710 PlaybackThread::threadLoop_write();
2711}
2712
Glenn Kasten000f0e32012-03-01 17:10:56 -08002713// shared by MIXER and DIRECT, overridden by DUPLICATING
2714void AudioFlinger::PlaybackThread::threadLoop_write()
2715{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002716 // FIXME rewrite to reduce number of system calls
2717 mLastWriteTime = systemTime();
2718 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002719 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002720
Eric Laurent67c0a582012-05-01 19:31:12 -07002721 // If an NBAIO sink is present, use it to write the normal mixer's submix
2722 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002723#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002724 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002725#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002726 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002727#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002728 // update the setpoint when gScreenState changes
2729 uint32_t screenState = gScreenState;
2730 if (screenState != mScreenState) {
2731 mScreenState = screenState;
2732 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2733 if (pipe != NULL) {
2734 pipe->setAvgFrames((mScreenState & 1) ?
2735 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2736 }
2737 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002738 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002739#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002740 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002741#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002742 if (framesWritten > 0) {
2743 bytesWritten = framesWritten << mBitShift;
2744 } else {
2745 bytesWritten = framesWritten;
2746 }
2747 // otherwise use the HAL / AudioStreamOut directly
2748 } else {
2749 // Direct output thread.
2750 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002751 }
2752
Eric Laurent67c0a582012-05-01 19:31:12 -07002753 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002754 mNumWrites++;
2755 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002756}
2757
Glenn Kasten58912562012-04-03 10:45:00 -07002758void AudioFlinger::MixerThread::threadLoop_standby()
2759{
2760 // Idle the fast mixer if it's currently running
2761 if (mFastMixer != NULL) {
2762 FastMixerStateQueue *sq = mFastMixer->sq();
2763 FastMixerState *state = sq->begin();
2764 if (!(state->mCommand & FastMixerState::IDLE)) {
2765 state->mCommand = FastMixerState::COLD_IDLE;
2766 state->mColdFutexAddr = &mFastMixerFutex;
2767 state->mColdGen++;
2768 mFastMixerFutex = 0;
2769 sq->end();
2770 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2771 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002772 if (kUseFastMixer == FastMixer_Dynamic) {
2773 mNormalSink = mOutputSink;
2774 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002775 if (mAudioWatchdog != 0) {
2776 mAudioWatchdog->pause();
2777 }
Glenn Kasten58912562012-04-03 10:45:00 -07002778 } else {
2779 sq->end(false /*didModify*/);
2780 }
2781 }
2782 PlaybackThread::threadLoop_standby();
2783}
2784
Glenn Kasten000f0e32012-03-01 17:10:56 -08002785// shared by MIXER and DIRECT, overridden by DUPLICATING
2786void AudioFlinger::PlaybackThread::threadLoop_standby()
2787{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002788 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002790}
2791
2792void AudioFlinger::MixerThread::threadLoop_mix()
2793{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 // obtain the presentation timestamp of the next output buffer
2795 int64_t pts;
2796 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002797
John Grossman2c3b2da2012-08-02 17:08:54 -07002798 if (mNormalSink != 0) {
2799 status = mNormalSink->getNextWriteTimestamp(&pts);
2800 } else {
2801 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002802 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002803
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 if (status != NO_ERROR) {
2805 pts = AudioBufferProvider::kInvalidPTS;
2806 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002807
Glenn Kasten952eeb22012-03-06 11:30:57 -08002808 // mix buffers...
2809 mAudioMixer->process(pts);
2810 // increase sleep time progressively when application underrun condition clears.
2811 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2812 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2813 // such that we would underrun the audio HAL.
2814 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2815 sleepTimeShift--;
2816 }
2817 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002818 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002819 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002820}
2821
2822void AudioFlinger::MixerThread::threadLoop_sleepTime()
2823{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002824 // If no tracks are ready, sleep once for the duration of an output
2825 // buffer size, then write 0s to the output
2826 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002827 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002828 sleepTime = activeSleepTime >> sleepTimeShift;
2829 if (sleepTime < kMinThreadSleepTimeUs) {
2830 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 // reduce sleep time in case of consecutive application underruns to avoid
2833 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2834 // duration we would end up writing less data than needed by the audio HAL if
2835 // the condition persists.
2836 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2837 sleepTimeShift++;
2838 }
2839 } else {
2840 sleepTime = idleSleepTime;
2841 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002842 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002843 memset (mMixBuffer, 0, mixBufferSize);
2844 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002845 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002846 }
2847 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848}
2849
2850// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002851AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002852 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853{
2854
Glenn Kasten29c23c32012-01-26 13:37:52 -08002855 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002857 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 size_t mixedTracks = 0;
2859 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002860 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002861 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002862 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863
2864 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002865 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866
Eric Laurent571d49c2010-08-11 05:20:11 -07002867 if (masterMute) {
2868 masterVolume = 0;
2869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002871 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002873 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002874 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 masterVolume = (float)((v + (1 << 23)) >> 24);
2876 chain.clear();
2877 }
2878
Glenn Kasten288ed212012-04-25 17:52:27 -07002879 // prepare a new state to push
2880 FastMixerStateQueue *sq = NULL;
2881 FastMixerState *state = NULL;
2882 bool didModify = false;
2883 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2884 if (mFastMixer != NULL) {
2885 sq = mFastMixer->sq();
2886 state = sq->begin();
2887 }
2888
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002890 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 if (t == 0) continue;
2892
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002893 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002895
Glenn Kasten288ed212012-04-25 17:52:27 -07002896 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002897 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002898
2899 // It's theoretically possible (though unlikely) for a fast track to be created
2900 // and then removed within the same normal mix cycle. This is not a problem, as
2901 // the track never becomes active so it's fast mixer slot is never touched.
2902 // The converse, of removing an (active) track and then creating a new track
2903 // at the identical fast mixer slot within the same normal mix cycle,
2904 // is impossible because the slot isn't marked available until the end of each cycle.
2905 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002906 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2907 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002908 FastTrack *fastTrack = &state->mFastTracks[j];
2909
2910 // Determine whether the track is currently in underrun condition,
2911 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002912 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2913 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002914 uint32_t recentFull = (underruns.mBitFields.mFull -
2915 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2916 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2917 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2918 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2919 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2920 uint32_t recentUnderruns = recentPartial + recentEmpty;
2921 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002922 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002923 // or stopped which can occur when flush() is called while active
2924 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002925 track->mUnderrunCount += recentUnderruns;
2926 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002927
Glenn Kastend08f48c2012-05-01 18:14:02 -07002928 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002929 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002930 bool isActive = true;
2931 switch (track->mState) {
2932 case TrackBase::STOPPING_1:
2933 // track stays active in STOPPING_1 state until first underrun
2934 if (recentUnderruns > 0) {
2935 track->mState = TrackBase::STOPPING_2;
2936 }
2937 break;
2938 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002940 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002941 break;
2942 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002943 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002944 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002945 break;
2946 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002947 if (recentFull > 0 || recentPartial > 0) {
2948 // track has provided at least some frames recently: reset retry count
2949 track->mRetryCount = kMaxTrackRetries;
2950 }
2951 if (recentUnderruns == 0) {
2952 // no recent underruns: stay active
2953 break;
2954 }
2955 // there has recently been an underrun of some kind
2956 if (track->sharedBuffer() == 0) {
2957 // were any of the recent underruns "empty" (no frames available)?
2958 if (recentEmpty == 0) {
2959 // no, then ignore the partial underruns as they are allowed indefinitely
2960 break;
2961 }
2962 // there has recently been an "empty" underrun: decrement the retry counter
2963 if (--(track->mRetryCount) > 0) {
2964 break;
2965 }
2966 // indicate to client process that the track was disabled because of underrun;
2967 // it will then automatically call start() when data is available
2968 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2969 // remove from active list, but state remains ACTIVE [confusing but true]
2970 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002971 break;
2972 }
2973 // fall through
2974 case TrackBase::STOPPING_2:
2975 case TrackBase::PAUSED:
2976 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002977 case TrackBase::STOPPED:
2978 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002979 // Check for presentation complete if track is inactive
2980 // We have consumed all the buffers of this track.
2981 // This would be incomplete if we auto-paused on underrun
2982 {
2983 size_t audioHALFrames =
2984 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2985 size_t framesWritten =
2986 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2987 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2988 // track stays in active list until presentation is complete
2989 break;
2990 }
2991 }
2992 if (track->isStopping_2()) {
2993 track->mState = TrackBase::STOPPED;
2994 }
2995 if (track->isStopped()) {
2996 // Can't reset directly, as fast mixer is still polling this track
2997 // track->reset();
2998 // So instead mark this track as needing to be reset after push with ack
2999 resetMask |= 1 << i;
3000 }
3001 isActive = false;
3002 break;
3003 case TrackBase::IDLE:
3004 default:
3005 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003006 }
3007
3008 if (isActive) {
3009 // was it previously inactive?
3010 if (!(state->mTrackMask & (1 << j))) {
3011 ExtendedAudioBufferProvider *eabp = track;
3012 VolumeProvider *vp = track;
3013 fastTrack->mBufferProvider = eabp;
3014 fastTrack->mVolumeProvider = vp;
3015 fastTrack->mSampleRate = track->mSampleRate;
3016 fastTrack->mChannelMask = track->mChannelMask;
3017 fastTrack->mGeneration++;
3018 state->mTrackMask |= 1 << j;
3019 didModify = true;
3020 // no acknowledgement required for newly active tracks
3021 }
3022 // cache the combined master volume and stream type volume for fast mixer; this
3023 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3024 track->mCachedVolume = track->isMuted() ?
3025 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3026 ++fastTracks;
3027 } else {
3028 // was it previously active?
3029 if (state->mTrackMask & (1 << j)) {
3030 fastTrack->mBufferProvider = NULL;
3031 fastTrack->mGeneration++;
3032 state->mTrackMask &= ~(1 << j);
3033 didModify = true;
3034 // If any fast tracks were removed, we must wait for acknowledgement
3035 // because we're about to decrement the last sp<> on those tracks.
3036 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003037 } else {
3038 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003039 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003040 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003041 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003042 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003043 }
3044 continue;
3045 }
3046
3047 { // local variable scope to avoid goto warning
3048
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 audio_track_cblk_t* cblk = track->cblk();
3050
3051 // The first time a track is added we wait
3052 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003053 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003054 // make sure that we have enough frames to mix one full buffer.
3055 // enforce this condition only once to enable draining the buffer in case the client
3056 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003057 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003058 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003059 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003060 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003061 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003062 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003063 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003064 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003065 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003066 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003067 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003068 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003069 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3070 // the minimum track buffer size is normally twice the number of frames necessary
3071 // to fill one buffer and the resampler should not leave more than one buffer worth
3072 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003073 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003074 }
3075 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003076 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 !track->isPaused() && !track->isTerminated())
3078 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003079 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080
3081 mixedTracks++;
3082
3083 // track->mainBuffer() != mMixBuffer means there is an effect chain
3084 // connected to the track
3085 chain.clear();
3086 if (track->mainBuffer() != mMixBuffer) {
3087 chain = getEffectChain_l(track->sessionId());
3088 // Delegate volume control to effect in track effect chain if needed
3089 if (chain != 0) {
3090 tracksWithEffect++;
3091 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003092 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003093 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
3095 }
3096
3097
3098 int param = AudioMixer::VOLUME;
3099 if (track->mFillingUpStatus == Track::FS_FILLED) {
3100 // no ramp for the first volume setting
3101 track->mFillingUpStatus = Track::FS_ACTIVE;
3102 if (track->mState == TrackBase::RESUMING) {
3103 track->mState = TrackBase::ACTIVE;
3104 param = AudioMixer::RAMP_VOLUME;
3105 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003106 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 } else if (cblk->server != 0) {
3108 // If the track is stopped before the first frame was mixed,
3109 // do not apply ramp
3110 param = AudioMixer::RAMP_VOLUME;
3111 }
3112
3113 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003114 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003115 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003116 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003117 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 if (track->isPausing()) {
3119 track->setPaused();
3120 }
3121 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003122
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003124 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003126 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003127 vl = vlr & 0xFFFF;
3128 vr = vlr >> 16;
3129 // track volumes come from shared memory, so can't be trusted and must be clamped
3130 if (vl > MAX_GAIN_INT) {
3131 ALOGV("Track left volume out of range: %04X", vl);
3132 vl = MAX_GAIN_INT;
3133 }
3134 if (vr > MAX_GAIN_INT) {
3135 ALOGV("Track right volume out of range: %04X", vr);
3136 vr = MAX_GAIN_INT;
3137 }
3138 // now apply the master volume and stream type volume
3139 vl = (uint32_t)(v * vl) << 12;
3140 vr = (uint32_t)(v * vr) << 12;
3141 // assuming master volume and stream type volume each go up to 1.0,
3142 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143
Glenn Kasten05632a52012-01-03 14:22:33 -08003144 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3145 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003146 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003147 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003148 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003149 }
3150 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003152 // Delegate volume control to effect in track effect chain if needed
3153 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3154 // Do not ramp volume if volume is controlled by effect
3155 param = AudioMixer::VOLUME;
3156 track->mHasVolumeController = true;
3157 } else {
3158 // force no volume ramp when volume controller was just disabled or removed
3159 // from effect chain to avoid volume spike
3160 if (track->mHasVolumeController) {
3161 param = AudioMixer::VOLUME;
3162 }
3163 track->mHasVolumeController = false;
3164 }
3165
3166 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003167 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003168 vl = (vl + (1 << 11)) >> 12;
3169 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3170 vr = (vr + (1 << 11)) >> 12;
3171 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003172
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003173 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 -07003174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003176 mAudioMixer->setBufferProvider(name, track);
3177 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003179 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3180 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3181 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003183 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 AudioMixer::TRACK,
3185 AudioMixer::FORMAT, (void *)track->format());
3186 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003187 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003189 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 AudioMixer::RESAMPLE,
3193 AudioMixer::SAMPLE_RATE,
3194 (void *)(cblk->sampleRate));
3195 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003196 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 AudioMixer::TRACK,
3198 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3199 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003200 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 AudioMixer::TRACK,
3202 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3203
3204 // reset retry count
3205 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003206
Eric Laurent27741442012-01-17 19:20:12 -08003207 // If one track is ready, set the mixer ready if:
3208 // - the mixer was not ready during previous round OR
3209 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003210 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003211 mixerStatus != MIXER_TRACKS_ENABLED) {
3212 mixerStatus = MIXER_TRACKS_READY;
3213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003215 // clear effect chain input buffer if an active track underruns to avoid sending
3216 // previous audio buffer again to effects
3217 chain = getEffectChain_l(track->sessionId());
3218 if (chain != 0) {
3219 chain->clearInputBuffer();
3220 }
3221
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003222 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003223 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003224 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 // We have consumed all the buffers of this track.
3226 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003227 // TODO: use actual buffer filling status instead of latency when available from
3228 // audio HAL
3229 size_t audioHALFrames =
3230 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3231 size_t framesWritten =
3232 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3233 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003234 if (track->isStopped()) {
3235 track->reset();
3236 }
Eric Laurenta011e352012-03-29 15:51:43 -07003237 tracksToRemove->add(track);
3238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003240 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 // No buffers for this track. Give it a few chances to
3242 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003243 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3244 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003246 // indicate to client process that the track was disabled because of underrun;
3247 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003248 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003249 // If one track is not ready, mark the mixer also not ready if:
3250 // - the mixer was ready during previous round OR
3251 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003252 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003253 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 mixerStatus = MIXER_TRACKS_ENABLED;
3255 }
3256 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003257 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 }
Glenn Kasten58912562012-04-03 10:45:00 -07003259
3260 } // local variable scope to avoid goto warning
3261track_is_ready: ;
3262
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 }
3264
Glenn Kasten288ed212012-04-25 17:52:27 -07003265 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003266 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003267 if (didModify) {
3268 state->mFastTracksGen++;
3269 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3270 if (kUseFastMixer == FastMixer_Dynamic &&
3271 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3272 state->mCommand = FastMixerState::COLD_IDLE;
3273 state->mColdFutexAddr = &mFastMixerFutex;
3274 state->mColdGen++;
3275 mFastMixerFutex = 0;
3276 if (kUseFastMixer == FastMixer_Dynamic) {
3277 mNormalSink = mOutputSink;
3278 }
3279 // If we go into cold idle, need to wait for acknowledgement
3280 // so that fast mixer stops doing I/O.
3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003282 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003283 }
3284 sq->end();
3285 }
3286 if (sq != NULL) {
3287 sq->end(didModify);
3288 sq->push(block);
3289 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003290 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3291 mAudioWatchdog->pause();
3292 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003293
3294 // Now perform the deferred reset on fast tracks that have stopped
3295 while (resetMask != 0) {
3296 size_t i = __builtin_ctz(resetMask);
3297 ALOG_ASSERT(i < count);
3298 resetMask &= ~(1 << i);
3299 sp<Track> t = mActiveTracks[i].promote();
3300 if (t == 0) continue;
3301 Track* track = t.get();
3302 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3303 track->reset();
3304 }
Glenn Kasten58912562012-04-03 10:45:00 -07003305
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 // remove all the tracks that need to be...
3307 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003308 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 for (size_t i=0 ; i<count ; i++) {
3310 const sp<Track>& track = tracksToRemove->itemAt(i);
3311 mActiveTracks.remove(track);
3312 if (track->mainBuffer() != mMixBuffer) {
3313 chain = getEffectChain_l(track->sessionId());
3314 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003315 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003316 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318 }
3319 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003320 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 }
3322 }
3323 }
3324
3325 // mix buffer must be cleared if all tracks are connected to an
3326 // effect chain as in this case the mixer will not write to
3327 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003328 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3329 // FIXME as a performance optimization, should remember previous zero status
3330 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 }
3332
Glenn Kasten58912562012-04-03 10:45:00 -07003333 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003334 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003335 if (fastTracks > 0) {
3336 mixerStatus = MIXER_TRACKS_READY;
3337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 return mixerStatus;
3339}
3340
Glenn Kasten66fcab92012-02-24 14:59:21 -08003341/*
3342The derived values that are cached:
3343 - mixBufferSize from frame count * frame size
3344 - activeSleepTime from activeSleepTimeUs()
3345 - idleSleepTime from idleSleepTimeUs()
3346 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3347 - maxPeriod from frame count and sample rate (MIXER only)
3348
3349The parameters that affect these derived values are:
3350 - frame count
3351 - frame size
3352 - sample rate
3353 - device type: A2DP or not
3354 - device latency
3355 - format: PCM or not
3356 - active sleep time
3357 - idle sleep time
3358*/
3359
3360void AudioFlinger::PlaybackThread::cacheParameters_l()
3361{
Glenn Kasten58912562012-04-03 10:45:00 -07003362 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003363 activeSleepTime = activeSleepTimeUs();
3364 idleSleepTime = idleSleepTimeUs();
3365}
3366
Eric Laurent22167852012-06-20 12:26:32 -07003367void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368{
Steve Block3856b092011-10-20 11:56:00 +01003369 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003370 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003372
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 size_t size = mTracks.size();
3374 for (size_t i = 0; i < size; i++) {
3375 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003376 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003377 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 }
3380 }
3381}
3382
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003384int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003386 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387}
3388
3389// deleteTrackName_l() must be called with ThreadBase::mLock held
3390void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3391{
Steve Block3856b092011-10-20 11:56:00 +01003392 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 mAudioMixer->deleteTrackName(name);
3394}
3395
3396// checkForNewParameters_l() must be called with ThreadBase::mLock held
3397bool AudioFlinger::MixerThread::checkForNewParameters_l()
3398{
Glenn Kasten58912562012-04-03 10:45:00 -07003399 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3400 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 bool reconfig = false;
3402
3403 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003404
3405 if (mFastMixer != NULL) {
3406 FastMixerStateQueue *sq = mFastMixer->sq();
3407 FastMixerState *state = sq->begin();
3408 if (!(state->mCommand & FastMixerState::IDLE)) {
3409 previousCommand = state->mCommand;
3410 state->mCommand = FastMixerState::HOT_IDLE;
3411 sq->end();
3412 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3413 } else {
3414 sq->end(false /*didModify*/);
3415 }
3416 }
3417
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 status_t status = NO_ERROR;
3419 String8 keyValuePair = mNewParameters[0];
3420 AudioParameter param = AudioParameter(keyValuePair);
3421 int value;
3422
3423 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3424 reconfig = true;
3425 }
3426 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003427 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 status = BAD_VALUE;
3429 } else {
3430 reconfig = true;
3431 }
3432 }
3433 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003434 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 status = BAD_VALUE;
3436 } else {
3437 reconfig = true;
3438 }
3439 }
3440 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3441 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003442 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 // if frame count is changed after track creation
3444 if (!mTracks.isEmpty()) {
3445 status = INVALID_OPERATION;
3446 } else {
3447 reconfig = true;
3448 }
3449 }
3450 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003451#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003452 // when changing the audio output device, call addBatteryData to notify
3453 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003454 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003455 uint32_t params = 0;
3456 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003457 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003458 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3459 }
3460
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003461 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003462 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003463 // check if any other device (except speaker) is on
3464 if (value & deviceWithoutSpeaker ) {
3465 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3466 }
3467
3468 if (params != 0) {
3469 addBatteryData(params);
3470 }
3471 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003472#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003473
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 // forward device change to effects that have requested to be
3475 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003476 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003478 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 }
3480 }
3481
3482 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003483 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003484 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003486 mOutput->stream->common.standby(&mOutput->stream->common);
3487 mStandby = true;
3488 mBytesWritten = 0;
3489 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003490 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 }
3492 if (status == NO_ERROR && reconfig) {
3493 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003494 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3495 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003497 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003499 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 if (name < 0) break;
3501 mTracks[i]->mName = name;
3502 // limit track sample rate to 2 x new output sample rate
3503 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3504 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3505 }
3506 }
3507 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3508 }
3509 }
3510
3511 mNewParameters.removeAt(0);
3512
3513 mParamStatus = status;
3514 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003515 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3516 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003517 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 }
Glenn Kasten58912562012-04-03 10:45:00 -07003519
3520 if (!(previousCommand & FastMixerState::IDLE)) {
3521 ALOG_ASSERT(mFastMixer != NULL);
3522 FastMixerStateQueue *sq = mFastMixer->sq();
3523 FastMixerState *state = sq->begin();
3524 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3525 state->mCommand = previousCommand;
3526 sq->end();
3527 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3528 }
3529
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 return reconfig;
3531}
3532
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003533void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534{
3535 const size_t SIZE = 256;
3536 char buffer[SIZE];
3537 String8 result;
3538
3539 PlaybackThread::dumpInternals(fd, args);
3540
3541 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3542 result.append(buffer);
3543 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003544
3545 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3546 FastMixerDumpState copy = mFastMixerDumpState;
3547 copy.dump(fd);
3548
Glenn Kasten39993082012-05-31 13:40:27 -07003549#ifdef STATE_QUEUE_DUMP
3550 // Similar for state queue
3551 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3552 observerCopy.dump(fd);
3553 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3554 mutatorCopy.dump(fd);
3555#endif
3556
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003557 // Write the tee output to a .wav file
3558 NBAIO_Source *teeSource = mTeeSource.get();
3559 if (teeSource != NULL) {
3560 char teePath[64];
3561 struct timeval tv;
3562 gettimeofday(&tv, NULL);
3563 struct tm tm;
3564 localtime_r(&tv.tv_sec, &tm);
3565 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3566 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3567 if (teeFd >= 0) {
3568 char wavHeader[44];
3569 memcpy(wavHeader,
3570 "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",
3571 sizeof(wavHeader));
3572 NBAIO_Format format = teeSource->format();
3573 unsigned channelCount = Format_channelCount(format);
3574 ALOG_ASSERT(channelCount <= FCC_2);
3575 unsigned sampleRate = Format_sampleRate(format);
3576 wavHeader[22] = channelCount; // number of channels
3577 wavHeader[24] = sampleRate; // sample rate
3578 wavHeader[25] = sampleRate >> 8;
3579 wavHeader[32] = channelCount * 2; // block alignment
3580 write(teeFd, wavHeader, sizeof(wavHeader));
3581 size_t total = 0;
3582 bool firstRead = true;
3583 for (;;) {
3584#define TEE_SINK_READ 1024
3585 short buffer[TEE_SINK_READ * FCC_2];
3586 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003587 ssize_t actual = teeSource->read(buffer, count,
3588 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003589 bool wasFirstRead = firstRead;
3590 firstRead = false;
3591 if (actual <= 0) {
3592 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3593 continue;
3594 }
3595 break;
3596 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003597 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003598 write(teeFd, buffer, actual * channelCount * sizeof(short));
3599 total += actual;
3600 }
3601 lseek(teeFd, (off_t) 4, SEEK_SET);
3602 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3603 write(teeFd, &temp, sizeof(temp));
3604 lseek(teeFd, (off_t) 40, SEEK_SET);
3605 temp = total * channelCount * sizeof(short);
3606 write(teeFd, &temp, sizeof(temp));
3607 close(teeFd);
3608 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3609 } else {
3610 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3611 }
3612 }
3613
Glenn Kastenc15d6652012-05-30 14:52:57 -07003614 if (mAudioWatchdog != 0) {
3615 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3616 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3617 wdCopy.dump(fd);
3618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619}
3620
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003621uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622{
Glenn Kasten58912562012-04-03 10:45:00 -07003623 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624}
3625
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003626uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003627{
Glenn Kasten58912562012-04-03 10:45:00 -07003628 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003629}
3630
Glenn Kasten66fcab92012-02-24 14:59:21 -08003631void AudioFlinger::MixerThread::cacheParameters_l()
3632{
3633 PlaybackThread::cacheParameters_l();
3634
3635 // FIXME: Relaxed timing because of a certain device that can't meet latency
3636 // Should be reduced to 2x after the vendor fixes the driver issue
3637 // increase threshold again due to low power audio mode. The way this warning
3638 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003639 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003640}
3641
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003643AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003644 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003645 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003646 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648}
3649
3650AudioFlinger::DirectOutputThread::~DirectOutputThread()
3651{
3652}
3653
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003654AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3655 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003656)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003658 sp<Track> trackToRemove;
3659
Glenn Kastenfec279f2012-03-08 07:47:15 -08003660 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 // find out which tracks need to be processed
3663 if (mActiveTracks.size() != 0) {
3664 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003665 // The track died recently
3666 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 Track* const track = t.get();
3669 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670
Glenn Kasten952eeb22012-03-06 11:30:57 -08003671 // The first time a track is added we wait
3672 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003673 uint32_t minFrames;
3674 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3675 minFrames = mNormalFrameCount;
3676 } else {
3677 minFrames = 1;
3678 }
3679 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003680 !track->isPaused() && !track->isTerminated())
3681 {
3682 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683
Glenn Kasten952eeb22012-03-06 11:30:57 -08003684 if (track->mFillingUpStatus == Track::FS_FILLED) {
3685 track->mFillingUpStatus = Track::FS_ACTIVE;
3686 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003687 if (track->mState == TrackBase::RESUMING) {
3688 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003690 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003691
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 // compute volume for this track
3693 float left, right;
3694 if (track->isMuted() || mMasterMute || track->isPausing() ||
3695 mStreamTypes[track->streamType()].mute) {
3696 left = right = 0;
3697 if (track->isPausing()) {
3698 track->setPaused();
3699 }
3700 } else {
3701 float typeVolume = mStreamTypes[track->streamType()].volume;
3702 float v = mMasterVolume * typeVolume;
3703 uint32_t vlr = cblk->getVolumeLR();
3704 float v_clamped = v * (vlr & 0xFFFF);
3705 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3706 left = v_clamped/MAX_GAIN;
3707 v_clamped = v * (vlr >> 16);
3708 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3709 right = v_clamped/MAX_GAIN;
3710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 if (left != mLeftVolFloat || right != mRightVolFloat) {
3713 mLeftVolFloat = left;
3714 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 // Convert volumes from float to 8.24
3717 uint32_t vl = (uint32_t)(left * (1 << 24));
3718 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719
Glenn Kasten952eeb22012-03-06 11:30:57 -08003720 // Delegate volume control to effect in track effect chain if needed
3721 // only one effect chain can be present on DirectOutputThread, so if
3722 // there is one, the track is connected to it
3723 if (!mEffectChains.isEmpty()) {
3724 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003725 mEffectChains[0]->setVolume_l(&vl, &vr);
3726 left = (float)vl / (1 << 24);
3727 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003728 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003729 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 }
3731
3732 // reset retry count
3733 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003734 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003735 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003736 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003737 // clear effect chain input buffer if an active track underruns to avoid sending
3738 // previous audio buffer again to effects
3739 if (!mEffectChains.isEmpty()) {
3740 mEffectChains[0]->clearInputBuffer();
3741 }
3742
Glenn Kasten952eeb22012-03-06 11:30:57 -08003743 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003744 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003745 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 // We have consumed all the buffers of this track.
3747 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003748 // TODO: implement behavior for compressed audio
3749 size_t audioHALFrames =
3750 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3751 size_t framesWritten =
3752 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3753 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003754 if (track->isStopped()) {
3755 track->reset();
3756 }
Eric Laurenta011e352012-03-29 15:51:43 -07003757 trackToRemove = track;
3758 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003759 } else {
3760 // No buffers for this track. Give it a few chances to
3761 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003762 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3763 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003764 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003766 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 }
3768 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 }
3770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003772 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 // remove all the tracks that need to be...
3774 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003775 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003776 mActiveTracks.remove(trackToRemove);
3777 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003778 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003779 trackToRemove->sessionId());
3780 mEffectChains[0]->decActiveTrackCnt();
3781 }
3782 if (trackToRemove->isTerminated()) {
3783 removeTrack_l(trackToRemove);
3784 }
3785 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786
Glenn Kastenfec279f2012-03-08 07:47:15 -08003787 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003788}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789
Glenn Kasten000f0e32012-03-01 17:10:56 -08003790void AudioFlinger::DirectOutputThread::threadLoop_mix()
3791{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003792 AudioBufferProvider::Buffer buffer;
3793 size_t frameCount = mFrameCount;
3794 int8_t *curBuf = (int8_t *)mMixBuffer;
3795 // output audio to hardware
3796 while (frameCount) {
3797 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003798 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003799 if (CC_UNLIKELY(buffer.raw == NULL)) {
3800 memset(curBuf, 0, frameCount * mFrameSize);
3801 break;
3802 }
3803 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3804 frameCount -= buffer.frameCount;
3805 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003806 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003807 }
3808 sleepTime = 0;
3809 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003810 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003811
Glenn Kasten000f0e32012-03-01 17:10:56 -08003812}
3813
3814void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3815{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003816 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003817 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 sleepTime = activeSleepTime;
3819 } else {
3820 sleepTime = idleSleepTime;
3821 }
3822 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003823 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003824 sleepTime = 0;
3825 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826}
3827
3828// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003829int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830{
3831 return 0;
3832}
3833
3834// deleteTrackName_l() must be called with ThreadBase::mLock held
3835void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3836{
3837}
3838
3839// checkForNewParameters_l() must be called with ThreadBase::mLock held
3840bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3841{
3842 bool reconfig = false;
3843
3844 while (!mNewParameters.isEmpty()) {
3845 status_t status = NO_ERROR;
3846 String8 keyValuePair = mNewParameters[0];
3847 AudioParameter param = AudioParameter(keyValuePair);
3848 int value;
3849
3850 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3851 // do not accept frame count changes if tracks are open as the track buffer
3852 // size depends on frame count and correct behavior would not be garantied
3853 // if frame count is changed after track creation
3854 if (!mTracks.isEmpty()) {
3855 status = INVALID_OPERATION;
3856 } else {
3857 reconfig = true;
3858 }
3859 }
3860 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003861 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003862 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003864 mOutput->stream->common.standby(&mOutput->stream->common);
3865 mStandby = true;
3866 mBytesWritten = 0;
3867 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003868 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 }
3870 if (status == NO_ERROR && reconfig) {
3871 readOutputParameters();
3872 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3873 }
3874 }
3875
3876 mNewParameters.removeAt(0);
3877
3878 mParamStatus = status;
3879 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003880 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3881 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003882 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 }
3884 return reconfig;
3885}
3886
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003887uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888{
3889 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003890 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003891 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 } else {
3893 time = 10000;
3894 }
3895 return time;
3896}
3897
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003898uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899{
3900 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003901 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003902 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003903 } else {
3904 time = 10000;
3905 }
3906 return time;
3907}
3908
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003909uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003910{
3911 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003912 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003913 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3914 } else {
3915 time = 10000;
3916 }
3917 return time;
3918}
3919
Glenn Kasten66fcab92012-02-24 14:59:21 -08003920void AudioFlinger::DirectOutputThread::cacheParameters_l()
3921{
3922 PlaybackThread::cacheParameters_l();
3923
3924 // use shorter standby delay as on normal output to release
3925 // hardware resources as soon as possible
3926 standbyDelay = microseconds(activeSleepTime*2);
3927}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003928
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929// ----------------------------------------------------------------------------
3930
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003931AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003932 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003933 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3934 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 addOutputTrack(mainThread);
3937}
3938
3939AudioFlinger::DuplicatingThread::~DuplicatingThread()
3940{
3941 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3942 mOutputTracks[i]->destroy();
3943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944}
3945
Glenn Kasten000f0e32012-03-01 17:10:56 -08003946void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003948 // mix buffers...
3949 if (outputsReady(outputTracks)) {
3950 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3951 } else {
3952 memset(mMixBuffer, 0, mixBufferSize);
3953 }
3954 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003955 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003956 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003957}
3958
3959void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3960{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003961 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003962 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003963 sleepTime = activeSleepTime;
3964 } else {
3965 sleepTime = idleSleepTime;
3966 }
3967 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003968 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3969 writeFrames = mNormalFrameCount;
3970 memset(mMixBuffer, 0, mixBufferSize);
3971 } else {
3972 // flush remaining overflow buffers in output tracks
3973 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003974 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003975 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003976 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003977}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978
Glenn Kasten000f0e32012-03-01 17:10:56 -08003979void AudioFlinger::DuplicatingThread::threadLoop_write()
3980{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003981 for (size_t i = 0; i < outputTracks.size(); i++) {
3982 outputTracks[i]->write(mMixBuffer, writeFrames);
3983 }
3984 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003985}
Glenn Kasten688a6402012-02-29 07:57:06 -08003986
Glenn Kasten000f0e32012-03-01 17:10:56 -08003987void AudioFlinger::DuplicatingThread::threadLoop_standby()
3988{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003989 // DuplicatingThread implements standby by stopping all tracks
3990 for (size_t i = 0; i < outputTracks.size(); i++) {
3991 outputTracks[i]->stop();
3992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993}
3994
Glenn Kastenfa26a852012-03-06 11:28:04 -08003995void AudioFlinger::DuplicatingThread::saveOutputTracks()
3996{
3997 outputTracks = mOutputTracks;
3998}
3999
4000void AudioFlinger::DuplicatingThread::clearOutputTracks()
4001{
4002 outputTracks.clear();
4003}
4004
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4006{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004007 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004008 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004009 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004010 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 this,
4012 mSampleRate,
4013 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004014 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 frameCount);
4016 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004017 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004019 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004020 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 }
4022}
4023
4024void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4025{
4026 Mutex::Autolock _l(mLock);
4027 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004028 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029 mOutputTracks[i]->destroy();
4030 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004031 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 return;
4033 }
4034 }
Steve Block3856b092011-10-20 11:56:00 +01004035 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036}
4037
Glenn Kasten438b0362012-03-06 11:24:48 -08004038// caller must hold mLock
4039void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040{
4041 mWaitTimeMs = UINT_MAX;
4042 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4043 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004044 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4046 if (waitTimeMs < mWaitTimeMs) {
4047 mWaitTimeMs = waitTimeMs;
4048 }
4049 }
4050 }
4051}
4052
4053
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004054bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055{
4056 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004057 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004059 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 return false;
4061 }
4062 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004063 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004065 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 return false;
4067 }
4068 }
4069 return true;
4070}
4071
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004072uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073{
4074 return (mWaitTimeMs * 1000) / 2;
4075}
4076
Glenn Kasten66fcab92012-02-24 14:59:21 -08004077void AudioFlinger::DuplicatingThread::cacheParameters_l()
4078{
4079 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4080 updateWaitTime_l();
4081
4082 MixerThread::cacheParameters_l();
4083}
4084
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085// ----------------------------------------------------------------------------
4086
4087// TrackBase constructor must be called with AudioFlinger::mLock held
4088AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004089 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 const sp<Client>& client,
4091 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004092 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004093 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 const sp<IMemory>& sharedBuffer,
4096 int sessionId)
4097 : RefBase(),
4098 mThread(thread),
4099 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004100 mCblk(NULL),
4101 // mBuffer
4102 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 mFrameCount(0),
4104 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004105 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004107 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004109 // mChannelCount
4110 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111{
Steve Block3856b092011-10-20 11:56:00 +01004112 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113
Steve Blockb8a80522011-12-20 16:23:08 +00004114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004115 size_t size = sizeof(audio_track_cblk_t);
4116 uint8_t channelCount = popcount(channelMask);
4117 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4118 if (sharedBuffer == 0) {
4119 size += bufferSize;
4120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004122 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 mCblkMemory = client->heap()->allocate(size);
4124 if (mCblkMemory != 0) {
4125 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004126 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 new(mCblk) audio_track_cblk_t();
4128 // clear all buffers
4129 mCblk->frameCount = frameCount;
4130 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004131// uncomment the following lines to quickly test 32-bit wraparound
4132// mCblk->user = 0xffff0000;
4133// mCblk->server = 0xffff0000;
4134// mCblk->userBase = 0xffff0000;
4135// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004136 mChannelCount = channelCount;
4137 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 if (sharedBuffer == 0) {
4139 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4140 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4141 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004142 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 mCblk->flags = CBLK_UNDERRUN_ON;
4144 } else {
4145 mBuffer = sharedBuffer->pointer();
4146 }
4147 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4148 }
4149 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004150 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 client->heap()->dump("AudioTrack");
4152 return;
4153 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004154 } else {
4155 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004156 // construct the shared structure in-place.
4157 new(mCblk) audio_track_cblk_t();
4158 // clear all buffers
4159 mCblk->frameCount = frameCount;
4160 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004161// uncomment the following lines to quickly test 32-bit wraparound
4162// mCblk->user = 0xffff0000;
4163// mCblk->server = 0xffff0000;
4164// mCblk->userBase = 0xffff0000;
4165// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004166 mChannelCount = channelCount;
4167 mChannelMask = channelMask;
4168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4169 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4170 // Force underrun condition to avoid false underrun callback until first data is
4171 // written to buffer (other flags are cleared)
4172 mCblk->flags = CBLK_UNDERRUN_ON;
4173 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175}
4176
4177AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4178{
Glenn Kastena0d68332012-01-27 16:47:15 -08004179 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004180 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004182 } else {
4183 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 }
4185 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004186 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004187 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004188 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004190 // If the client's reference count drops to zero, the associated destructor
4191 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4192 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 mClient.clear();
4194 }
4195}
4196
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004197// AudioBufferProvider interface
4198// getNextBuffer() = 0;
4199// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4201{
Glenn Kastene0feee32011-12-13 11:53:26 -08004202 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004204 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004205 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 buffer->frameCount = 0;
4207}
4208
4209bool AudioFlinger::ThreadBase::TrackBase::step() {
4210 bool result;
4211 audio_track_cblk_t* cblk = this->cblk();
4212
4213 result = cblk->stepServer(mFrameCount);
4214 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004216 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 }
4218 return result;
4219}
4220
4221void AudioFlinger::ThreadBase::TrackBase::reset() {
4222 audio_track_cblk_t* cblk = this->cblk();
4223
4224 cblk->user = 0;
4225 cblk->server = 0;
4226 cblk->userBase = 0;
4227 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004228 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004229 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230}
4231
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4233 return (int)mCblk->sampleRate;
4234}
4235
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4237 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004238 size_t frameSize = cblk->frameSize;
4239 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4240 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
4242 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004243 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4244 "TrackBase::getBuffer buffer out of range:\n"
4245 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4246 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004248 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249
4250 return bufferStart;
4251}
4252
Eric Laurenta011e352012-03-29 15:51:43 -07004253status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4254{
4255 mSyncEvents.add(event);
4256 return NO_ERROR;
4257}
4258
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259// ----------------------------------------------------------------------------
4260
4261// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4262AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004263 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004265 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004267 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004268 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 int frameCount,
4270 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004271 int sessionId,
4272 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004273 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004274 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004275 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004276 // mRetryCount initialized later when needed
4277 mSharedBuffer(sharedBuffer),
4278 mStreamType(streamType),
4279 mName(-1), // see note below
4280 mMainBuffer(thread->mixBuffer()),
4281 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004282 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004283 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004284 mFlags(flags),
4285 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004286 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004287 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288{
4289 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4291 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004292 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004293 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004294 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004295 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004296 if (mName < 0) {
4297 ALOGE("no more track names available");
4298 return;
4299 }
4300 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004301 if (flags & IAudioFlinger::TRACK_FAST) {
4302 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4303 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4304 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004305 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004306 // FIXME This is too eager. We allocate a fast track index before the
4307 // fast track becomes active. Since fast tracks are a scarce resource,
4308 // this means we are potentially denying other more important fast tracks from
4309 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004310 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004311 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004312 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004313 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004314 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004317 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318}
4319
4320AudioFlinger::PlaybackThread::Track::~Track()
4321{
Steve Block3856b092011-10-20 11:56:00 +01004322 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323}
4324
4325void AudioFlinger::PlaybackThread::Track::destroy()
4326{
4327 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4328 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004329 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 // we must acquire a strong reference on this Track before locking mLock
4331 // here so that the destructor is called only when exiting this function.
4332 // On the other hand, as long as Track::destroy() is only called by
4333 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4334 // this Track with its member mTrack.
4335 sp<Track> keep(this);
4336 { // scope for mLock
4337 sp<ThreadBase> thread = mThread.promote();
4338 if (thread != 0) {
4339 if (!isOutputTrack()) {
4340 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004341 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004342
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004343#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004344 // to track the speaker usage
4345 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004346#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 }
4348 AudioSystem::releaseOutput(thread->id());
4349 }
4350 Mutex::Autolock _l(thread->mLock);
4351 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4352 playbackThread->destroyTrack_l(this);
4353 }
4354 }
4355}
4356
Glenn Kasten288ed212012-04-25 17:52:27 -07004357/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4358{
Glenn Kastene213c862012-04-25 13:46:15 -07004359 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 -07004360 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004361}
4362
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4364{
Glenn Kasten83d86532012-01-17 14:39:34 -08004365 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004366 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004367 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004368 } else {
4369 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4370 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004371 track_state state = mState;
4372 char stateChar;
4373 switch (state) {
4374 case IDLE:
4375 stateChar = 'I';
4376 break;
4377 case TERMINATED:
4378 stateChar = 'T';
4379 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004380 case STOPPING_1:
4381 stateChar = 's';
4382 break;
4383 case STOPPING_2:
4384 stateChar = '5';
4385 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004386 case STOPPED:
4387 stateChar = 'S';
4388 break;
4389 case RESUMING:
4390 stateChar = 'R';
4391 break;
4392 case ACTIVE:
4393 stateChar = 'A';
4394 break;
4395 case PAUSING:
4396 stateChar = 'p';
4397 break;
4398 case PAUSED:
4399 stateChar = 'P';
4400 break;
Eric Laurent29864602012-05-08 18:57:51 -07004401 case FLUSHED:
4402 stateChar = 'F';
4403 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004404 default:
4405 stateChar = '?';
4406 break;
4407 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004408 char nowInUnderrun;
4409 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4410 case UNDERRUN_FULL:
4411 nowInUnderrun = ' ';
4412 break;
4413 case UNDERRUN_PARTIAL:
4414 nowInUnderrun = '<';
4415 break;
4416 case UNDERRUN_EMPTY:
4417 nowInUnderrun = '*';
4418 break;
4419 default:
4420 nowInUnderrun = '?';
4421 break;
4422 }
Glenn Kastene213c862012-04-25 13:46:15 -07004423 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4424 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004425 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 mStreamType,
4427 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004428 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 mSessionId,
4430 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004431 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004432 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 mMute,
4434 mFillingUpStatus,
4435 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004436 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4437 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 mCblk->server,
4439 mCblk->user,
4440 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004441 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004442 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004443 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004444 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445}
4446
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004447// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004448status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004449 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004451 audio_track_cblk_t* cblk = this->cblk();
4452 uint32_t framesReady;
4453 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004455 // Check if last stepServer failed, try to step now
4456 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004457 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4458 // Since the fast mixer is higher priority than client callback thread,
4459 // it does not result in priority inversion for client.
4460 // But a non-blocking solution would be preferable to avoid
4461 // fast mixer being unable to tryLock(), and
4462 // to avoid the extra context switches if the client wakes up,
4463 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004464 if (!step()) goto getNextBuffer_exit;
4465 ALOGV("stepServer recovered");
4466 mStepServerFailed = false;
4467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468
Glenn Kasten288ed212012-04-25 17:52:27 -07004469 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004470 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004472 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004473 uint32_t s = cblk->server;
4474 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4475
4476 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4477 if (framesReq > framesReady) {
4478 framesReq = framesReady;
4479 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004480 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 framesReq = bufferEnd - s;
4482 }
4483
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004484 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004485 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488
4489getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004490 buffer->raw = NULL;
4491 buffer->frameCount = 0;
4492 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4493 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494}
4495
Glenn Kasten288ed212012-04-25 17:52:27 -07004496// Note that framesReady() takes a mutex on the control block using tryLock().
4497// This could result in priority inversion if framesReady() is called by the normal mixer,
4498// as the normal mixer thread runs at lower
4499// priority than the client's callback thread: there is a short window within framesReady()
4500// during which the normal mixer could be preempted, and the client callback would block.
4501// Another problem can occur if framesReady() is called by the fast mixer:
4502// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4503// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4504size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004505 return mCblk->framesReady();
4506}
4507
Glenn Kasten288ed212012-04-25 17:52:27 -07004508// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004510 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511
John Grossman4ff14ba2012-02-08 16:37:41 -08004512 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4514 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004515 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 return true;
4517 }
4518 return false;
4519}
4520
Glenn Kasten3acbd052012-02-28 10:39:56 -08004521status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004522 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523{
4524 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004525 ALOGV("start(%d), calling pid %d session %d",
4526 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004527
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 sp<ThreadBase> thread = mThread.promote();
4529 if (thread != 0) {
4530 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004531 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 // here the track could be either new, or restarted
4533 // in both cases "unstop" the track
4534 if (mState == PAUSED) {
4535 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004536 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 } else {
4538 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 }
4541
4542 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4543 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004544 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004546
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004547#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004548 // to track the speaker usage
4549 if (status == NO_ERROR) {
4550 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4551 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004552#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 }
4554 if (status == NO_ERROR) {
4555 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4556 playbackThread->addTrack_l(this);
4557 } else {
4558 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004559 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
4561 } else {
4562 status = BAD_VALUE;
4563 }
4564 return status;
4565}
4566
4567void AudioFlinger::PlaybackThread::Track::stop()
4568{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004569 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 sp<ThreadBase> thread = mThread.promote();
4571 if (thread != 0) {
4572 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004573 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004574 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 // If the track is not active (PAUSED and buffers full), flush buffers
4576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4577 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4578 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004579 mState = STOPPED;
4580 } else if (!isFastTrack()) {
4581 mState = STOPPED;
4582 } else {
4583 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4584 // and then to STOPPED and reset() when presentation is complete
4585 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004587 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 }
4589 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4590 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004591 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004593
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004594#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004595 // to track the speaker usage
4596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004597#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 }
4600}
4601
4602void AudioFlinger::PlaybackThread::Track::pause()
4603{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004604 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 sp<ThreadBase> thread = mThread.promote();
4606 if (thread != 0) {
4607 Mutex::Autolock _l(thread->mLock);
4608 if (mState == ACTIVE || mState == RESUMING) {
4609 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004610 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 if (!isOutputTrack()) {
4612 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004613 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004615
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004616#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004617 // to track the speaker usage
4618 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004619#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621 }
4622 }
4623}
4624
4625void AudioFlinger::PlaybackThread::Track::flush()
4626{
Steve Block3856b092011-10-20 11:56:00 +01004627 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 sp<ThreadBase> thread = mThread.promote();
4629 if (thread != 0) {
4630 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004631 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4632 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 return;
4634 }
4635 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004636 // FLUSHED state
4637 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004638 // do not reset the track if it is still in the process of being stopped or paused.
4639 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004640 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004641 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004642 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4643 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4644 reset();
4645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 }
4647}
4648
4649void AudioFlinger::PlaybackThread::Track::reset()
4650{
4651 // Do not reset twice to avoid discarding data written just after a flush and before
4652 // the audioflinger thread detects the track is stopped.
4653 if (!mResetDone) {
4654 TrackBase::reset();
4655 // Force underrun condition to avoid false underrun callback until first data is
4656 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004657 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4658 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 mFillingUpStatus = FS_FILLING;
4660 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004661 if (mState == FLUSHED) {
4662 mState = IDLE;
4663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004664 }
4665}
4666
4667void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4668{
4669 mMute = muted;
4670}
4671
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4673{
4674 status_t status = DEAD_OBJECT;
4675 sp<ThreadBase> thread = mThread.promote();
4676 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004677 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004678 sp<AudioFlinger> af = mClient->audioFlinger();
4679
4680 Mutex::Autolock _l(af->mLock);
4681
4682 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004683
Eric Laurent109347d2012-07-02 12:31:03 -07004684 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004685 Mutex::Autolock _dl(playbackThread->mLock);
4686 Mutex::Autolock _sl(srcThread->mLock);
4687 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4688 if (chain == 0) {
4689 return INVALID_OPERATION;
4690 }
4691
4692 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4693 if (effect == 0) {
4694 return INVALID_OPERATION;
4695 }
4696 srcThread->removeEffect_l(effect);
4697 playbackThread->addEffect_l(effect);
4698 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4699 if (effect->state() == EffectModule::ACTIVE ||
4700 effect->state() == EffectModule::STOPPING) {
4701 effect->start();
4702 }
4703
4704 sp<EffectChain> dstChain = effect->chain().promote();
4705 if (dstChain == 0) {
4706 srcThread->addEffect_l(effect);
4707 return INVALID_OPERATION;
4708 }
4709 AudioSystem::unregisterEffect(effect->id());
4710 AudioSystem::registerEffect(&effect->desc(),
4711 srcThread->id(),
4712 dstChain->strategy(),
4713 AUDIO_SESSION_OUTPUT_MIX,
4714 effect->id());
4715 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004716 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717 }
4718 return status;
4719}
4720
4721void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4722{
4723 mAuxEffectId = EffectId;
4724 mAuxBuffer = buffer;
4725}
4726
Eric Laurenta011e352012-03-29 15:51:43 -07004727bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4728 size_t audioHalFrames)
4729{
4730 // a track is considered presented when the total number of frames written to audio HAL
4731 // corresponds to the number of frames written when presentationComplete() is called for the
4732 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4733 if (mPresentationCompleteFrames == 0) {
4734 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4735 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4736 mPresentationCompleteFrames, audioHalFrames);
4737 }
4738 if (framesWritten >= mPresentationCompleteFrames) {
4739 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4740 mSessionId, framesWritten);
4741 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004742 return true;
4743 }
4744 return false;
4745}
4746
4747void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4748{
4749 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4750 if (mSyncEvents[i]->type() == type) {
4751 mSyncEvents[i]->trigger();
4752 mSyncEvents.removeAt(i);
4753 i--;
4754 }
4755 }
4756}
4757
Glenn Kasten58912562012-04-03 10:45:00 -07004758// implement VolumeBufferProvider interface
4759
4760uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4761{
4762 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4763 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4764 uint32_t vlr = mCblk->getVolumeLR();
4765 uint32_t vl = vlr & 0xFFFF;
4766 uint32_t vr = vlr >> 16;
4767 // track volumes come from shared memory, so can't be trusted and must be clamped
4768 if (vl > MAX_GAIN_INT) {
4769 vl = MAX_GAIN_INT;
4770 }
4771 if (vr > MAX_GAIN_INT) {
4772 vr = MAX_GAIN_INT;
4773 }
4774 // now apply the cached master volume and stream type volume;
4775 // this is trusted but lacks any synchronization or barrier so may be stale
4776 float v = mCachedVolume;
4777 vl *= v;
4778 vr *= v;
4779 // re-combine into U4.16
4780 vlr = (vr << 16) | (vl & 0xFFFF);
4781 // FIXME look at mute, pause, and stop flags
4782 return vlr;
4783}
Eric Laurenta011e352012-03-29 15:51:43 -07004784
Eric Laurent29864602012-05-08 18:57:51 -07004785status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4786{
4787 if (mState == TERMINATED || mState == PAUSED ||
4788 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4789 (mState == STOPPED)))) {
4790 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4791 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4792 event->cancel();
4793 return INVALID_OPERATION;
4794 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004795 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004796 return NO_ERROR;
4797}
4798
John Grossman4ff14ba2012-02-08 16:37:41 -08004799// timed audio tracks
4800
4801sp<AudioFlinger::PlaybackThread::TimedTrack>
4802AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004803 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004804 const sp<Client>& client,
4805 audio_stream_type_t streamType,
4806 uint32_t sampleRate,
4807 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004808 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004809 int frameCount,
4810 const sp<IMemory>& sharedBuffer,
4811 int sessionId) {
4812 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004813 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004814
Glenn Kastena0356762012-03-19 10:38:51 -07004815 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004816 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4817 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004818}
4819
4820AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004821 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004822 const sp<Client>& client,
4823 audio_stream_type_t streamType,
4824 uint32_t sampleRate,
4825 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004826 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004827 int frameCount,
4828 const sp<IMemory>& sharedBuffer,
4829 int sessionId)
4830 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004831 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004832 mQueueHeadInFlight(false),
4833 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004834 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004835 mTimedSilenceBuffer(NULL),
4836 mTimedSilenceBufferSize(0),
4837 mTimedAudioOutputOnTime(false),
4838 mMediaTimeTransformValid(false)
4839{
4840 LocalClock lc;
4841 mLocalTimeFreq = lc.getLocalFreq();
4842
4843 mLocalTimeToSampleTransform.a_zero = 0;
4844 mLocalTimeToSampleTransform.b_zero = 0;
4845 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4846 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4847 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4848 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004849
4850 mMediaTimeToSampleTransform.a_zero = 0;
4851 mMediaTimeToSampleTransform.b_zero = 0;
4852 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4853 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4854 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4855 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004856}
4857
4858AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4859 mClient->releaseTimedTrack();
4860 delete [] mTimedSilenceBuffer;
4861}
4862
4863status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4864 size_t size, sp<IMemory>* buffer) {
4865
4866 Mutex::Autolock _l(mTimedBufferQueueLock);
4867
4868 trimTimedBufferQueue_l();
4869
4870 // lazily initialize the shared memory heap for timed buffers
4871 if (mTimedMemoryDealer == NULL) {
4872 const int kTimedBufferHeapSize = 512 << 10;
4873
4874 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4875 "AudioFlingerTimed");
4876 if (mTimedMemoryDealer == NULL)
4877 return NO_MEMORY;
4878 }
4879
4880 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4881 if (newBuffer == NULL) {
4882 newBuffer = mTimedMemoryDealer->allocate(size);
4883 if (newBuffer == NULL)
4884 return NO_MEMORY;
4885 }
4886
4887 *buffer = newBuffer;
4888 return NO_ERROR;
4889}
4890
4891// caller must hold mTimedBufferQueueLock
4892void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4893 int64_t mediaTimeNow;
4894 {
4895 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4896 if (!mMediaTimeTransformValid)
4897 return;
4898
4899 int64_t targetTimeNow;
4900 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4901 ? mCCHelper.getCommonTime(&targetTimeNow)
4902 : mCCHelper.getLocalTime(&targetTimeNow);
4903
4904 if (OK != res)
4905 return;
4906
4907 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4908 &mediaTimeNow)) {
4909 return;
4910 }
4911 }
4912
John Grossman1c345192012-03-27 14:00:17 -07004913 size_t trimEnd;
4914 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004915 int64_t bufEnd;
4916
John Grossmanc95cfbb2012-04-12 11:53:11 -07004917 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4918 // We have a next buffer. Just use its PTS as the PTS of the frame
4919 // following the last frame in this buffer. If the stream is sparse
4920 // (ie, there are deliberate gaps left in the stream which should be
4921 // filled with silence by the TimedAudioTrack), then this can result
4922 // in one extra buffer being left un-trimmed when it could have
4923 // been. In general, this is not typical, and we would rather
4924 // optimized away the TS calculation below for the more common case
4925 // where PTSes are contiguous.
4926 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4927 } else {
4928 // We have no next buffer. Compute the PTS of the frame following
4929 // the last frame in this buffer by computing the duration of of
4930 // this frame in media time units and adding it to the PTS of the
4931 // buffer.
4932 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4933 / mCblk->frameSize;
4934
4935 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4936 &bufEnd)) {
4937 ALOGE("Failed to convert frame count of %lld to media time"
4938 " duration" " (scale factor %d/%u) in %s",
4939 frameCount,
4940 mMediaTimeToSampleTransform.a_to_b_numer,
4941 mMediaTimeToSampleTransform.a_to_b_denom,
4942 __PRETTY_FUNCTION__);
4943 break;
4944 }
4945 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004946 }
John Grossman9fbdee12012-03-26 17:51:46 -07004947
4948 if (bufEnd > mediaTimeNow)
4949 break;
4950
4951 // Is the buffer we want to use in the middle of a mix operation right
4952 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4953 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004954 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004955 mTrimQueueHeadOnRelease = true;
4956 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004957 }
4958
John Grossman9fbdee12012-03-26 17:51:46 -07004959 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004960 if (trimStart < trimEnd) {
4961 // Update the bookkeeping for framesReady()
4962 for (size_t i = trimStart; i < trimEnd; ++i) {
4963 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4964 }
4965
4966 // Now actually remove the buffers from the queue.
4967 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004968 }
4969}
4970
John Grossman1c345192012-03-27 14:00:17 -07004971void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4972 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004973 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4974 "%s called (reason \"%s\"), but timed buffer queue has no"
4975 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004976
4977 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4978 mTimedBufferQueue.removeAt(0);
4979}
4980
4981void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4982 const TimedBuffer& buf,
4983 const char* logTag) {
4984 uint32_t bufBytes = buf.buffer()->size();
4985 uint32_t consumedAlready = buf.position();
4986
Eric Laurentb388e532012-04-14 13:32:48 -07004987 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004988 "Bad bookkeeping while updating frames pending. Timed buffer is"
4989 " only %u bytes long, but claims to have consumed %u"
4990 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004991 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004992
4993 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004994 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4995 "Bad bookkeeping while updating frames pending. Should have at"
4996 " least %u queued frames, but we think we have only %u. (update"
4997 " reason: \"%s\")",
4998 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004999
5000 mFramesPendingInQueue -= bufFrames;
5001}
5002
John Grossman4ff14ba2012-02-08 16:37:41 -08005003status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5004 const sp<IMemory>& buffer, int64_t pts) {
5005
5006 {
5007 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5008 if (!mMediaTimeTransformValid)
5009 return INVALID_OPERATION;
5010 }
5011
5012 Mutex::Autolock _l(mTimedBufferQueueLock);
5013
John Grossman1c345192012-03-27 14:00:17 -07005014 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5015 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005016 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5017
5018 return NO_ERROR;
5019}
5020
5021status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5022 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5023
John Grossman1c345192012-03-27 14:00:17 -07005024 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5025 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5026 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005027
5028 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5029 target == TimedAudioTrack::COMMON_TIME)) {
5030 return BAD_VALUE;
5031 }
5032
5033 Mutex::Autolock lock(mMediaTimeTransformLock);
5034 mMediaTimeTransform = xform;
5035 mMediaTimeTransformTarget = target;
5036 mMediaTimeTransformValid = true;
5037
5038 return NO_ERROR;
5039}
5040
5041#define min(a, b) ((a) < (b) ? (a) : (b))
5042
5043// implementation of getNextBuffer for tracks whose buffers have timestamps
5044status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5045 AudioBufferProvider::Buffer* buffer, int64_t pts)
5046{
5047 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005048 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005049 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005050 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005051 return INVALID_OPERATION;
5052 }
5053
John Grossman4ff14ba2012-02-08 16:37:41 -08005054 Mutex::Autolock _l(mTimedBufferQueueLock);
5055
John Grossman9fbdee12012-03-26 17:51:46 -07005056 ALOG_ASSERT(!mQueueHeadInFlight,
5057 "getNextBuffer called without releaseBuffer!");
5058
John Grossman4ff14ba2012-02-08 16:37:41 -08005059 while (true) {
5060
5061 // if we have no timed buffers, then fail
5062 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005063 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005064 buffer->frameCount = 0;
5065 return NOT_ENOUGH_DATA;
5066 }
5067
5068 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5069
5070 // calculate the PTS of the head of the timed buffer queue expressed in
5071 // local time
5072 int64_t headLocalPTS;
5073 {
5074 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5075
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005076 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005077
5078 if (mMediaTimeTransform.a_to_b_denom == 0) {
5079 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005080 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005081 return NO_ERROR;
5082 }
5083
5084 int64_t transformedPTS;
5085 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5086 &transformedPTS)) {
5087 // the transform failed. this shouldn't happen, but if it does
5088 // then just drop this buffer
5089 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005090 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005091 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005092 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005093 return NO_ERROR;
5094 }
5095
5096 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5097 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5098 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005099 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005100 buffer->frameCount = 0;
5101 return INVALID_OPERATION;
5102 }
5103 } else {
5104 headLocalPTS = transformedPTS;
5105 }
5106 }
5107
5108 // adjust the head buffer's PTS to reflect the portion of the head buffer
5109 // that has already been consumed
5110 int64_t effectivePTS = headLocalPTS +
5111 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5112
5113 // Calculate the delta in samples between the head of the input buffer
5114 // queue and the start of the next output buffer that will be written.
5115 // If the transformation fails because of over or underflow, it means
5116 // that the sample's position in the output stream is so far out of
5117 // whack that it should just be dropped.
5118 int64_t sampleDelta;
5119 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5120 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005121 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5122 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005123 continue;
5124 }
5125 if (!mLocalTimeToSampleTransform.doForwardTransform(
5126 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005127 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005128 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005129 continue;
5130 }
5131
John Grossman1c345192012-03-27 14:00:17 -07005132 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5133 " sampleDelta=[%d.%08x]",
5134 head.pts(), head.position(), pts,
5135 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5136 + (sampleDelta >> 32)),
5137 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005138
5139 // if the delta between the ideal placement for the next input sample and
5140 // the current output position is within this threshold, then we will
5141 // concatenate the next input samples to the previous output
5142 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005143 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005144
5145 // if this is the first buffer of audio that we're emitting from this track
5146 // then it should be almost exactly on time.
5147 const int64_t kSampleStartupThreshold = 1LL << 32;
5148
5149 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005150 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005151 // the next input is close enough to being on time, so concatenate it
5152 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005153 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005154
John Grossman1c345192012-03-27 14:00:17 -07005155 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5156 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005157 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005158 }
5159
5160 // Looks like our output is not on time. Reset our on timed status.
5161 // Next time we mix samples from our input queue, then should be within
5162 // the StartupThreshold.
5163 mTimedAudioOutputOnTime = false;
5164 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 // the gap between the current output position and the proper start of
5166 // the next input sample is too big, so fill it with silence
5167 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5168
John Grossman9fbdee12012-03-26 17:51:46 -07005169 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005170 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5171 return NO_ERROR;
5172 } else {
5173 // the next input sample is late
5174 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5175 size_t onTimeSamplePosition =
5176 head.position() + lateFrames * mCblk->frameSize;
5177
5178 if (onTimeSamplePosition > head.buffer()->size()) {
5179 // all the remaining samples in the head are too late, so
5180 // drop it and move on
5181 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005182 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005183 continue;
5184 } else {
5185 // skip over the late samples
5186 head.setPosition(onTimeSamplePosition);
5187
5188 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005189 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005190
5191 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5192 return NO_ERROR;
5193 }
5194 }
5195 }
5196}
5197
5198// Yield samples from the timed buffer queue head up to the given output
5199// buffer's capacity.
5200//
5201// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005202void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 AudioBufferProvider::Buffer* buffer) {
5204
5205 const TimedBuffer& head = mTimedBufferQueue[0];
5206
5207 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5208 head.position());
5209
5210 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5211 mCblk->frameSize);
5212 size_t framesRequested = buffer->frameCount;
5213 buffer->frameCount = min(framesLeftInHead, framesRequested);
5214
John Grossman9fbdee12012-03-26 17:51:46 -07005215 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 mTimedAudioOutputOnTime = true;
5217}
5218
5219// Yield samples of silence up to the given output buffer's capacity
5220//
5221// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005222void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005223 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5224
5225 // lazily allocate a buffer filled with silence
5226 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5227 delete [] mTimedSilenceBuffer;
5228 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5229 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5230 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5231 }
5232
5233 buffer->raw = mTimedSilenceBuffer;
5234 size_t framesRequested = buffer->frameCount;
5235 buffer->frameCount = min(numFrames, framesRequested);
5236
5237 mTimedAudioOutputOnTime = false;
5238}
5239
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005240// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005241void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5242 AudioBufferProvider::Buffer* buffer) {
5243
5244 Mutex::Autolock _l(mTimedBufferQueueLock);
5245
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005246 // If the buffer which was just released is part of the buffer at the head
5247 // of the queue, be sure to update the amt of the buffer which has been
5248 // consumed. If the buffer being returned is not part of the head of the
5249 // queue, its either because the buffer is part of the silence buffer, or
5250 // because the head of the timed queue was trimmed after the mixer called
5251 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005252 if (buffer->raw == mTimedSilenceBuffer) {
5253 ALOG_ASSERT(!mQueueHeadInFlight,
5254 "Queue head in flight during release of silence buffer!");
5255 goto done;
5256 }
5257
5258 ALOG_ASSERT(mQueueHeadInFlight,
5259 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5260 " head in flight.");
5261
5262 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005263 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005264
5265 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005266 void* end = reinterpret_cast<void*>(
5267 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5268 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005269
John Grossman9fbdee12012-03-26 17:51:46 -07005270 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5271 "released buffer not within the head of the timed buffer"
5272 " queue; qHead = [%p, %p], released buffer = %p",
5273 start, end, buffer->raw);
5274
5275 head.setPosition(head.position() +
5276 (buffer->frameCount * mCblk->frameSize));
5277 mQueueHeadInFlight = false;
5278
John Grossman1c345192012-03-27 14:00:17 -07005279 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5280 "Bad bookkeeping during releaseBuffer! Should have at"
5281 " least %u queued frames, but we think we have only %u",
5282 buffer->frameCount, mFramesPendingInQueue);
5283
5284 mFramesPendingInQueue -= buffer->frameCount;
5285
John Grossman9fbdee12012-03-26 17:51:46 -07005286 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5287 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005288 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005289 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005290 }
John Grossman9fbdee12012-03-26 17:51:46 -07005291 } else {
5292 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5293 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005294 }
5295
John Grossman9fbdee12012-03-26 17:51:46 -07005296done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005297 buffer->raw = 0;
5298 buffer->frameCount = 0;
5299}
5300
Glenn Kasten288ed212012-04-25 17:52:27 -07005301size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005302 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005303 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005304}
5305
5306AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5307 : mPTS(0), mPosition(0) {}
5308
5309AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5310 const sp<IMemory>& buffer, int64_t pts)
5311 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5312
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313// ----------------------------------------------------------------------------
5314
5315// RecordTrack constructor must be called with AudioFlinger::mLock held
5316AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005317 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 const sp<Client>& client,
5319 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005320 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005321 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323 int sessionId)
5324 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005325 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 mOverflow(false)
5327{
5328 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005329 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5330 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5331 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5332 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5333 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5334 } else {
5335 mCblk->frameSize = sizeof(int8_t);
5336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 }
5338}
5339
5340AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5341{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005342 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343}
5344
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005345// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005346status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347{
5348 audio_track_cblk_t* cblk = this->cblk();
5349 uint32_t framesAvail;
5350 uint32_t framesReq = buffer->frameCount;
5351
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005352 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005353 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005355 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005356 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 }
5358
5359 framesAvail = cblk->framesAvailable_l();
5360
Glenn Kastenf6b16782011-12-15 09:51:17 -08005361 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005362 uint32_t s = cblk->server;
5363 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5364
5365 if (framesReq > framesAvail) {
5366 framesReq = framesAvail;
5367 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005368 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 framesReq = bufferEnd - s;
5370 }
5371
5372 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 buffer->frameCount = framesReq;
5374 return NO_ERROR;
5375 }
5376
5377getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005378 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 buffer->frameCount = 0;
5380 return NOT_ENOUGH_DATA;
5381}
5382
Glenn Kasten3acbd052012-02-28 10:39:56 -08005383status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005384 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385{
5386 sp<ThreadBase> thread = mThread.promote();
5387 if (thread != 0) {
5388 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005389 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 } else {
5391 return BAD_VALUE;
5392 }
5393}
5394
5395void AudioFlinger::RecordThread::RecordTrack::stop()
5396{
5397 sp<ThreadBase> thread = mThread.promote();
5398 if (thread != 0) {
5399 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005400 recordThread->mLock.lock();
5401 bool doStop = recordThread->stop_l(this);
5402 if (doStop) {
5403 TrackBase::reset();
5404 // Force overrun condition to avoid false overrun callback until first data is
5405 // read from buffer
5406 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5407 }
5408 recordThread->mLock.unlock();
5409 if (doStop) {
5410 AudioSystem::stopInput(recordThread->id());
5411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 }
5413}
5414
Glenn Kasten510a3d62012-07-16 14:24:34 -07005415/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5416{
5417 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
5418}
5419
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5421{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005422 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005423 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005425 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 mSessionId,
5427 mFrameCount,
5428 mState,
5429 mCblk->sampleRate,
5430 mCblk->server,
5431 mCblk->user);
5432}
5433
5434
5435// ----------------------------------------------------------------------------
5436
5437AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005438 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 DuplicatingThread *sourceThread,
5440 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005441 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005442 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005444 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5445 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 mActive(false), mSourceThread(sourceThread)
5447{
5448
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 if (mCblk != NULL) {
5450 mCblk->flags |= CBLK_DIRECTION_OUT;
5451 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 mOutBuffer.frameCount = 0;
5453 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005454 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005455 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5456 mCblk, mBuffer, mCblk->buffers,
5457 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005459 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 }
5461}
5462
5463AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5464{
5465 clearBufferQueue();
5466}
5467
Glenn Kasten3acbd052012-02-28 10:39:56 -08005468status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005469 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005471 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 if (status != NO_ERROR) {
5473 return status;
5474 }
5475
5476 mActive = true;
5477 mRetryCount = 127;
5478 return status;
5479}
5480
5481void AudioFlinger::PlaybackThread::OutputTrack::stop()
5482{
5483 Track::stop();
5484 clearBufferQueue();
5485 mOutBuffer.frameCount = 0;
5486 mActive = false;
5487}
5488
5489bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5490{
5491 Buffer *pInBuffer;
5492 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005493 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 bool outputBufferFull = false;
5495 inBuffer.frameCount = frames;
5496 inBuffer.i16 = data;
5497
5498 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5499
5500 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005501 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 sp<ThreadBase> thread = mThread.promote();
5503 if (thread != 0) {
5504 MixerThread *mixerThread = (MixerThread *)thread.get();
5505 if (mCblk->frameCount > frames){
5506 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5507 uint32_t startFrames = (mCblk->frameCount - frames);
5508 pInBuffer = new Buffer;
5509 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5510 pInBuffer->frameCount = startFrames;
5511 pInBuffer->i16 = pInBuffer->mBuffer;
5512 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5513 mBufferQueue.add(pInBuffer);
5514 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005515 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 }
5517 }
5518 }
5519 }
5520
5521 while (waitTimeLeftMs) {
5522 // First write pending buffers, then new data
5523 if (mBufferQueue.size()) {
5524 pInBuffer = mBufferQueue.itemAt(0);
5525 } else {
5526 pInBuffer = &inBuffer;
5527 }
5528
5529 if (pInBuffer->frameCount == 0) {
5530 break;
5531 }
5532
5533 if (mOutBuffer.frameCount == 0) {
5534 mOutBuffer.frameCount = pInBuffer->frameCount;
5535 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005536 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005537 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 outputBufferFull = true;
5539 break;
5540 }
5541 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5542 if (waitTimeLeftMs >= waitTimeMs) {
5543 waitTimeLeftMs -= waitTimeMs;
5544 } else {
5545 waitTimeLeftMs = 0;
5546 }
5547 }
5548
5549 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5550 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5551 mCblk->stepUser(outFrames);
5552 pInBuffer->frameCount -= outFrames;
5553 pInBuffer->i16 += outFrames * channelCount;
5554 mOutBuffer.frameCount -= outFrames;
5555 mOutBuffer.i16 += outFrames * channelCount;
5556
5557 if (pInBuffer->frameCount == 0) {
5558 if (mBufferQueue.size()) {
5559 mBufferQueue.removeAt(0);
5560 delete [] pInBuffer->mBuffer;
5561 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 } else {
5564 break;
5565 }
5566 }
5567 }
5568
5569 // If we could not write all frames, allocate a buffer and queue it for next time.
5570 if (inBuffer.frameCount) {
5571 sp<ThreadBase> thread = mThread.promote();
5572 if (thread != 0 && !thread->standby()) {
5573 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5574 pInBuffer = new Buffer;
5575 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5576 pInBuffer->frameCount = inBuffer.frameCount;
5577 pInBuffer->i16 = pInBuffer->mBuffer;
5578 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5579 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005580 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005582 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 }
5584 }
5585 }
5586
5587 // Calling write() with a 0 length buffer, means that no more data will be written:
5588 // If no more buffers are pending, fill output track buffer to make sure it is started
5589 // by output mixer.
5590 if (frames == 0 && mBufferQueue.size() == 0) {
5591 if (mCblk->user < mCblk->frameCount) {
5592 frames = mCblk->frameCount - mCblk->user;
5593 pInBuffer = new Buffer;
5594 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5595 pInBuffer->frameCount = frames;
5596 pInBuffer->i16 = pInBuffer->mBuffer;
5597 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5598 mBufferQueue.add(pInBuffer);
5599 } else if (mActive) {
5600 stop();
5601 }
5602 }
5603
5604 return outputBufferFull;
5605}
5606
5607status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5608{
5609 int active;
5610 status_t result;
5611 audio_track_cblk_t* cblk = mCblk;
5612 uint32_t framesReq = buffer->frameCount;
5613
Steve Block3856b092011-10-20 11:56:00 +01005614// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 buffer->frameCount = 0;
5616
5617 uint32_t framesAvail = cblk->framesAvailable();
5618
5619
5620 if (framesAvail == 0) {
5621 Mutex::Autolock _l(cblk->lock);
5622 goto start_loop_here;
5623 while (framesAvail == 0) {
5624 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005625 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005626 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005627 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 }
5629 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5630 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005631 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 }
5633 // read the server count again
5634 start_loop_here:
5635 framesAvail = cblk->framesAvailable_l();
5636 }
5637 }
5638
5639// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005640// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641// }
5642
5643 if (framesReq > framesAvail) {
5644 framesReq = framesAvail;
5645 }
5646
5647 uint32_t u = cblk->user;
5648 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5649
Marco Nelissena1472d92012-03-30 14:36:54 -07005650 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 framesReq = bufferEnd - u;
5652 }
5653
5654 buffer->frameCount = framesReq;
5655 buffer->raw = (void *)cblk->buffer(u);
5656 return NO_ERROR;
5657}
5658
5659
5660void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5661{
5662 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663
5664 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005665 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 delete [] pBuffer->mBuffer;
5667 delete pBuffer;
5668 }
5669 mBufferQueue.clear();
5670}
5671
5672// ----------------------------------------------------------------------------
5673
5674AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5675 : RefBase(),
5676 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005677 // 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 -07005678 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005679 mPid(pid),
5680 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681{
5682 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5683}
5684
5685// Client destructor must be called with AudioFlinger::mLock held
5686AudioFlinger::Client::~Client()
5687{
5688 mAudioFlinger->removeClient_l(mPid);
5689}
5690
Glenn Kasten435dbe62012-01-30 10:15:48 -08005691sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692{
5693 return mMemoryDealer;
5694}
5695
John Grossman4ff14ba2012-02-08 16:37:41 -08005696// Reserve one of the limited slots for a timed audio track associated
5697// with this client
5698bool AudioFlinger::Client::reserveTimedTrack()
5699{
5700 const int kMaxTimedTracksPerClient = 4;
5701
5702 Mutex::Autolock _l(mTimedTrackLock);
5703
5704 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5705 ALOGW("can not create timed track - pid %d has exceeded the limit",
5706 mPid);
5707 return false;
5708 }
5709
5710 mTimedTrackCount++;
5711 return true;
5712}
5713
5714// Release a slot for a timed audio track
5715void AudioFlinger::Client::releaseTimedTrack()
5716{
5717 Mutex::Autolock _l(mTimedTrackLock);
5718 mTimedTrackCount--;
5719}
5720
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721// ----------------------------------------------------------------------------
5722
5723AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5724 const sp<IAudioFlingerClient>& client,
5725 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005726 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727{
5728}
5729
5730AudioFlinger::NotificationClient::~NotificationClient()
5731{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
5734void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5735{
5736 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005737 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738}
5739
5740// ----------------------------------------------------------------------------
5741
5742AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5743 : BnAudioTrack(),
5744 mTrack(track)
5745{
5746}
5747
5748AudioFlinger::TrackHandle::~TrackHandle() {
5749 // just stop the track on deletion, associated resources
5750 // will be freed from the main thread once all pending buffers have
5751 // been played. Unless it's not in the active track list, in which
5752 // case we free everything now...
5753 mTrack->destroy();
5754}
5755
Glenn Kasten90716c52012-01-26 13:40:12 -08005756sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5757 return mTrack->getCblk();
5758}
5759
Glenn Kasten3acbd052012-02-28 10:39:56 -08005760status_t AudioFlinger::TrackHandle::start() {
5761 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762}
5763
5764void AudioFlinger::TrackHandle::stop() {
5765 mTrack->stop();
5766}
5767
5768void AudioFlinger::TrackHandle::flush() {
5769 mTrack->flush();
5770}
5771
5772void AudioFlinger::TrackHandle::mute(bool e) {
5773 mTrack->mute(e);
5774}
5775
5776void AudioFlinger::TrackHandle::pause() {
5777 mTrack->pause();
5778}
5779
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5781{
5782 return mTrack->attachAuxEffect(EffectId);
5783}
5784
John Grossman4ff14ba2012-02-08 16:37:41 -08005785status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5786 sp<IMemory>* buffer) {
5787 if (!mTrack->isTimedTrack())
5788 return INVALID_OPERATION;
5789
5790 PlaybackThread::TimedTrack* tt =
5791 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5792 return tt->allocateTimedBuffer(size, buffer);
5793}
5794
5795status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5796 int64_t pts) {
5797 if (!mTrack->isTimedTrack())
5798 return INVALID_OPERATION;
5799
5800 PlaybackThread::TimedTrack* tt =
5801 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5802 return tt->queueTimedBuffer(buffer, pts);
5803}
5804
5805status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5806 const LinearTransform& xform, int target) {
5807
5808 if (!mTrack->isTimedTrack())
5809 return INVALID_OPERATION;
5810
5811 PlaybackThread::TimedTrack* tt =
5812 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5813 return tt->setMediaTimeTransform(
5814 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5815}
5816
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817status_t AudioFlinger::TrackHandle::onTransact(
5818 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5819{
5820 return BnAudioTrack::onTransact(code, data, reply, flags);
5821}
5822
5823// ----------------------------------------------------------------------------
5824
5825sp<IAudioRecord> AudioFlinger::openRecord(
5826 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005827 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005829 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005830 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005832 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005833 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 int *sessionId,
5835 status_t *status)
5836{
5837 sp<RecordThread::RecordTrack> recordTrack;
5838 sp<RecordHandle> recordHandle;
5839 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 status_t lStatus;
5841 RecordThread *thread;
5842 size_t inFrameCount;
5843 int lSessionId;
5844
5845 // check calling permissions
5846 if (!recordingAllowed()) {
5847 lStatus = PERMISSION_DENIED;
5848 goto Exit;
5849 }
5850
5851 // add client to list
5852 { // scope for mLock
5853 Mutex::Autolock _l(mLock);
5854 thread = checkRecordThread_l(input);
5855 if (thread == NULL) {
5856 lStatus = BAD_VALUE;
5857 goto Exit;
5858 }
5859
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005860 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861
5862 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005863 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 lSessionId = *sessionId;
5865 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 if (sessionId != NULL) {
5868 *sessionId = lSessionId;
5869 }
5870 }
5871 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005872 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5873 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5877 // destructor is called by the TrackBase destructor with mLock held
5878 client.clear();
5879 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 goto Exit;
5881 }
5882
5883 // return to handle to client
5884 recordHandle = new RecordHandle(recordTrack);
5885 lStatus = NO_ERROR;
5886
5887Exit:
5888 if (status) {
5889 *status = lStatus;
5890 }
5891 return recordHandle;
5892}
5893
5894// ----------------------------------------------------------------------------
5895
5896AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5897 : BnAudioRecord(),
5898 mRecordTrack(recordTrack)
5899{
5900}
5901
5902AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005903 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005904 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905}
5906
Glenn Kasten90716c52012-01-26 13:40:12 -08005907sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5908 return mRecordTrack->getCblk();
5909}
5910
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005911status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005912 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005913 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914}
5915
5916void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005917 stop_nonvirtual();
5918}
5919
5920void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005921 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922 mRecordTrack->stop();
5923}
5924
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925status_t AudioFlinger::RecordHandle::onTransact(
5926 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5927{
5928 return BnAudioRecord::onTransact(code, data, reply, flags);
5929}
5930
5931// ----------------------------------------------------------------------------
5932
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005933AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5934 AudioStreamIn *input,
5935 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005936 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005937 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005938 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005939 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005940 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005941 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005942 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005943 mReqSampleRate(sampleRate)
5944 // mBytesRead is only meaningful while active, and so is cleared in start()
5945 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946{
Glenn Kasten480b4682012-02-28 12:30:08 -08005947 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005948
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 readInputParameters();
5950}
5951
5952
5953AudioFlinger::RecordThread::~RecordThread()
5954{
5955 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005956 delete mResampler;
5957 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958}
5959
5960void AudioFlinger::RecordThread::onFirstRef()
5961{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005962 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963}
5964
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005965status_t AudioFlinger::RecordThread::readyToRun()
5966{
5967 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005968 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005969 return status;
5970}
5971
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972bool AudioFlinger::RecordThread::threadLoop()
5973{
5974 AudioBufferProvider::Buffer buffer;
5975 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005976 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977
Eric Laurent44d98482010-09-30 16:12:31 -07005978 nsecs_t lastWarning = 0;
5979
Glenn Kastene4e2a372012-07-23 12:55:09 -07005980 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005981 acquireWakeLock();
5982
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 // start recording
5984 while (!exitPending()) {
5985
5986 processConfigEvents();
5987
5988 { // scope for mLock
5989 Mutex::Autolock _l(mLock);
5990 checkForNewParameters_l();
5991 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005992 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993
5994 if (exitPending()) break;
5995
Eric Laurentfeb0db62011-07-22 09:04:31 -07005996 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005997 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 // go to sleep
5999 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006000 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006001 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 continue;
6003 }
6004 if (mActiveTrack != 0) {
6005 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006006 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 mActiveTrack.clear();
6008 mStartStopCond.broadcast();
6009 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6010 if (mReqChannelCount != mActiveTrack->channelCount()) {
6011 mActiveTrack.clear();
6012 mStartStopCond.broadcast();
6013 } else if (mBytesRead != 0) {
6014 // record start succeeds only if first read from audio input
6015 // succeeds
6016 if (mBytesRead > 0) {
6017 mActiveTrack->mState = TrackBase::ACTIVE;
6018 } else {
6019 mActiveTrack.clear();
6020 }
6021 mStartStopCond.broadcast();
6022 }
6023 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006024 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6025 removeTrack_l(mActiveTrack);
6026 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027 }
6028 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 }
6031
6032 if (mActiveTrack != 0) {
6033 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6034 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006035 unlockEffectChains(effectChains);
6036 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 continue;
6038 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039 for (size_t i = 0; i < effectChains.size(); i ++) {
6040 effectChains[i]->process_l();
6041 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006042
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006044 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006046 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 // no resampling
6048 while (framesOut) {
6049 size_t framesIn = mFrameCount - mRsmpInIndex;
6050 if (framesIn) {
6051 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6052 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6053 if (framesIn > framesOut)
6054 framesIn = framesOut;
6055 mRsmpInIndex += framesIn;
6056 framesOut -= framesIn;
6057 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006058 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 memcpy(dst, src, framesIn * mFrameSize);
6060 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006062 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6063 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006065 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6066 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 }
6068 }
6069 }
6070 if (framesOut && mFrameCount == mRsmpInIndex) {
6071 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006072 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006073 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 framesOut = 0;
6075 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006076 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 mRsmpInIndex = 0;
6078 }
6079 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006080 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6082 // Force input into standby so that it tries to
6083 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006084 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006085 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 }
6087 mRsmpInIndex = mFrameCount;
6088 framesOut = 0;
6089 buffer.frameCount = 0;
6090 }
6091 }
6092 }
6093 } else {
6094 // resampling
6095
6096 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6097 // alter output frame count as if we were expecting stereo samples
6098 if (mChannelCount == 1 && mReqChannelCount == 1) {
6099 framesOut >>= 1;
6100 }
Glenn Kasten2662ac92012-07-30 10:59:30 -07006101 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6103 // are 32 bit aligned which should be always true.
6104 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006105 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006107 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6108 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006110 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 }
6112
6113 }
Eric Laurenta011e352012-03-29 15:51:43 -07006114 if (mFramestoDrop == 0) {
6115 mActiveTrack->releaseBuffer(&buffer);
6116 } else {
6117 if (mFramestoDrop > 0) {
6118 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006119 if (mFramestoDrop <= 0) {
6120 clearSyncStartEvent();
6121 }
6122 } else {
6123 mFramestoDrop += buffer.frameCount;
6124 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6125 mSyncStartEvent->isCancelled()) {
6126 ALOGW("Synced record %s, session %d, trigger session %d",
6127 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6128 mActiveTrack->sessionId(),
6129 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6130 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006131 }
6132 }
6133 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006134 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 }
6136 // client isn't retrieving buffers fast enough
6137 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006138 if (!mActiveTrack->setOverflow()) {
6139 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006140 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006141 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006142 lastWarning = now;
6143 }
6144 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 // Release the processor for a while before asking for a new buffer.
6146 // This will give the application more chance to read from the buffer and
6147 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 }
6150 }
Eric Laurentec437d82011-07-26 20:54:46 -07006151 // enable changes in effect chain
6152 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 }
6155
Glenn Kastene4e2a372012-07-23 12:55:09 -07006156 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157
Glenn Kasten33e6e352012-07-16 15:56:57 -07006158 {
6159 Mutex::Autolock _l(mLock);
6160 mActiveTrack.clear();
6161 mStartStopCond.broadcast();
6162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163
Eric Laurentfeb0db62011-07-22 09:04:31 -07006164 releaseWakeLock();
6165
Steve Block3856b092011-10-20 11:56:00 +01006166 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167 return false;
6168}
6169
Glenn Kastene4e2a372012-07-23 12:55:09 -07006170void AudioFlinger::RecordThread::standby()
6171{
6172 if (!mStandby) {
6173 inputStandBy();
6174 mStandby = true;
6175 }
6176}
6177
6178void AudioFlinger::RecordThread::inputStandBy()
6179{
6180 mInput->stream->common.standby(&mInput->stream->common);
6181}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182
6183sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6184 const sp<AudioFlinger::Client>& client,
6185 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006186 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006187 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006188 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006189 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006190 IAudioFlinger::track_flags_t flags,
6191 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006192 status_t *status)
6193{
6194 sp<RecordTrack> track;
6195 status_t lStatus;
6196
6197 lStatus = initCheck();
6198 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006199 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006200 goto Exit;
6201 }
6202
Glenn Kasten1879fff2012-07-11 15:36:59 -07006203 // FIXME use flags and tid similar to createTrack_l()
6204
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006205 { // scope for mLock
6206 Mutex::Autolock _l(mLock);
6207
6208 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006209 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006210
Glenn Kasten7378ca52012-01-20 13:44:40 -08006211 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006212 lStatus = NO_MEMORY;
6213 goto Exit;
6214 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006215 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216
Eric Laurent59bd0da2011-08-01 09:52:20 -07006217 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006218 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6219 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006220 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6221 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006222 }
6223 lStatus = NO_ERROR;
6224
6225Exit:
6226 if (status) {
6227 *status = lStatus;
6228 }
6229 return track;
6230}
6231
Eric Laurenta011e352012-03-29 15:51:43 -07006232status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006233 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006234 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235{
Glenn Kasten58912562012-04-03 10:45:00 -07006236 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006237 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006239
6240 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006241 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006242 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6243 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6244 triggerSession,
6245 recordTrack->sessionId(),
6246 syncStartEventCallback,
6247 this);
Eric Laurent29864602012-05-08 18:57:51 -07006248 // Sync event can be cancelled by the trigger session if the track is not in a
6249 // compatible state in which case we start record immediately
6250 if (mSyncStartEvent->isCancelled()) {
6251 clearSyncStartEvent();
6252 } else {
6253 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6254 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6255 }
Eric Laurenta011e352012-03-29 15:51:43 -07006256 }
6257
Mathias Agopian65ab4712010-07-14 17:59:35 -07006258 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006259 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 if (mActiveTrack != 0) {
6261 if (recordTrack != mActiveTrack.get()) {
6262 status = -EBUSY;
6263 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6264 mActiveTrack->mState = TrackBase::ACTIVE;
6265 }
6266 return status;
6267 }
6268
6269 recordTrack->mState = TrackBase::IDLE;
6270 mActiveTrack = recordTrack;
6271 mLock.unlock();
6272 status_t status = AudioSystem::startInput(mId);
6273 mLock.lock();
6274 if (status != NO_ERROR) {
6275 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006276 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 return status;
6278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 mRsmpInIndex = mFrameCount;
6280 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006281 if (mResampler != NULL) {
6282 mResampler->reset();
6283 }
6284 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006286 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 mWaitWorkCV.signal();
6288 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006289 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 mActiveTrack.clear();
6291 status = INVALID_OPERATION;
6292 goto startError;
6293 }
6294 mStartStopCond.wait(mLock);
6295 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006296 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 status = BAD_VALUE;
6298 goto startError;
6299 }
Steve Block3856b092011-10-20 11:56:00 +01006300 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 return status;
6302 }
6303startError:
6304 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006305 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 return status;
6307}
6308
Eric Laurenta011e352012-03-29 15:51:43 -07006309void AudioFlinger::RecordThread::clearSyncStartEvent()
6310{
6311 if (mSyncStartEvent != 0) {
6312 mSyncStartEvent->cancel();
6313 }
6314 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006315 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006316}
6317
6318void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6319{
6320 sp<SyncEvent> strongEvent = event.promote();
6321
6322 if (strongEvent != 0) {
6323 RecordThread *me = (RecordThread *)strongEvent->cookie();
6324 me->handleSyncStartEvent(strongEvent);
6325 }
6326}
6327
6328void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6329{
Eric Laurent29864602012-05-08 18:57:51 -07006330 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006331 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6332 // from audio HAL
6333 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006334 }
6335}
6336
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006337bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006338 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006339 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6340 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006342 recordTrack->mState = TrackBase::PAUSING;
6343 // do not wait for mStartStopCond if exiting
6344 if (exitPending()) {
6345 return true;
6346 }
6347 mStartStopCond.wait(mLock);
6348 // if we have been restarted, recordTrack == mActiveTrack.get() here
6349 if (exitPending() || recordTrack != mActiveTrack.get()) {
6350 ALOGV("Record stopped OK");
6351 return true;
6352 }
6353 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354}
6355
Glenn Kasten106e8a42012-08-02 13:37:12 -07006356bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006357{
6358 return false;
6359}
6360
6361status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6362{
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006363#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 -07006364 if (!isValidSyncEvent(event)) {
6365 return BAD_VALUE;
6366 }
6367
Glenn Kasten510a3d62012-07-16 14:24:34 -07006368 int eventSession = event->triggerSession();
6369 status_t ret = NAME_NOT_FOUND;
6370
Eric Laurenta011e352012-03-29 15:51:43 -07006371 Mutex::Autolock _l(mLock);
6372
Glenn Kasten510a3d62012-07-16 14:24:34 -07006373 for (size_t i = 0; i < mTracks.size(); i++) {
6374 sp<RecordTrack> track = mTracks[i];
6375 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006376 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006377 ret = NO_ERROR;
6378 }
Eric Laurenta011e352012-03-29 15:51:43 -07006379 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006380 return ret;
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006381#else
6382 return BAD_VALUE;
6383#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006384}
6385
6386void AudioFlinger::RecordThread::RecordTrack::destroy()
6387{
6388 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6389 sp<RecordTrack> keep(this);
6390 {
6391 sp<ThreadBase> thread = mThread.promote();
6392 if (thread != 0) {
6393 if (mState == ACTIVE || mState == RESUMING) {
6394 AudioSystem::stopInput(thread->id());
6395 }
6396 AudioSystem::releaseInput(thread->id());
6397 Mutex::Autolock _l(thread->mLock);
6398 RecordThread *recordThread = (RecordThread *) thread.get();
6399 recordThread->destroyTrack_l(this);
6400 }
6401 }
6402}
6403
6404// destroyTrack_l() must be called with ThreadBase::mLock held
6405void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6406{
6407 track->mState = TrackBase::TERMINATED;
6408 // active tracks are removed by threadLoop()
6409 if (mActiveTrack != track) {
6410 removeTrack_l(track);
6411 }
6412}
6413
6414void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6415{
6416 mTracks.remove(track);
6417 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006418}
6419
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006420void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006422 dumpInternals(fd, args);
6423 dumpTracks(fd, args);
6424 dumpEffectChains(fd, args);
6425}
6426
6427void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6428{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 const size_t SIZE = 256;
6430 char buffer[SIZE];
6431 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432
6433 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6434 result.append(buffer);
6435
6436 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6438 result.append(buffer);
6439 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6440 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006441 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 result.append(buffer);
6443 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6444 result.append(buffer);
6445 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6446 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006448 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006450
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 write(fd, result.string(), result.size());
6452
6453 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006454}
6455
6456void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6457{
6458 const size_t SIZE = 256;
6459 char buffer[SIZE];
6460 String8 result;
6461
6462 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6463 result.append(buffer);
6464 RecordTrack::appendDumpHeader(result);
6465 for (size_t i = 0; i < mTracks.size(); ++i) {
6466 sp<RecordTrack> track = mTracks[i];
6467 if (track != 0) {
6468 track->dump(buffer, SIZE);
6469 result.append(buffer);
6470 }
6471 }
6472
6473 if (mActiveTrack != 0) {
6474 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6475 result.append(buffer);
6476 RecordTrack::appendDumpHeader(result);
6477 mActiveTrack->dump(buffer, SIZE);
6478 result.append(buffer);
6479
6480 }
6481 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006482}
6483
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006484// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006485status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486{
6487 size_t framesReq = buffer->frameCount;
6488 size_t framesReady = mFrameCount - mRsmpInIndex;
6489 int channelCount;
6490
6491 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006492 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006494 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6496 // Force input into standby so that it tries to
6497 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006498 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006499 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006501 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 buffer->frameCount = 0;
6503 return NOT_ENOUGH_DATA;
6504 }
6505 mRsmpInIndex = 0;
6506 framesReady = mFrameCount;
6507 }
6508
6509 if (framesReq > framesReady) {
6510 framesReq = framesReady;
6511 }
6512
6513 if (mChannelCount == 1 && mReqChannelCount == 2) {
6514 channelCount = 1;
6515 } else {
6516 channelCount = 2;
6517 }
6518 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6519 buffer->frameCount = framesReq;
6520 return NO_ERROR;
6521}
6522
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006523// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6525{
6526 mRsmpInIndex += buffer->frameCount;
6527 buffer->frameCount = 0;
6528}
6529
6530bool AudioFlinger::RecordThread::checkForNewParameters_l()
6531{
6532 bool reconfig = false;
6533
6534 while (!mNewParameters.isEmpty()) {
6535 status_t status = NO_ERROR;
6536 String8 keyValuePair = mNewParameters[0];
6537 AudioParameter param = AudioParameter(keyValuePair);
6538 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006539 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 int reqSamplingRate = mReqSampleRate;
6541 int reqChannelCount = mReqChannelCount;
6542
6543 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6544 reqSamplingRate = value;
6545 reconfig = true;
6546 }
6547 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006548 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 reconfig = true;
6550 }
6551 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006552 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 reconfig = true;
6554 }
6555 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6556 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006557 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 // if frame count is changed after track creation
6559 if (mActiveTrack != 0) {
6560 status = INVALID_OPERATION;
6561 } else {
6562 reconfig = true;
6563 }
6564 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006565 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6566 // forward device change to effects that have requested to be
6567 // aware of attached audio device.
6568 for (size_t i = 0; i < mEffectChains.size(); i++) {
6569 mEffectChains[i]->setDevice_l(value);
6570 }
6571 // store input device and output device but do not forward output device to audio HAL.
6572 // Note that status is ignored by the caller for output device
6573 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006574 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006575 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006576 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006577 status = BAD_VALUE;
6578 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006579 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006580 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006581 if (mTracks.size() > 0) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07006582 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006583 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006584 for (size_t i = 0; i < mTracks.size(); i++) {
6585 sp<RecordTrack> track = mTracks[i];
6586 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6587 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6588 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006589 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006590 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006591 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006592 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006593 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006595 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006597 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006598 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6599 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600 }
6601 if (reconfig) {
6602 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006603 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006604 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006605 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006606 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6607 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 status = NO_ERROR;
6609 }
6610 if (status == NO_ERROR) {
6611 readInputParameters();
6612 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6613 }
6614 }
6615 }
6616
6617 mNewParameters.removeAt(0);
6618
6619 mParamStatus = status;
6620 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006621 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6622 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006623 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 }
6625 return reconfig;
6626}
6627
6628String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6629{
Dima Zavinfce7a472011-04-19 22:30:36 -07006630 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006631 String8 out_s8 = String8();
6632
6633 Mutex::Autolock _l(mLock);
6634 if (initCheck() != NO_ERROR) {
6635 return out_s8;
6636 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006637
Dima Zavin799a70e2011-04-18 16:57:27 -07006638 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006639 out_s8 = String8(s);
6640 free(s);
6641 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642}
6643
6644void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6645 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006646 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006647
6648 switch (event) {
6649 case AudioSystem::INPUT_OPENED:
6650 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006651 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652 desc.samplingRate = mSampleRate;
6653 desc.format = mFormat;
6654 desc.frameCount = mFrameCount;
6655 desc.latency = 0;
6656 param2 = &desc;
6657 break;
6658
6659 case AudioSystem::INPUT_CLOSED:
6660 default:
6661 break;
6662 }
6663 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6664}
6665
6666void AudioFlinger::RecordThread::readInputParameters()
6667{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006668 delete mRsmpInBuffer;
6669 // mRsmpInBuffer is always assigned a new[] below
6670 delete mRsmpOutBuffer;
6671 mRsmpOutBuffer = NULL;
6672 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006673 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674
Dima Zavin799a70e2011-04-18 16:57:27 -07006675 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006676 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6677 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006678 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006679 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006680 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006682 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6684
Glenn Kasten53d76db2012-03-08 12:32:47 -08006685 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 {
6687 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006688 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6689 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 if (mChannelCount == 1 && mReqChannelCount == 2) {
6691 channelCount = 1;
6692 } else {
6693 channelCount = 2;
6694 }
6695 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6696 mResampler->setSampleRate(mSampleRate);
6697 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6698 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6699
6700 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6701 if (mChannelCount == 1 && mReqChannelCount == 1) {
6702 mFrameCount >>= 1;
6703 }
6704
6705 }
6706 mRsmpInIndex = mFrameCount;
6707}
6708
6709unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6710{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006711 Mutex::Autolock _l(mLock);
6712 if (initCheck() != NO_ERROR) {
6713 return 0;
6714 }
6715
Dima Zavin799a70e2011-04-18 16:57:27 -07006716 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717}
6718
Glenn Kasten106e8a42012-08-02 13:37:12 -07006719uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006720{
6721 Mutex::Autolock _l(mLock);
6722 uint32_t result = 0;
6723 if (getEffectChain_l(sessionId) != 0) {
6724 result = EFFECT_SESSION;
6725 }
6726
Glenn Kasten510a3d62012-07-16 14:24:34 -07006727 for (size_t i = 0; i < mTracks.size(); ++i) {
6728 if (sessionId == mTracks[i]->sessionId()) {
6729 result |= TRACK_SESSION;
6730 break;
6731 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006732 }
6733
6734 return result;
6735}
6736
Glenn Kasten106e8a42012-08-02 13:37:12 -07006737KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006738{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006739 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006740 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006741 for (size_t j = 0; j < mTracks.size(); ++j) {
6742 sp<RecordThread::RecordTrack> track = mTracks[j];
6743 int sessionId = track->sessionId();
6744 if (ids.indexOfKey(sessionId) < 0) {
6745 ids.add(sessionId, true);
6746 }
6747 }
6748 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006749}
6750
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006751AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6752{
6753 Mutex::Autolock _l(mLock);
6754 AudioStreamIn *input = mInput;
6755 mInput = NULL;
6756 return input;
6757}
6758
6759// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006760audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006761{
6762 if (mInput == NULL) {
6763 return NULL;
6764 }
6765 return &mInput->stream->common;
6766}
6767
6768
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769// ----------------------------------------------------------------------------
6770
Eric Laurenta4c5a552012-03-29 10:12:40 -07006771audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6772{
6773 if (!settingsAllowed()) {
6774 return 0;
6775 }
6776 Mutex::Autolock _l(mLock);
6777 return loadHwModule_l(name);
6778}
6779
6780// loadHwModule_l() must be called with AudioFlinger::mLock held
6781audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6782{
6783 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6784 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6785 ALOGW("loadHwModule() module %s already loaded", name);
6786 return mAudioHwDevs.keyAt(i);
6787 }
6788 }
6789
Eric Laurenta4c5a552012-03-29 10:12:40 -07006790 audio_hw_device_t *dev;
6791
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006792 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006793 if (rc) {
6794 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6795 return 0;
6796 }
6797
6798 mHardwareStatus = AUDIO_HW_INIT;
6799 rc = dev->init_check(dev);
6800 mHardwareStatus = AUDIO_HW_IDLE;
6801 if (rc) {
6802 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6803 return 0;
6804 }
6805
John Grossmanee578c02012-07-23 17:05:46 -07006806 // Check and cache this HAL's level of support for master mute and master
6807 // volume. If this is the first HAL opened, and it supports the get
6808 // methods, use the initial values provided by the HAL as the current
6809 // master mute and volume settings.
6810
6811 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6812 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006813 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006814
6815 if (0 == mAudioHwDevs.size()) {
6816 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6817 if (NULL != dev->get_master_volume) {
6818 float mv;
6819 if (OK == dev->get_master_volume(dev, &mv)) {
6820 mMasterVolume = mv;
6821 }
6822 }
6823
6824 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6825 if (NULL != dev->get_master_mute) {
6826 bool mm;
6827 if (OK == dev->get_master_mute(dev, &mm)) {
6828 mMasterMute = mm;
6829 }
6830 }
6831 }
6832
Eric Laurenta4c5a552012-03-29 10:12:40 -07006833 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006834 if ((NULL != dev->set_master_volume) &&
6835 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6836 flags = static_cast<AudioHwDevice::Flags>(flags |
6837 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6838 }
6839
6840 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6841 if ((NULL != dev->set_master_mute) &&
6842 (OK == dev->set_master_mute(dev, mMasterMute))) {
6843 flags = static_cast<AudioHwDevice::Flags>(flags |
6844 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6845 }
6846
Eric Laurenta4c5a552012-03-29 10:12:40 -07006847 mHardwareStatus = AUDIO_HW_IDLE;
6848 }
6849
6850 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006851 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006852
6853 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006854 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006855
6856 return handle;
6857
6858}
6859
6860audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6861 audio_devices_t *pDevices,
6862 uint32_t *pSamplingRate,
6863 audio_format_t *pFormat,
6864 audio_channel_mask_t *pChannelMask,
6865 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006866 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867{
6868 status_t status;
6869 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006870 struct audio_config config = {
6871 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6872 channel_mask: pChannelMask ? *pChannelMask : 0,
6873 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6874 };
6875 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006876 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877
Eric Laurenta4c5a552012-03-29 10:12:40 -07006878 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6879 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006880 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006881 config.sample_rate,
6882 config.format,
6883 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006884 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885
6886 if (pDevices == NULL || *pDevices == 0) {
6887 return 0;
6888 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006889
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 Mutex::Autolock _l(mLock);
6891
Eric Laurenta4c5a552012-03-29 10:12:40 -07006892 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006893 if (outHwDev == NULL)
6894 return 0;
6895
John Grossmanee578c02012-07-23 17:05:46 -07006896 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006897 audio_io_handle_t id = nextUniqueId();
6898
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006899 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006900
John Grossmanee578c02012-07-23 17:05:46 -07006901 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006902 id,
6903 *pDevices,
6904 (audio_output_flags_t)flags,
6905 &config,
6906 &outStream);
6907
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006908 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006909 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006910 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006911 config.sample_rate,
6912 config.format,
6913 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914 status);
6915
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006916 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006917 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006918
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006919 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006920 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6921 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006923 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924 } else {
6925 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006926 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 }
6928 mPlaybackThreads.add(id, thread);
6929
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006930 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6931 if (pFormat != NULL) *pFormat = config.format;
6932 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006933 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934
6935 // notify client processes of the new output creation
6936 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006937
6938 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006939 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006940 ALOGI("Using module %d has the primary audio interface", module);
6941 mPrimaryHardwareDev = outHwDev;
6942
6943 AutoMutex lock(mHardwareLock);
6944 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07006945 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006946 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 return id;
6949 }
6950
6951 return 0;
6952}
6953
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006954audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6955 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956{
6957 Mutex::Autolock _l(mLock);
6958 MixerThread *thread1 = checkMixerThread_l(output1);
6959 MixerThread *thread2 = checkMixerThread_l(output2);
6960
6961 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006962 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963 return 0;
6964 }
6965
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006966 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6968 thread->addOutputTrack(thread2);
6969 mPlaybackThreads.add(id, thread);
6970 // notify client processes of the new output creation
6971 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6972 return id;
6973}
6974
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006975status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976{
Glenn Kastend96c5722012-04-25 13:44:49 -07006977 return closeOutput_nonvirtual(output);
6978}
6979
6980status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6981{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 // keep strong reference on the playback thread so that
6983 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006984 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 {
6986 Mutex::Autolock _l(mLock);
6987 thread = checkPlaybackThread_l(output);
6988 if (thread == NULL) {
6989 return BAD_VALUE;
6990 }
6991
Steve Block3856b092011-10-20 11:56:00 +01006992 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006994 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6998 dupThread->removeOutputTrack((MixerThread *)thread.get());
6999 }
7000 }
7001 }
Glenn Kastena1117922012-01-26 10:53:32 -08007002 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 mPlaybackThreads.removeItem(output);
7004 }
7005 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007006 // The thread entity (active unit of execution) is no longer running here,
7007 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007009 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007010 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007011 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007012 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007013 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007014 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 }
7016 return NO_ERROR;
7017}
7018
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007019status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020{
7021 Mutex::Autolock _l(mLock);
7022 PlaybackThread *thread = checkPlaybackThread_l(output);
7023
7024 if (thread == NULL) {
7025 return BAD_VALUE;
7026 }
7027
Steve Block3856b092011-10-20 11:56:00 +01007028 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029 thread->suspend();
7030
7031 return NO_ERROR;
7032}
7033
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007034status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035{
7036 Mutex::Autolock _l(mLock);
7037 PlaybackThread *thread = checkPlaybackThread_l(output);
7038
7039 if (thread == NULL) {
7040 return BAD_VALUE;
7041 }
7042
Steve Block3856b092011-10-20 11:56:00 +01007043 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044
7045 thread->restore();
7046
7047 return NO_ERROR;
7048}
7049
Eric Laurenta4c5a552012-03-29 10:12:40 -07007050audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7051 audio_devices_t *pDevices,
7052 uint32_t *pSamplingRate,
7053 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007054 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055{
7056 status_t status;
7057 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007058 struct audio_config config = {
7059 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7060 channel_mask: pChannelMask ? *pChannelMask : 0,
7061 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7062 };
7063 uint32_t reqSamplingRate = config.sample_rate;
7064 audio_format_t reqFormat = config.format;
7065 audio_channel_mask_t reqChannels = config.channel_mask;
7066 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007067 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068
7069 if (pDevices == NULL || *pDevices == 0) {
7070 return 0;
7071 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007072
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 Mutex::Autolock _l(mLock);
7074
Eric Laurenta4c5a552012-03-29 10:12:40 -07007075 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007076 if (inHwDev == NULL)
7077 return 0;
7078
John Grossmanee578c02012-07-23 17:05:46 -07007079 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007080 audio_io_handle_t id = nextUniqueId();
7081
John Grossmanee578c02012-07-23 17:05:46 -07007082 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007083 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007084 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007085 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007086 config.sample_rate,
7087 config.format,
7088 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 status);
7090
7091 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7092 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7093 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007094 if (status == BAD_VALUE &&
7095 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7096 (config.sample_rate <= 2 * reqSamplingRate) &&
7097 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007098 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007099 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007100 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 }
7102
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007103 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007104 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7105
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007106 // Start record thread
7107 // RecorThread require both input and output device indication to forward to audio
7108 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007109 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007110 thread = new RecordThread(this,
7111 input,
7112 reqSamplingRate,
7113 reqChannels,
7114 id,
7115 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007116 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007117 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007118 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007119 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007120 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121
Mathias Agopian65ab4712010-07-14 17:59:35 -07007122 // notify client processes of the new input creation
7123 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7124 return id;
7125 }
7126
7127 return 0;
7128}
7129
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007130status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131{
Glenn Kastend96c5722012-04-25 13:44:49 -07007132 return closeInput_nonvirtual(input);
7133}
7134
7135status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7136{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 // keep strong reference on the record thread so that
7138 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007139 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 {
7141 Mutex::Autolock _l(mLock);
7142 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007143 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 return BAD_VALUE;
7145 }
7146
Steve Block3856b092011-10-20 11:56:00 +01007147 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007148 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149 mRecordThreads.removeItem(input);
7150 }
7151 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007152 // The thread entity (active unit of execution) is no longer running here,
7153 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007155 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007156 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007157 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007158 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007159 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160
7161 return NO_ERROR;
7162}
7163
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007164status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
7166 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007167 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168
7169 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7170 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007171 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173
7174 return NO_ERROR;
7175}
7176
7177
7178int AudioFlinger::newAudioSessionId()
7179{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181}
7182
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007183void AudioFlinger::acquireAudioSessionId(int audioSession)
7184{
7185 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007186 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007187 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007188 size_t num = mAudioSessionRefs.size();
7189 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007190 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007191 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7192 ref->mCnt++;
7193 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007194 return;
7195 }
7196 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007197 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7198 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007199}
7200
7201void AudioFlinger::releaseAudioSessionId(int audioSession)
7202{
7203 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007204 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007205 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007206 size_t num = mAudioSessionRefs.size();
7207 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007208 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007209 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7210 ref->mCnt--;
7211 ALOGV(" decremented refcount to %d", ref->mCnt);
7212 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007213 mAudioSessionRefs.removeAt(i);
7214 delete ref;
7215 purgeStaleEffects_l();
7216 }
7217 return;
7218 }
7219 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007220 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007221}
7222
7223void AudioFlinger::purgeStaleEffects_l() {
7224
Steve Block3856b092011-10-20 11:56:00 +01007225 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007226
7227 Vector< sp<EffectChain> > chains;
7228
7229 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7230 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7231 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7232 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007233 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7234 chains.push(ec);
7235 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007236 }
7237 }
7238 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7239 sp<RecordThread> t = mRecordThreads.valueAt(i);
7240 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7241 sp<EffectChain> ec = t->mEffectChains[j];
7242 chains.push(ec);
7243 }
7244 }
7245
7246 for (size_t i = 0; i < chains.size(); i++) {
7247 sp<EffectChain> ec = chains[i];
7248 int sessionid = ec->sessionId();
7249 sp<ThreadBase> t = ec->mThread.promote();
7250 if (t == 0) {
7251 continue;
7252 }
7253 size_t numsessionrefs = mAudioSessionRefs.size();
7254 bool found = false;
7255 for (size_t k = 0; k < numsessionrefs; k++) {
7256 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007257 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007258 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007259 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007260 found = true;
7261 break;
7262 }
7263 }
7264 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007265 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007266 // remove all effects from the chain
7267 while (ec->mEffects.size()) {
7268 sp<EffectModule> effect = ec->mEffects[0];
7269 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007270 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007271 if (effect->purgeHandles()) {
7272 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007273 }
7274 AudioSystem::unregisterEffect(effect->id());
7275 }
7276 }
7277 }
7278 return;
7279}
7280
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007282AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283{
Glenn Kastena1117922012-01-26 10:53:32 -08007284 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285}
7286
7287// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007288AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289{
7290 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007291 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007292}
7293
7294// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007295AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296{
Glenn Kastena1117922012-01-26 10:53:32 -08007297 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007298}
7299
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007300uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007302 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303}
7304
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007305AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306{
7307 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7308 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007309 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007310 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007311 return thread;
7312 }
7313 }
7314 return NULL;
7315}
7316
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007317audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007318{
7319 PlaybackThread *thread = primaryPlaybackThread_l();
7320
7321 if (thread == NULL) {
7322 return 0;
7323 }
7324
7325 return thread->device();
7326}
7327
Eric Laurenta011e352012-03-29 15:51:43 -07007328sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7329 int triggerSession,
7330 int listenerSession,
7331 sync_event_callback_t callBack,
7332 void *cookie)
7333{
7334 Mutex::Autolock _l(mLock);
7335
7336 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7337 status_t playStatus = NAME_NOT_FOUND;
7338 status_t recStatus = NAME_NOT_FOUND;
7339 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7340 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7341 if (playStatus == NO_ERROR) {
7342 return event;
7343 }
7344 }
7345 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7346 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7347 if (recStatus == NO_ERROR) {
7348 return event;
7349 }
7350 }
7351 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7352 mPendingSyncEvents.add(event);
7353 } else {
7354 ALOGV("createSyncEvent() invalid event %d", event->type());
7355 event.clear();
7356 }
7357 return event;
7358}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007359
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360// ----------------------------------------------------------------------------
7361// Effect management
7362// ----------------------------------------------------------------------------
7363
7364
Glenn Kastenf587ba52012-01-26 16:25:10 -08007365status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366{
7367 Mutex::Autolock _l(mLock);
7368 return EffectQueryNumberEffects(numEffects);
7369}
7370
Glenn Kastenf587ba52012-01-26 16:25:10 -08007371status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372{
7373 Mutex::Autolock _l(mLock);
7374 return EffectQueryEffect(index, descriptor);
7375}
7376
Glenn Kasten5e92a782012-01-30 07:40:52 -08007377status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007378 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379{
7380 Mutex::Autolock _l(mLock);
7381 return EffectGetDescriptor(pUuid, descriptor);
7382}
7383
7384
Mathias Agopian65ab4712010-07-14 17:59:35 -07007385sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7386 effect_descriptor_t *pDesc,
7387 const sp<IEffectClient>& effectClient,
7388 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007389 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 int sessionId,
7391 status_t *status,
7392 int *id,
7393 int *enabled)
7394{
7395 status_t lStatus = NO_ERROR;
7396 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007399 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401
7402 if (pDesc == NULL) {
7403 lStatus = BAD_VALUE;
7404 goto Exit;
7405 }
7406
Eric Laurent84e9a102010-09-23 16:10:16 -07007407 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007408 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007409 lStatus = PERMISSION_DENIED;
7410 goto Exit;
7411 }
7412
Dima Zavinfce7a472011-04-19 22:30:36 -07007413 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007414 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007415 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007416 lStatus = PERMISSION_DENIED;
7417 goto Exit;
7418 }
7419
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007420 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007421 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007422 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007423 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007424 lStatus = BAD_VALUE;
7425 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007426 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007427 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007428 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007429 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007430 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007431 }
7432 }
7433
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 {
7435 Mutex::Autolock _l(mLock);
7436
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437
7438 if (!EffectIsNullUuid(&pDesc->uuid)) {
7439 // if uuid is specified, request effect descriptor
7440 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7441 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007442 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 goto Exit;
7444 }
7445 } else {
7446 // if uuid is not specified, look for an available implementation
7447 // of the required type in effect factory
7448 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007449 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 lStatus = BAD_VALUE;
7451 goto Exit;
7452 }
7453 uint32_t numEffects = 0;
7454 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007455 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 bool found = false;
7457
7458 lStatus = EffectQueryNumberEffects(&numEffects);
7459 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 goto Exit;
7462 }
7463 for (uint32_t i = 0; i < numEffects; i++) {
7464 lStatus = EffectQueryEffect(i, &desc);
7465 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007466 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007467 continue;
7468 }
7469 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7470 // If matching type found save effect descriptor. If the session is
7471 // 0 and the effect is not auxiliary, continue enumeration in case
7472 // an auxiliary version of this effect type is available
7473 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007474 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007475 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007476 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7477 break;
7478 }
7479 }
7480 }
7481 if (!found) {
7482 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007483 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484 goto Exit;
7485 }
7486 // For same effect type, chose auxiliary version over insert version if
7487 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007488 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007490 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491 }
7492 }
7493
7494 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007495 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7497 lStatus = INVALID_OPERATION;
7498 goto Exit;
7499 }
7500
Eric Laurent59255e42011-07-27 19:49:51 -07007501 // check recording permission for visualizer
7502 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7503 !recordingAllowed()) {
7504 lStatus = PERMISSION_DENIED;
7505 goto Exit;
7506 }
7507
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007509 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510
7511 // If output is not specified try to find a matching audio session ID in one of the
7512 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007513 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7514 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007515 // Note: io is never 0 when creating an effect on an input
7516 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007517 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007518 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7519 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007520 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007521 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007522 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007524 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007525 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7526 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7527 io = mRecordThreads.keyAt(i);
7528 break;
7529 }
7530 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007531 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007532 // If no output thread contains the requested session ID, default to
7533 // first output. The effect chain will be moved to the correct output
7534 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007535 if (io == 0 && mPlaybackThreads.size()) {
7536 io = mPlaybackThreads.keyAt(0);
7537 }
Steve Block3856b092011-10-20 11:56:00 +01007538 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007539 }
7540 ThreadBase *thread = checkRecordThread_l(io);
7541 if (thread == NULL) {
7542 thread = checkPlaybackThread_l(io);
7543 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007544 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007545 lStatus = BAD_VALUE;
7546 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007549
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007550 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007552 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007553 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7554 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 if (handle != 0 && id != NULL) {
7556 *id = handle->id();
7557 }
7558 }
7559
7560Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007561 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562 *status = lStatus;
7563 }
7564 return handle;
7565}
7566
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007567status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7568 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007569{
Steve Block3856b092011-10-20 11:56:00 +01007570 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007571 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007572 Mutex::Autolock _l(mLock);
7573 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007574 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007575 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576 }
Eric Laurentde070132010-07-13 04:45:46 -07007577 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7578 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007579 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007580 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581 }
Eric Laurentde070132010-07-13 04:45:46 -07007582 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7583 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007584 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007585 return BAD_VALUE;
7586 }
7587
7588 Mutex::Autolock _dl(dstThread->mLock);
7589 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007590 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007591
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 return NO_ERROR;
7593}
7594
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007595// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007596status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007597 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007598 AudioFlinger::PlaybackThread *dstThread,
7599 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007600{
Steve Block3856b092011-10-20 11:56:00 +01007601 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007602 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007603
Eric Laurent59255e42011-07-27 19:49:51 -07007604 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007605 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007606 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007607 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007608 return INVALID_OPERATION;
7609 }
7610
Eric Laurent39e94f82010-07-28 01:32:47 -07007611 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007612 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007613 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007614 // removed.
7615 srcThread->removeEffectChain_l(chain);
7616
7617 // transfer all effects one by one so that new effect chain is created on new thread with
7618 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007619 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007620 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007621 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007622 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7623 while (effect != 0) {
7624 srcThread->removeEffect_l(effect);
7625 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007626 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7627 if (effect->state() == EffectModule::ACTIVE ||
7628 effect->state() == EffectModule::STOPPING) {
7629 effect->start();
7630 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007631 // if the move request is not received from audio policy manager, the effect must be
7632 // re-registered with the new strategy and output
7633 if (dstChain == 0) {
7634 dstChain = effect->chain().promote();
7635 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007636 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007637 srcThread->addEffect_l(effect);
7638 return NO_INIT;
7639 }
7640 strategy = dstChain->strategy();
7641 }
7642 if (reRegister) {
7643 AudioSystem::unregisterEffect(effect->id());
7644 AudioSystem::registerEffect(&effect->desc(),
7645 dstOutput,
7646 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007647 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007648 effect->id());
7649 }
Eric Laurentde070132010-07-13 04:45:46 -07007650 effect = chain->getEffectFromId_l(0);
7651 }
7652
7653 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007654}
7655
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007656
Mathias Agopian65ab4712010-07-14 17:59:35 -07007657// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007658sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007659 const sp<AudioFlinger::Client>& client,
7660 const sp<IEffectClient>& effectClient,
7661 int32_t priority,
7662 int sessionId,
7663 effect_descriptor_t *desc,
7664 int *enabled,
7665 status_t *status
7666 )
7667{
7668 sp<EffectModule> effect;
7669 sp<EffectHandle> handle;
7670 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007672 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673 bool effectCreated = false;
7674 bool effectRegistered = false;
7675
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007676 lStatus = initCheck();
7677 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007678 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 goto Exit;
7680 }
7681
7682 // Do not allow effects with session ID 0 on direct output or duplicating threads
7683 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007684 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007685 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007686 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 lStatus = BAD_VALUE;
7688 goto Exit;
7689 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007690 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007691 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007692 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007693 desc->name, desc->flags, mType);
7694 lStatus = BAD_VALUE;
7695 goto Exit;
7696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697
Steve Block3856b092011-10-20 11:56:00 +01007698 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699
7700 { // scope for mLock
7701 Mutex::Autolock _l(mLock);
7702
7703 // check for existing effect chain with the requested audio session
7704 chain = getEffectChain_l(sessionId);
7705 if (chain == 0) {
7706 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007707 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 chain = new EffectChain(this, sessionId);
7709 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007710 chain->setStrategy(getStrategyForSession_l(sessionId));
7711 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007713 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 }
7715
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007716 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007717
7718 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007721 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007722 if (lStatus != NO_ERROR) {
7723 goto Exit;
7724 }
7725 effectRegistered = true;
7726 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007727 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 lStatus = effect->status();
7729 if (lStatus != NO_ERROR) {
7730 goto Exit;
7731 }
Eric Laurentcab11242010-07-15 12:50:15 -07007732 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 if (lStatus != NO_ERROR) {
7734 goto Exit;
7735 }
7736 effectCreated = true;
7737
7738 effect->setDevice(mDevice);
7739 effect->setMode(mAudioFlinger->getMode());
7740 }
7741 // create effect handle and connect it to effect module
7742 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007743 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007744 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007745 *enabled = (int)effect->isEnabled();
7746 }
7747 }
7748
7749Exit:
7750 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007751 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007753 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 }
7755 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007756 AudioSystem::unregisterEffect(effect->id());
7757 }
7758 if (chainCreated) {
7759 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 }
7761 handle.clear();
7762 }
7763
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007764 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765 *status = lStatus;
7766 }
7767 return handle;
7768}
7769
Eric Laurent717e1282012-06-29 16:36:52 -07007770sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7771{
7772 Mutex::Autolock _l(mLock);
7773 return getEffect_l(sessionId, effectId);
7774}
7775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007776sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7777{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007778 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007779 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007780}
7781
Eric Laurentde070132010-07-13 04:45:46 -07007782// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7783// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007784status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007785{
7786 // check for existing effect chain with the requested audio session
7787 int sessionId = effect->sessionId();
7788 sp<EffectChain> chain = getEffectChain_l(sessionId);
7789 bool chainCreated = false;
7790
7791 if (chain == 0) {
7792 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007793 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007794 chain = new EffectChain(this, sessionId);
7795 addEffectChain_l(chain);
7796 chain->setStrategy(getStrategyForSession_l(sessionId));
7797 chainCreated = true;
7798 }
Steve Block3856b092011-10-20 11:56:00 +01007799 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007800
7801 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007802 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007803 this, effect->desc().name, chain.get());
7804 return BAD_VALUE;
7805 }
7806
7807 status_t status = chain->addEffect_l(effect);
7808 if (status != NO_ERROR) {
7809 if (chainCreated) {
7810 removeEffectChain_l(chain);
7811 }
7812 return status;
7813 }
7814
7815 effect->setDevice(mDevice);
7816 effect->setMode(mAudioFlinger->getMode());
7817 return NO_ERROR;
7818}
7819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007820void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007821
Steve Block3856b092011-10-20 11:56:00 +01007822 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007824 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7825 detachAuxEffect_l(effect->id());
7826 }
7827
7828 sp<EffectChain> chain = effect->chain().promote();
7829 if (chain != 0) {
7830 // remove effect chain if removing last effect
7831 if (chain->removeEffect_l(effect) == 0) {
7832 removeEffectChain_l(chain);
7833 }
7834 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007835 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007836 }
7837}
7838
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007839void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007840 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007841{
7842 effectChains = mEffectChains;
7843 for (size_t i = 0; i < mEffectChains.size(); i++) {
7844 mEffectChains[i]->lock();
7845 }
7846}
7847
7848void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007849 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007850{
7851 for (size_t i = 0; i < effectChains.size(); i++) {
7852 effectChains[i]->unlock();
7853 }
7854}
7855
7856sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7857{
7858 Mutex::Autolock _l(mLock);
7859 return getEffectChain_l(sessionId);
7860}
7861
Glenn Kasten106e8a42012-08-02 13:37:12 -07007862sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007863{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007864 size_t size = mEffectChains.size();
7865 for (size_t i = 0; i < size; i++) {
7866 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007867 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007868 }
7869 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007870 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007871}
7872
Glenn Kastenf78aee72012-01-04 11:00:47 -08007873void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007874{
7875 Mutex::Autolock _l(mLock);
7876 size_t size = mEffectChains.size();
7877 for (size_t i = 0; i < size; i++) {
7878 mEffectChains[i]->setMode_l(mode);
7879 }
7880}
7881
7882void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007883 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007884 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007885
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007887 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007888 // delete the effect module if removing last handle on it
7889 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007890 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007891 removeEffect_l(effect);
7892 AudioSystem::unregisterEffect(effect->id());
7893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 }
7895}
7896
7897status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7898{
7899 int session = chain->sessionId();
7900 int16_t *buffer = mMixBuffer;
7901 bool ownsBuffer = false;
7902
Steve Block3856b092011-10-20 11:56:00 +01007903 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 if (session > 0) {
7905 // Only one effect chain can be present in direct output thread and it uses
7906 // the mix buffer as input
7907 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007908 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 buffer = new int16_t[numSamples];
7910 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007911 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912 ownsBuffer = true;
7913 }
7914
7915 // Attach all tracks with same session ID to this chain.
7916 for (size_t i = 0; i < mTracks.size(); ++i) {
7917 sp<Track> track = mTracks[i];
7918 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007919 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007920 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007921 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 }
7923 }
7924
7925 // indicate all active tracks in the chain
7926 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7927 sp<Track> track = mActiveTracks[i].promote();
7928 if (track == 0) continue;
7929 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007930 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007931 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 }
7933 }
7934 }
7935
7936 chain->setInBuffer(buffer, ownsBuffer);
7937 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007938 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007939 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007940 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7941 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007943 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7944 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007945 // Effect chain for other sessions are inserted at beginning of effect
7946 // chains list to be processed before output mix effects. Relative order between other
7947 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948 size_t size = mEffectChains.size();
7949 size_t i = 0;
7950 for (i = 0; i < size; i++) {
7951 if (mEffectChains[i]->sessionId() < session) break;
7952 }
7953 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007954 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955
7956 return NO_ERROR;
7957}
7958
7959size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7960{
7961 int session = chain->sessionId();
7962
Steve Block3856b092011-10-20 11:56:00 +01007963 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964
7965 for (size_t i = 0; i < mEffectChains.size(); i++) {
7966 if (chain == mEffectChains[i]) {
7967 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007968 // detach all active tracks from the chain
7969 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7970 sp<Track> track = mActiveTracks[i].promote();
7971 if (track == 0) continue;
7972 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007973 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007974 chain.get(), session);
7975 chain->decActiveTrackCnt();
7976 }
7977 }
7978
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979 // detach all tracks with same session ID from this chain
7980 for (size_t i = 0; i < mTracks.size(); ++i) {
7981 sp<Track> track = mTracks[i];
7982 if (session == track->sessionId()) {
7983 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007984 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985 }
7986 }
Eric Laurentde070132010-07-13 04:45:46 -07007987 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 }
7989 }
7990 return mEffectChains.size();
7991}
7992
Eric Laurentde070132010-07-13 04:45:46 -07007993status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7994 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007995{
7996 Mutex::Autolock _l(mLock);
7997 return attachAuxEffect_l(track, EffectId);
7998}
7999
Eric Laurentde070132010-07-13 04:45:46 -07008000status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8001 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008002{
8003 status_t status = NO_ERROR;
8004
8005 if (EffectId == 0) {
8006 track->setAuxBuffer(0, NULL);
8007 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008008 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8009 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008010 if (effect != 0) {
8011 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8012 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8013 } else {
8014 status = INVALID_OPERATION;
8015 }
8016 } else {
8017 status = BAD_VALUE;
8018 }
8019 }
8020 return status;
8021}
8022
8023void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8024{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008025 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 sp<Track> track = mTracks[i];
8027 if (track->auxEffectId() == effectId) {
8028 attachAuxEffect_l(track, 0);
8029 }
8030 }
8031}
8032
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008033status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8034{
8035 // only one chain per input thread
8036 if (mEffectChains.size() != 0) {
8037 return INVALID_OPERATION;
8038 }
Steve Block3856b092011-10-20 11:56:00 +01008039 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008040
8041 chain->setInBuffer(NULL);
8042 chain->setOutBuffer(NULL);
8043
Eric Laurent59255e42011-07-27 19:49:51 -07008044 checkSuspendOnAddEffectChain_l(chain);
8045
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008046 mEffectChains.add(chain);
8047
8048 return NO_ERROR;
8049}
8050
8051size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8052{
Steve Block3856b092011-10-20 11:56:00 +01008053 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008054 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008055 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8056 chain.get(), mEffectChains.size(), this);
8057 if (mEffectChains.size() == 1) {
8058 mEffectChains.removeAt(0);
8059 }
8060 return 0;
8061}
8062
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063// ----------------------------------------------------------------------------
8064// EffectModule implementation
8065// ----------------------------------------------------------------------------
8066
8067#undef LOG_TAG
8068#define LOG_TAG "AudioFlinger::EffectModule"
8069
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008070AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008071 const wp<AudioFlinger::EffectChain>& chain,
8072 effect_descriptor_t *desc,
8073 int id,
8074 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008075 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8076 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008077 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008078 // mConfig is set by configure() and not used before then
8079 mEffectInterface(NULL),
8080 mStatus(NO_INIT), mState(IDLE),
8081 // mMaxDisableWaitCnt is set by configure() and not used before then
8082 // mDisableWaitCnt is set by process() and updateState() and not used before then
8083 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084{
Steve Block3856b092011-10-20 11:56:00 +01008085 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087
8088 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008089 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008090
8091 if (mStatus != NO_ERROR) {
8092 return;
8093 }
8094 lStatus = init();
8095 if (lStatus < 0) {
8096 mStatus = lStatus;
8097 goto Error;
8098 }
8099
Steve Block3856b092011-10-20 11:56:00 +01008100 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101 return;
8102Error:
8103 EffectRelease(mEffectInterface);
8104 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008105 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106}
8107
8108AudioFlinger::EffectModule::~EffectModule()
8109{
Steve Block3856b092011-10-20 11:56:00 +01008110 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008112 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8113 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8114 sp<ThreadBase> thread = mThread.promote();
8115 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008116 audio_stream_t *stream = thread->stream();
8117 if (stream != NULL) {
8118 stream->remove_audio_effect(stream, mEffectInterface);
8119 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008120 }
8121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008122 // release effect engine
8123 EffectRelease(mEffectInterface);
8124 }
8125}
8126
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008127status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128{
8129 status_t status;
8130
8131 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 int priority = handle->priority();
8133 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008134 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 size_t i;
8136 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008137 EffectHandle *h = mHandles[i];
8138 if (h == NULL || h->destroyed_l()) continue;
8139 // first non destroyed handle is considered in control
8140 if (controlHandle == NULL)
8141 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008142 if (h->priority() <= priority) break;
8143 }
8144 // if inserted in first place, move effect control from previous owner to this handle
8145 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008146 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008147 if (controlHandle != NULL) {
8148 enabled = controlHandle->enabled();
8149 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150 }
Eric Laurent59255e42011-07-27 19:49:51 -07008151 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152 status = NO_ERROR;
8153 } else {
8154 status = ALREADY_EXISTS;
8155 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008156 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 mHandles.insertAt(handle, i);
8158 return status;
8159}
8160
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008161size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162{
8163 Mutex::Autolock _l(mLock);
8164 size_t size = mHandles.size();
8165 size_t i;
8166 for (i = 0; i < size; i++) {
8167 if (mHandles[i] == handle) break;
8168 }
8169 if (i == size) {
8170 return size;
8171 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008172 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008173
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008175 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008176 if (i == 0) {
8177 EffectHandle *h = controlHandle_l();
8178 if (h != NULL) {
8179 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 }
8181 }
8182
Eric Laurentec437d82011-07-26 20:54:46 -07008183 // Prevent calls to process() and other functions on effect interface from now on.
8184 // The effect engine will be released by the destructor when the last strong reference on
8185 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008186 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008187 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008188 }
8189
Eric Laurente65c8912012-07-20 15:57:23 -07008190 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191}
8192
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008193// must be called with EffectModule::mLock held
8194AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008195{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008196 // the first valid handle in the list has control over the module
8197 for (size_t i = 0; i < mHandles.size(); i++) {
8198 EffectHandle *h = mHandles[i];
8199 if (h != NULL && !h->destroyed_l()) {
8200 return h;
8201 }
8202 }
8203
8204 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008205}
8206
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008207size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008209 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210 // keep a strong reference on this EffectModule to avoid calling the
8211 // destructor before we exit
8212 sp<EffectModule> keep(this);
8213 {
8214 sp<ThreadBase> thread = mThread.promote();
8215 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008216 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 }
8218 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008219 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220}
8221
8222void AudioFlinger::EffectModule::updateState() {
8223 Mutex::Autolock _l(mLock);
8224
8225 switch (mState) {
8226 case RESTART:
8227 reset_l();
8228 // FALL THROUGH
8229
8230 case STARTING:
8231 // clear auxiliary effect input buffer for next accumulation
8232 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8233 memset(mConfig.inputCfg.buffer.raw,
8234 0,
8235 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8236 }
8237 start_l();
8238 mState = ACTIVE;
8239 break;
8240 case STOPPING:
8241 stop_l();
8242 mDisableWaitCnt = mMaxDisableWaitCnt;
8243 mState = STOPPED;
8244 break;
8245 case STOPPED:
8246 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8247 // turn off sequence.
8248 if (--mDisableWaitCnt == 0) {
8249 reset_l();
8250 mState = IDLE;
8251 }
8252 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008253 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008254 break;
8255 }
8256}
8257
8258void AudioFlinger::EffectModule::process()
8259{
8260 Mutex::Autolock _l(mLock);
8261
Eric Laurentec437d82011-07-26 20:54:46 -07008262 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263 mConfig.inputCfg.buffer.raw == NULL ||
8264 mConfig.outputCfg.buffer.raw == NULL) {
8265 return;
8266 }
8267
Eric Laurent8f45bd72010-08-31 13:50:07 -07008268 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008269 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8270 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008271 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008273 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 }
8275
8276 // do the actual processing in the effect engine
8277 int ret = (*mEffectInterface)->process(mEffectInterface,
8278 &mConfig.inputCfg.buffer,
8279 &mConfig.outputCfg.buffer);
8280
8281 // force transition to IDLE state when engine is ready
8282 if (mState == STOPPED && ret == -ENODATA) {
8283 mDisableWaitCnt = 1;
8284 }
8285
8286 // clear auxiliary effect input buffer for next accumulation
8287 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008288 memset(mConfig.inputCfg.buffer.raw, 0,
8289 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008290 }
8291 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008292 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8293 // If an insert effect is idle and input buffer is different from output buffer,
8294 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008296 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008297 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8298 int16_t *in = mConfig.inputCfg.buffer.s16;
8299 int16_t *out = mConfig.outputCfg.buffer.s16;
8300 for (size_t i = 0; i < frameCnt; i++) {
8301 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008303 }
8304 }
8305}
8306
8307void AudioFlinger::EffectModule::reset_l()
8308{
8309 if (mEffectInterface == NULL) {
8310 return;
8311 }
8312 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8313}
8314
8315status_t AudioFlinger::EffectModule::configure()
8316{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008317 if (mEffectInterface == NULL) {
8318 return NO_INIT;
8319 }
8320
8321 sp<ThreadBase> thread = mThread.promote();
8322 if (thread == 0) {
8323 return DEAD_OBJECT;
8324 }
8325
8326 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008327 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008328
8329 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008330 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008332 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008333 }
Glenn Kasten254af182012-07-03 14:59:05 -07008334 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008335 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8336 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008337 mConfig.inputCfg.samplingRate = thread->sampleRate();
8338 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8339 mConfig.inputCfg.bufferProvider.cookie = NULL;
8340 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8341 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8342 mConfig.outputCfg.bufferProvider.cookie = NULL;
8343 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8344 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8345 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8346 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008347 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008348 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008349 // - in other sessions:
8350 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8351 // other effect: overwrites output buffer: input buffer == output buffer
8352 // Auxiliary effect:
8353 // accumulates in output buffer: input buffer != output buffer
8354 // Therefore: accumulate <=> input buffer != output buffer
8355 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8356 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8357 } else {
8358 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8359 }
8360 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8361 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8362 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8363 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8364
Steve Block3856b092011-10-20 11:56:00 +01008365 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008366 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8367
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008369 uint32_t size = sizeof(int);
8370 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008371 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008372 sizeof(effect_config_t),
8373 &mConfig,
8374 &size,
8375 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 if (status == 0) {
8377 status = cmdStatus;
8378 }
8379
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008380 if (status == 0 &&
8381 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8382 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8383 effect_param_t *p = (effect_param_t *)buf32;
8384
8385 p->psize = sizeof(uint32_t);
8386 p->vsize = sizeof(uint32_t);
8387 size = sizeof(int);
8388 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8389
8390 uint32_t latency = 0;
8391 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8392 if (pbt != NULL) {
8393 latency = pbt->latency_l();
8394 }
8395
8396 *((int32_t *)p->data + 1)= latency;
8397 (*mEffectInterface)->command(mEffectInterface,
8398 EFFECT_CMD_SET_PARAM,
8399 sizeof(effect_param_t) + 8,
8400 &buf32,
8401 &size,
8402 &cmdStatus);
8403 }
8404
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8406 (1000 * mConfig.outputCfg.buffer.frameCount);
8407
8408 return status;
8409}
8410
8411status_t AudioFlinger::EffectModule::init()
8412{
8413 Mutex::Autolock _l(mLock);
8414 if (mEffectInterface == NULL) {
8415 return NO_INIT;
8416 }
8417 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008418 uint32_t size = sizeof(status_t);
8419 status_t status = (*mEffectInterface)->command(mEffectInterface,
8420 EFFECT_CMD_INIT,
8421 0,
8422 NULL,
8423 &size,
8424 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425 if (status == 0) {
8426 status = cmdStatus;
8427 }
8428 return status;
8429}
8430
Eric Laurentec35a142011-10-05 17:42:25 -07008431status_t AudioFlinger::EffectModule::start()
8432{
8433 Mutex::Autolock _l(mLock);
8434 return start_l();
8435}
8436
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437status_t AudioFlinger::EffectModule::start_l()
8438{
8439 if (mEffectInterface == NULL) {
8440 return NO_INIT;
8441 }
8442 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008443 uint32_t size = sizeof(status_t);
8444 status_t status = (*mEffectInterface)->command(mEffectInterface,
8445 EFFECT_CMD_ENABLE,
8446 0,
8447 NULL,
8448 &size,
8449 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008450 if (status == 0) {
8451 status = cmdStatus;
8452 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008453 if (status == 0 &&
8454 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8455 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8456 sp<ThreadBase> thread = mThread.promote();
8457 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008458 audio_stream_t *stream = thread->stream();
8459 if (stream != NULL) {
8460 stream->add_audio_effect(stream, mEffectInterface);
8461 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008462 }
8463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464 return status;
8465}
8466
Eric Laurentec437d82011-07-26 20:54:46 -07008467status_t AudioFlinger::EffectModule::stop()
8468{
8469 Mutex::Autolock _l(mLock);
8470 return stop_l();
8471}
8472
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473status_t AudioFlinger::EffectModule::stop_l()
8474{
8475 if (mEffectInterface == NULL) {
8476 return NO_INIT;
8477 }
8478 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008479 uint32_t size = sizeof(status_t);
8480 status_t status = (*mEffectInterface)->command(mEffectInterface,
8481 EFFECT_CMD_DISABLE,
8482 0,
8483 NULL,
8484 &size,
8485 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008486 if (status == 0) {
8487 status = cmdStatus;
8488 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008489 if (status == 0 &&
8490 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8491 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8492 sp<ThreadBase> thread = mThread.promote();
8493 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008494 audio_stream_t *stream = thread->stream();
8495 if (stream != NULL) {
8496 stream->remove_audio_effect(stream, mEffectInterface);
8497 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008498 }
8499 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500 return status;
8501}
8502
Eric Laurent25f43952010-07-28 05:40:18 -07008503status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8504 uint32_t cmdSize,
8505 void *pCmdData,
8506 uint32_t *replySize,
8507 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008508{
8509 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008510// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511
Eric Laurentec437d82011-07-26 20:54:46 -07008512 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 return NO_INIT;
8514 }
Eric Laurent25f43952010-07-28 05:40:18 -07008515 status_t status = (*mEffectInterface)->command(mEffectInterface,
8516 cmdCode,
8517 cmdSize,
8518 pCmdData,
8519 replySize,
8520 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008522 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008523 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008524 EffectHandle *h = mHandles[i];
8525 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8527 }
8528 }
8529 }
8530 return status;
8531}
8532
8533status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8534{
8535 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008536 return setEnabled_l(enabled);
8537}
8538
8539// must be called with EffectModule::mLock held
8540status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8541{
8542
Steve Block3856b092011-10-20 11:56:00 +01008543 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008544
8545 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008546 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8547 if (enabled && status != NO_ERROR) {
8548 return status;
8549 }
8550
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 switch (mState) {
8552 // going from disabled to enabled
8553 case IDLE:
8554 mState = STARTING;
8555 break;
8556 case STOPPED:
8557 mState = RESTART;
8558 break;
8559 case STOPPING:
8560 mState = ACTIVE;
8561 break;
8562
8563 // going from enabled to disabled
8564 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008565 mState = STOPPED;
8566 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008567 case STARTING:
8568 mState = IDLE;
8569 break;
8570 case ACTIVE:
8571 mState = STOPPING;
8572 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008573 case DESTROYED:
8574 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 }
8576 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008577 EffectHandle *h = mHandles[i];
8578 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008579 h->setEnabled(enabled);
8580 }
8581 }
8582 }
8583 return NO_ERROR;
8584}
8585
Glenn Kastenc59c0042012-02-02 14:06:11 -08008586bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587{
8588 switch (mState) {
8589 case RESTART:
8590 case STARTING:
8591 case ACTIVE:
8592 return true;
8593 case IDLE:
8594 case STOPPING:
8595 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008596 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597 default:
8598 return false;
8599 }
8600}
8601
Glenn Kastenc59c0042012-02-02 14:06:11 -08008602bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008603{
8604 switch (mState) {
8605 case RESTART:
8606 case ACTIVE:
8607 case STOPPING:
8608 case STOPPED:
8609 return true;
8610 case IDLE:
8611 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008612 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008613 default:
8614 return false;
8615 }
8616}
8617
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8619{
8620 Mutex::Autolock _l(mLock);
8621 status_t status = NO_ERROR;
8622
8623 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8624 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008625 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008626 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8627 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008628 status_t cmdStatus;
8629 uint32_t volume[2];
8630 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008631 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632 volume[0] = *left;
8633 volume[1] = *right;
8634 if (controller) {
8635 pVolume = volume;
8636 }
Eric Laurent25f43952010-07-28 05:40:18 -07008637 status = (*mEffectInterface)->command(mEffectInterface,
8638 EFFECT_CMD_SET_VOLUME,
8639 size,
8640 volume,
8641 &size,
8642 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008643 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8644 *left = volume[0];
8645 *right = volume[1];
8646 }
8647 }
8648 return status;
8649}
8650
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008651status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652{
8653 Mutex::Autolock _l(mLock);
8654 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008655 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8656 // audio pre processing modules on RecordThread can receive both output and
8657 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008658 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008659 if (dev) {
8660 status_t cmdStatus;
8661 uint32_t size = sizeof(status_t);
8662
8663 status = (*mEffectInterface)->command(mEffectInterface,
8664 EFFECT_CMD_SET_DEVICE,
8665 sizeof(uint32_t),
8666 &dev,
8667 &size,
8668 &cmdStatus);
8669 if (status == NO_ERROR) {
8670 status = cmdStatus;
8671 }
8672 }
8673 dev = device & AUDIO_DEVICE_IN_ALL;
8674 if (dev) {
8675 status_t cmdStatus;
8676 uint32_t size = sizeof(status_t);
8677
8678 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8679 EFFECT_CMD_SET_INPUT_DEVICE,
8680 sizeof(uint32_t),
8681 &dev,
8682 &size,
8683 &cmdStatus);
8684 if (status2 == NO_ERROR) {
8685 status2 = cmdStatus;
8686 }
8687 if (status == NO_ERROR) {
8688 status = status2;
8689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 }
8691 }
8692 return status;
8693}
8694
Glenn Kastenf78aee72012-01-04 11:00:47 -08008695status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696{
8697 Mutex::Autolock _l(mLock);
8698 status_t status = NO_ERROR;
8699 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008701 uint32_t size = sizeof(status_t);
8702 status = (*mEffectInterface)->command(mEffectInterface,
8703 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008704 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008705 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008706 &size,
8707 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708 if (status == NO_ERROR) {
8709 status = cmdStatus;
8710 }
8711 }
8712 return status;
8713}
8714
Eric Laurent59255e42011-07-27 19:49:51 -07008715void AudioFlinger::EffectModule::setSuspended(bool suspended)
8716{
8717 Mutex::Autolock _l(mLock);
8718 mSuspended = suspended;
8719}
Glenn Kastena3a85482012-01-04 11:01:11 -08008720
8721bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008722{
8723 Mutex::Autolock _l(mLock);
8724 return mSuspended;
8725}
8726
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008727bool AudioFlinger::EffectModule::purgeHandles()
8728{
8729 bool enabled = false;
8730 Mutex::Autolock _l(mLock);
8731 for (size_t i = 0; i < mHandles.size(); i++) {
8732 EffectHandle *handle = mHandles[i];
8733 if (handle != NULL && !handle->destroyed_l()) {
8734 handle->effect().clear();
8735 if (handle->hasControl()) {
8736 enabled = handle->enabled();
8737 }
8738 }
8739 }
8740 return enabled;
8741}
8742
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008743void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744{
8745 const size_t SIZE = 256;
8746 char buffer[SIZE];
8747 String8 result;
8748
8749 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8750 result.append(buffer);
8751
8752 bool locked = tryLock(mLock);
8753 // failed to lock - AudioFlinger is probably deadlocked
8754 if (!locked) {
8755 result.append("\t\tCould not lock Fx mutex:\n");
8756 }
8757
8758 result.append("\t\tSession Status State Engine:\n");
8759 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8760 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8761 result.append(buffer);
8762
8763 result.append("\t\tDescriptor:\n");
8764 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8765 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8766 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8767 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8768 result.append(buffer);
8769 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8770 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8771 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8772 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8773 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008774 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008775 mDescriptor.apiVersion,
8776 mDescriptor.flags);
8777 result.append(buffer);
8778 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8779 mDescriptor.name);
8780 result.append(buffer);
8781 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8782 mDescriptor.implementor);
8783 result.append(buffer);
8784
8785 result.append("\t\t- Input configuration:\n");
8786 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8787 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8788 (uint32_t)mConfig.inputCfg.buffer.raw,
8789 mConfig.inputCfg.buffer.frameCount,
8790 mConfig.inputCfg.samplingRate,
8791 mConfig.inputCfg.channels,
8792 mConfig.inputCfg.format);
8793 result.append(buffer);
8794
8795 result.append("\t\t- Output configuration:\n");
8796 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8797 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8798 (uint32_t)mConfig.outputCfg.buffer.raw,
8799 mConfig.outputCfg.buffer.frameCount,
8800 mConfig.outputCfg.samplingRate,
8801 mConfig.outputCfg.channels,
8802 mConfig.outputCfg.format);
8803 result.append(buffer);
8804
8805 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8806 result.append(buffer);
8807 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8808 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008809 EffectHandle *handle = mHandles[i];
8810 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811 handle->dump(buffer, SIZE);
8812 result.append(buffer);
8813 }
8814 }
8815
8816 result.append("\n");
8817
8818 write(fd, result.string(), result.length());
8819
8820 if (locked) {
8821 mLock.unlock();
8822 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008823}
8824
8825// ----------------------------------------------------------------------------
8826// EffectHandle implementation
8827// ----------------------------------------------------------------------------
8828
8829#undef LOG_TAG
8830#define LOG_TAG "AudioFlinger::EffectHandle"
8831
8832AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8833 const sp<AudioFlinger::Client>& client,
8834 const sp<IEffectClient>& effectClient,
8835 int32_t priority)
8836 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008837 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008838 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839{
Steve Block3856b092011-10-20 11:56:00 +01008840 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008841
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008842 if (client == 0) {
8843 return;
8844 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008845 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8846 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8847 if (mCblkMemory != 0) {
8848 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8849
Glenn Kastena0d68332012-01-27 16:47:15 -08008850 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008851 new(mCblk) effect_param_cblk_t();
8852 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008853 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008854 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008855 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856 return;
8857 }
8858}
8859
8860AudioFlinger::EffectHandle::~EffectHandle()
8861{
Steve Block3856b092011-10-20 11:56:00 +01008862 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008863
8864 if (mEffect == 0) {
8865 mDestroyed = true;
8866 return;
8867 }
8868 mEffect->lock();
8869 mDestroyed = true;
8870 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008871 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008872}
8873
8874status_t AudioFlinger::EffectHandle::enable()
8875{
Steve Block3856b092011-10-20 11:56:00 +01008876 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877 if (!mHasControl) return INVALID_OPERATION;
8878 if (mEffect == 0) return DEAD_OBJECT;
8879
Eric Laurentdb7c0792011-08-10 10:37:50 -07008880 if (mEnabled) {
8881 return NO_ERROR;
8882 }
8883
Eric Laurent59255e42011-07-27 19:49:51 -07008884 mEnabled = true;
8885
8886 sp<ThreadBase> thread = mEffect->thread().promote();
8887 if (thread != 0) {
8888 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8889 }
8890
8891 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8892 if (mEffect->suspended()) {
8893 return NO_ERROR;
8894 }
8895
Eric Laurentdb7c0792011-08-10 10:37:50 -07008896 status_t status = mEffect->setEnabled(true);
8897 if (status != NO_ERROR) {
8898 if (thread != 0) {
8899 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8900 }
8901 mEnabled = false;
8902 }
8903 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904}
8905
8906status_t AudioFlinger::EffectHandle::disable()
8907{
Steve Block3856b092011-10-20 11:56:00 +01008908 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008909 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008910 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911
Eric Laurentdb7c0792011-08-10 10:37:50 -07008912 if (!mEnabled) {
8913 return NO_ERROR;
8914 }
Eric Laurent59255e42011-07-27 19:49:51 -07008915 mEnabled = false;
8916
8917 if (mEffect->suspended()) {
8918 return NO_ERROR;
8919 }
8920
8921 status_t status = mEffect->setEnabled(false);
8922
8923 sp<ThreadBase> thread = mEffect->thread().promote();
8924 if (thread != 0) {
8925 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8926 }
8927
8928 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929}
8930
8931void AudioFlinger::EffectHandle::disconnect()
8932{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008933 disconnect(true);
8934}
8935
Glenn Kasten58123c32012-02-03 10:32:24 -08008936void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008937{
Glenn Kasten58123c32012-02-03 10:32:24 -08008938 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 if (mEffect == 0) {
8940 return;
8941 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008942 // restore suspended effects if the disconnected handle was enabled and the last one.
8943 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008944 sp<ThreadBase> thread = mEffect->thread().promote();
8945 if (thread != 0) {
8946 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8947 }
Eric Laurent59255e42011-07-27 19:49:51 -07008948 }
8949
Mathias Agopian65ab4712010-07-14 17:59:35 -07008950 // release sp on module => module destructor can be called now
8951 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008953 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008954 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008955 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8956 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008957 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008958 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8960 mClient.clear();
8961 }
8962}
8963
Eric Laurent25f43952010-07-28 05:40:18 -07008964status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8965 uint32_t cmdSize,
8966 void *pCmdData,
8967 uint32_t *replySize,
8968 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969{
Steve Block3856b092011-10-20 11:56:00 +01008970// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008971// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972
8973 // only get parameter command is permitted for applications not controlling the effect
8974 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8975 return INVALID_OPERATION;
8976 }
8977 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008978 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008979
8980 // handle commands that are not forwarded transparently to effect engine
8981 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8982 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8983 // no risk to block the whole media server process or mixer threads is we are stuck here
8984 Mutex::Autolock _l(mCblk->lock);
8985 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8986 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8987 mCblk->serverIndex = 0;
8988 mCblk->clientIndex = 0;
8989 return BAD_VALUE;
8990 }
8991 status_t status = NO_ERROR;
8992 while (mCblk->serverIndex < mCblk->clientIndex) {
8993 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008994 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995 int *p = (int *)(mBuffer + mCblk->serverIndex);
8996 int size = *p++;
8997 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008998 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008999 break;
9000 }
9001 effect_param_t *param = (effect_param_t *)p;
9002 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009003 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009004 mCblk->serverIndex += size;
9005 continue;
9006 }
Eric Laurent25f43952010-07-28 05:40:18 -07009007 uint32_t psize = sizeof(effect_param_t) +
9008 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9009 param->vsize;
9010 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9011 psize,
9012 p,
9013 &rsize,
9014 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009015 // stop at first error encountered
9016 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009018 *(int *)pReplyData = reply;
9019 break;
9020 } else if (reply != NO_ERROR) {
9021 *(int *)pReplyData = reply;
9022 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023 }
9024 mCblk->serverIndex += size;
9025 }
9026 mCblk->serverIndex = 0;
9027 mCblk->clientIndex = 0;
9028 return status;
9029 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009030 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031 return enable();
9032 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009033 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034 return disable();
9035 }
9036
9037 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9038}
9039
Eric Laurent59255e42011-07-27 19:49:51 -07009040void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009041{
Steve Block3856b092011-10-20 11:56:00 +01009042 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009043
9044 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009045 mEnabled = enabled;
9046
Mathias Agopian65ab4712010-07-14 17:59:35 -07009047 if (signal && mEffectClient != 0) {
9048 mEffectClient->controlStatusChanged(hasControl);
9049 }
9050}
9051
Eric Laurent25f43952010-07-28 05:40:18 -07009052void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9053 uint32_t cmdSize,
9054 void *pCmdData,
9055 uint32_t replySize,
9056 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009057{
9058 if (mEffectClient != 0) {
9059 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9060 }
9061}
9062
9063
9064
9065void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9066{
9067 if (mEffectClient != 0) {
9068 mEffectClient->enableStatusChanged(enabled);
9069 }
9070}
9071
9072status_t AudioFlinger::EffectHandle::onTransact(
9073 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9074{
9075 return BnEffect::onTransact(code, data, reply, flags);
9076}
9077
9078
9079void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9080{
Glenn Kastena0d68332012-01-27 16:47:15 -08009081 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009082
9083 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009084 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009085 mPriority,
9086 mHasControl,
9087 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009088 mCblk ? mCblk->clientIndex : 0,
9089 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090 );
9091
9092 if (locked) {
9093 mCblk->lock.unlock();
9094 }
9095}
9096
9097#undef LOG_TAG
9098#define LOG_TAG "AudioFlinger::EffectChain"
9099
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009100AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009102 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009103 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9104 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009105{
Dima Zavinfce7a472011-04-19 22:30:36 -07009106 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009107 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009108 return;
9109 }
9110 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9111 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009112}
9113
9114AudioFlinger::EffectChain::~EffectChain()
9115{
9116 if (mOwnInBuffer) {
9117 delete mInBuffer;
9118 }
9119
9120}
9121
Eric Laurent59255e42011-07-27 19:49:51 -07009122// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009123sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009125 size_t size = mEffects.size();
9126
9127 for (size_t i = 0; i < size; i++) {
9128 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009129 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009130 }
9131 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009132 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009133}
9134
Eric Laurent59255e42011-07-27 19:49:51 -07009135// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009136sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009137{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009138 size_t size = mEffects.size();
9139
9140 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009141 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9142 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009143 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009144 }
9145 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009146 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009147}
9148
Eric Laurent59255e42011-07-27 19:49:51 -07009149// getEffectFromType_l() must be called with ThreadBase::mLock held
9150sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9151 const effect_uuid_t *type)
9152{
Eric Laurent59255e42011-07-27 19:49:51 -07009153 size_t size = mEffects.size();
9154
9155 for (size_t i = 0; i < size; i++) {
9156 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009157 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009158 }
9159 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009160 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009161}
9162
Eric Laurent91b14c42012-05-30 12:30:29 -07009163void AudioFlinger::EffectChain::clearInputBuffer()
9164{
9165 Mutex::Autolock _l(mLock);
9166 sp<ThreadBase> thread = mThread.promote();
9167 if (thread == 0) {
9168 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9169 return;
9170 }
9171 clearInputBuffer_l(thread);
9172}
9173
9174// Must be called with EffectChain::mLock locked
9175void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9176{
9177 size_t numSamples = thread->frameCount() * thread->channelCount();
9178 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9179
9180}
9181
Mathias Agopian65ab4712010-07-14 17:59:35 -07009182// Must be called with EffectChain::mLock locked
9183void AudioFlinger::EffectChain::process_l()
9184{
Eric Laurentdac69112010-09-28 14:09:57 -07009185 sp<ThreadBase> thread = mThread.promote();
9186 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009187 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009188 return;
9189 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009190 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9191 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009192 // always process effects unless no more tracks are on the session and the effect tail
9193 // has been rendered
9194 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009195 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009196 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009197
Eric Laurent544fe9b2011-11-11 15:42:52 -08009198 if (!tracksOnSession && mTailBufferCount == 0) {
9199 doProcess = false;
9200 }
9201
9202 if (activeTrackCnt() == 0) {
9203 // if no track is active and the effect tail has not been rendered,
9204 // the input buffer must be cleared here as the mixer process will not do it
9205 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009206 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009207 if (mTailBufferCount > 0) {
9208 mTailBufferCount--;
9209 }
9210 }
9211 }
Eric Laurentdac69112010-09-28 14:09:57 -07009212 }
9213
Mathias Agopian65ab4712010-07-14 17:59:35 -07009214 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009215 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009216 for (size_t i = 0; i < size; i++) {
9217 mEffects[i]->process();
9218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009219 }
9220 for (size_t i = 0; i < size; i++) {
9221 mEffects[i]->updateState();
9222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009223}
9224
Eric Laurentcab11242010-07-15 12:50:15 -07009225// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009226status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009227{
9228 effect_descriptor_t desc = effect->desc();
9229 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9230
9231 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009232 effect->setChain(this);
9233 sp<ThreadBase> thread = mThread.promote();
9234 if (thread == 0) {
9235 return NO_INIT;
9236 }
9237 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238
9239 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9240 // Auxiliary effects are inserted at the beginning of mEffects vector as
9241 // they are processed first and accumulated in chain input buffer
9242 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009243
Mathias Agopian65ab4712010-07-14 17:59:35 -07009244 // the input buffer for auxiliary effect contains mono samples in
9245 // 32 bit format. This is to avoid saturation in AudoMixer
9246 // accumulation stage. Saturation is done in EffectModule::process() before
9247 // calling the process in effect engine
9248 size_t numSamples = thread->frameCount();
9249 int32_t *buffer = new int32_t[numSamples];
9250 memset(buffer, 0, numSamples * sizeof(int32_t));
9251 effect->setInBuffer((int16_t *)buffer);
9252 // auxiliary effects output samples to chain input buffer for further processing
9253 // by insert effects
9254 effect->setOutBuffer(mInBuffer);
9255 } else {
9256 // Insert effects are inserted at the end of mEffects vector as they are processed
9257 // after track and auxiliary effects.
9258 // Insert effect order as a function of indicated preference:
9259 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9260 // another effect is present
9261 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9262 // last effect claiming first position
9263 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9264 // first effect claiming last position
9265 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9266 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9267 // already present
9268
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009269 size_t size = mEffects.size();
9270 size_t idx_insert = size;
9271 ssize_t idx_insert_first = -1;
9272 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009274 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009275 effect_descriptor_t d = mEffects[i]->desc();
9276 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9277 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9278 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9279 // check invalid effect chaining combinations
9280 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9281 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009282 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009283 return INVALID_OPERATION;
9284 }
9285 // remember position of first insert effect and by default
9286 // select this as insert position for new effect
9287 if (idx_insert == size) {
9288 idx_insert = i;
9289 }
9290 // remember position of last insert effect claiming
9291 // first position
9292 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9293 idx_insert_first = i;
9294 }
9295 // remember position of first insert effect claiming
9296 // last position
9297 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9298 idx_insert_last == -1) {
9299 idx_insert_last = i;
9300 }
9301 }
9302 }
9303
9304 // modify idx_insert from first position if needed
9305 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9306 if (idx_insert_last != -1) {
9307 idx_insert = idx_insert_last;
9308 } else {
9309 idx_insert = size;
9310 }
9311 } else {
9312 if (idx_insert_first != -1) {
9313 idx_insert = idx_insert_first + 1;
9314 }
9315 }
9316
9317 // always read samples from chain input buffer
9318 effect->setInBuffer(mInBuffer);
9319
9320 // if last effect in the chain, output samples to chain
9321 // output buffer, otherwise to chain input buffer
9322 if (idx_insert == size) {
9323 if (idx_insert != 0) {
9324 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9325 mEffects[idx_insert-1]->configure();
9326 }
9327 effect->setOutBuffer(mOutBuffer);
9328 } else {
9329 effect->setOutBuffer(mInBuffer);
9330 }
9331 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332
Steve Block3856b092011-10-20 11:56:00 +01009333 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009334 }
9335 effect->configure();
9336 return NO_ERROR;
9337}
9338
Eric Laurentcab11242010-07-15 12:50:15 -07009339// removeEffect_l() must be called with PlaybackThread::mLock held
9340size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341{
9342 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009343 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009344 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9345
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009346 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009347 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009348 // calling stop here will remove pre-processing effect from the audio HAL.
9349 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9350 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009351 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9352 mEffects[i]->state() == EffectModule::STOPPING) {
9353 mEffects[i]->stop();
9354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9356 delete[] effect->inBuffer();
9357 } else {
9358 if (i == size - 1 && i != 0) {
9359 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9360 mEffects[i - 1]->configure();
9361 }
9362 }
9363 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009364 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009365 break;
9366 }
9367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009368
9369 return mEffects.size();
9370}
9371
Eric Laurentcab11242010-07-15 12:50:15 -07009372// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009373void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009374{
9375 size_t size = mEffects.size();
9376 for (size_t i = 0; i < size; i++) {
9377 mEffects[i]->setDevice(device);
9378 }
9379}
9380
Eric Laurentcab11242010-07-15 12:50:15 -07009381// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009382void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383{
9384 size_t size = mEffects.size();
9385 for (size_t i = 0; i < size; i++) {
9386 mEffects[i]->setMode(mode);
9387 }
9388}
9389
Eric Laurentcab11242010-07-15 12:50:15 -07009390// setVolume_l() must be called with PlaybackThread::mLock held
9391bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009392{
9393 uint32_t newLeft = *left;
9394 uint32_t newRight = *right;
9395 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009396 int ctrlIdx = -1;
9397 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009398
Eric Laurentcab11242010-07-15 12:50:15 -07009399 // first update volume controller
9400 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009401 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009402 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9403 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009404 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009405 break;
9406 }
9407 }
9408
9409 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009410 if (hasControl) {
9411 *left = mNewLeftVolume;
9412 *right = mNewRightVolume;
9413 }
9414 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009415 }
9416
9417 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009418 mLeftVolume = newLeft;
9419 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009420
9421 // second get volume update from volume controller
9422 if (ctrlIdx >= 0) {
9423 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009424 mNewLeftVolume = newLeft;
9425 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009426 }
9427 // then indicate volume to all other effects in chain.
9428 // Pass altered volume to effects before volume controller
9429 // and requested volume to effects after controller
9430 uint32_t lVol = newLeft;
9431 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009432
Mathias Agopian65ab4712010-07-14 17:59:35 -07009433 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009434 if ((int)i == ctrlIdx) continue;
9435 // this also works for ctrlIdx == -1 when there is no volume controller
9436 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009437 lVol = *left;
9438 rVol = *right;
9439 }
9440 mEffects[i]->setVolume(&lVol, &rVol, false);
9441 }
9442 *left = newLeft;
9443 *right = newRight;
9444
9445 return hasControl;
9446}
9447
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009448void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009449{
9450 const size_t SIZE = 256;
9451 char buffer[SIZE];
9452 String8 result;
9453
9454 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9455 result.append(buffer);
9456
9457 bool locked = tryLock(mLock);
9458 // failed to lock - AudioFlinger is probably deadlocked
9459 if (!locked) {
9460 result.append("\tCould not lock mutex:\n");
9461 }
9462
Eric Laurentcab11242010-07-15 12:50:15 -07009463 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9464 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009465 mEffects.size(),
9466 (uint32_t)mInBuffer,
9467 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009468 mActiveTrackCnt);
9469 result.append(buffer);
9470 write(fd, result.string(), result.size());
9471
9472 for (size_t i = 0; i < mEffects.size(); ++i) {
9473 sp<EffectModule> effect = mEffects[i];
9474 if (effect != 0) {
9475 effect->dump(fd, args);
9476 }
9477 }
9478
9479 if (locked) {
9480 mLock.unlock();
9481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009482}
9483
Eric Laurent59255e42011-07-27 19:49:51 -07009484// must be called with ThreadBase::mLock held
9485void AudioFlinger::EffectChain::setEffectSuspended_l(
9486 const effect_uuid_t *type, bool suspend)
9487{
9488 sp<SuspendedEffectDesc> desc;
9489 // use effect type UUID timelow as key as there is no real risk of identical
9490 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009491 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009492 if (suspend) {
9493 if (index >= 0) {
9494 desc = mSuspendedEffects.valueAt(index);
9495 } else {
9496 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009497 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009498 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009499 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009500 }
9501 if (desc->mRefCount++ == 0) {
9502 sp<EffectModule> effect = getEffectIfEnabled(type);
9503 if (effect != 0) {
9504 desc->mEffect = effect;
9505 effect->setSuspended(true);
9506 effect->setEnabled(false);
9507 }
9508 }
9509 } else {
9510 if (index < 0) {
9511 return;
9512 }
9513 desc = mSuspendedEffects.valueAt(index);
9514 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009515 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 desc->mRefCount = 1;
9517 }
9518 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009519 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009520 if (desc->mEffect != 0) {
9521 sp<EffectModule> effect = desc->mEffect.promote();
9522 if (effect != 0) {
9523 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009524 effect->lock();
9525 EffectHandle *handle = effect->controlHandle_l();
9526 if (handle != NULL && !handle->destroyed_l()) {
9527 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009528 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009529 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009530 }
9531 desc->mEffect.clear();
9532 }
9533 mSuspendedEffects.removeItemsAt(index);
9534 }
9535 }
9536}
9537
9538// must be called with ThreadBase::mLock held
9539void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9540{
9541 sp<SuspendedEffectDesc> desc;
9542
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009543 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009544 if (suspend) {
9545 if (index >= 0) {
9546 desc = mSuspendedEffects.valueAt(index);
9547 } else {
9548 desc = new SuspendedEffectDesc();
9549 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009550 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009551 }
9552 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009553 Vector< sp<EffectModule> > effects;
9554 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009555 for (size_t i = 0; i < effects.size(); i++) {
9556 setEffectSuspended_l(&effects[i]->desc().type, true);
9557 }
9558 }
9559 } else {
9560 if (index < 0) {
9561 return;
9562 }
9563 desc = mSuspendedEffects.valueAt(index);
9564 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009565 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009566 desc->mRefCount = 1;
9567 }
9568 if (--desc->mRefCount == 0) {
9569 Vector<const effect_uuid_t *> types;
9570 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9571 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9572 continue;
9573 }
9574 types.add(&mSuspendedEffects.valueAt(i)->mType);
9575 }
9576 for (size_t i = 0; i < types.size(); i++) {
9577 setEffectSuspended_l(types[i], false);
9578 }
Steve Block3856b092011-10-20 11:56:00 +01009579 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009580 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9581 }
9582 }
9583}
9584
Eric Laurent6bffdb82011-09-23 08:40:41 -07009585
9586// The volume effect is used for automated tests only
9587#ifndef OPENSL_ES_H_
9588static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9589 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9590const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9591#endif //OPENSL_ES_H_
9592
Eric Laurentdb7c0792011-08-10 10:37:50 -07009593bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9594{
9595 // auxiliary effects and visualizer are never suspended on output mix
9596 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9597 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009598 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9599 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009600 return false;
9601 }
9602 return true;
9603}
9604
Glenn Kastend0539712012-01-30 12:56:03 -08009605void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009606{
Glenn Kastend0539712012-01-30 12:56:03 -08009607 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009608 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009609 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9610 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009611 }
Eric Laurent59255e42011-07-27 19:49:51 -07009612 }
Eric Laurent59255e42011-07-27 19:49:51 -07009613}
9614
9615sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9616 const effect_uuid_t *type)
9617{
Glenn Kasten090f0192012-01-30 13:00:02 -08009618 sp<EffectModule> effect = getEffectFromType_l(type);
9619 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009620}
9621
9622void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9623 bool enabled)
9624{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009625 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009626 if (enabled) {
9627 if (index < 0) {
9628 // if the effect is not suspend check if all effects are suspended
9629 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9630 if (index < 0) {
9631 return;
9632 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009633 if (!isEffectEligibleForSuspend(effect->desc())) {
9634 return;
9635 }
Eric Laurent59255e42011-07-27 19:49:51 -07009636 setEffectSuspended_l(&effect->desc().type, enabled);
9637 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009638 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009639 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009640 return;
9641 }
Eric Laurent59255e42011-07-27 19:49:51 -07009642 }
Steve Block3856b092011-10-20 11:56:00 +01009643 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009644 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009645 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9646 // if effect is requested to suspended but was not yet enabled, supend it now.
9647 if (desc->mEffect == 0) {
9648 desc->mEffect = effect;
9649 effect->setEnabled(false);
9650 effect->setSuspended(true);
9651 }
9652 } else {
9653 if (index < 0) {
9654 return;
9655 }
Steve Block3856b092011-10-20 11:56:00 +01009656 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009657 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009658 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9659 desc->mEffect.clear();
9660 effect->setSuspended(false);
9661 }
9662}
9663
Mathias Agopian65ab4712010-07-14 17:59:35 -07009664#undef LOG_TAG
9665#define LOG_TAG "AudioFlinger"
9666
9667// ----------------------------------------------------------------------------
9668
9669status_t AudioFlinger::onTransact(
9670 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9671{
9672 return BnAudioFlinger::onTransact(code, data, reply, flags);
9673}
9674
Mathias Agopian65ab4712010-07-14 17:59:35 -07009675}; // namespace android