blob: e7abc455a082d089d466922d021957685dcc3d08 [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
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
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
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168// ----------------------------------------------------------------------------
169
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700170#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800173 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174 if (service == NULL) {
175 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800176 return;
177 }
178
179 service->addBatteryData(params);
180}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700181#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800182
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700184{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 int rc;
187
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700188 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700193 }
194 rc = audio_hw_device_open(mod, dev);
195 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700199 }
200 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202 rc = BAD_VALUE;
203 goto out;
204 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 return 0;
206
207out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700208 *dev = NULL;
209 return rc;
210}
211
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700217 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMasterVolume(1.0f),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700219 mMasterVolumeSW(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800220 mMasterVolumeSupportLvl(MVS_NONE),
221 mMasterMute(false),
222 mNextUniqueId(1),
223 mMode(AUDIO_MODE_INVALID),
224 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700226}
227
228void AudioFlinger::onFirstRef()
229{
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700231
Eric Laurent93575202011-01-18 18:39:02 -0800232 Mutex::Autolock _l(mLock);
233
Dima Zavin799a70e2011-04-18 16:57:27 -0700234 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800235 char val_str[PROPERTY_VALUE_MAX] = { 0 };
236 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
237 uint32_t int_val;
238 if (1 == sscanf(val_str, "%u", &int_val)) {
239 mStandbyTimeInNsecs = milliseconds(int_val);
240 ALOGI("Using %u mSec as standby time.", int_val);
241 } else {
242 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
243 ALOGI("Using default %u mSec as standby time.",
244 (uint32_t)(mStandbyTimeInNsecs / 1000000));
245 }
246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247
Eric Laurenta4c5a552012-03-29 10:12:40 -0700248 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
251AudioFlinger::~AudioFlinger()
252{
253 while (!mRecordThreads.isEmpty()) {
254 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700255 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256 }
257 while (!mPlaybackThreads.isEmpty()) {
258 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700259 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700261
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800262 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700264 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266 }
267}
268
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269static const char * const audio_interfaces[] = {
270 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271 AUDIO_HARDWARE_MODULE_ID_A2DP,
272 AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700277{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 } else {
286 // check a match for the requested module handle
287 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288 if (audioHwdevice != NULL) {
289 return audioHwdevice->hwDevice();
290 }
291 }
292 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700294 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 if ((dev->get_supported_devices(dev) & devices) == devices)
296 return dev;
297 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298
Dima Zavin799a70e2011-04-18 16:57:27 -0700299 return NULL;
300}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301
302status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append("Clients:\n");
309 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800310 sp<Client> client = mClients.valueAt(i).promote();
311 if (client != 0) {
312 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314 }
315 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316
317 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800321 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 result.append(buffer);
323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 write(fd, result.string(), result.size());
325 return NO_ERROR;
326}
327
328
329status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
330{
331 const size_t SIZE = 256;
332 char buffer[SIZE];
333 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800334 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335
John Grossman4ff14ba2012-02-08 16:37:41 -0800336 snprintf(buffer, SIZE, "Hardware status: %d\n"
337 "Standby Time mSec: %u\n",
338 hardwareStatus,
339 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340 result.append(buffer);
341 write(fd, result.string(), result.size());
342 return NO_ERROR;
343}
344
345status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 snprintf(buffer, SIZE, "Permission Denial: "
351 "can't dump AudioFlinger from pid=%d, uid=%d\n",
352 IPCThreadState::self()->getCallingPid(),
353 IPCThreadState::self()->getCallingUid());
354 result.append(buffer);
355 write(fd, result.string(), result.size());
356 return NO_ERROR;
357}
358
359static bool tryLock(Mutex& mutex)
360{
361 bool locked = false;
362 for (int i = 0; i < kDumpLockRetries; ++i) {
363 if (mutex.tryLock() == NO_ERROR) {
364 locked = true;
365 break;
366 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800367 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
Glenn Kasten44deb052012-02-05 18:09:08 -0800374 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 dumpPermissionDenial(fd, args);
376 } else {
377 // get state of hardware lock
378 bool hardwareLocked = tryLock(mHardwareLock);
379 if (!hardwareLocked) {
380 String8 result(kHardwareLockedString);
381 write(fd, result.string(), result.size());
382 } else {
383 mHardwareLock.unlock();
384 }
385
386 bool locked = tryLock(mLock);
387
388 // failed to lock - AudioFlinger is probably deadlocked
389 if (!locked) {
390 String8 result(kDeadlockedString);
391 write(fd, result.string(), result.size());
392 }
393
394 dumpClients(fd, args);
395 dumpInternals(fd, args);
396
397 // dump playback threads
398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
399 mPlaybackThreads.valueAt(i)->dump(fd, args);
400 }
401
402 // dump record threads
403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
404 mRecordThreads.valueAt(i)->dump(fd, args);
405 }
406
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 // dump all hardware devs
408 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700409 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700410 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 if (locked) mLock.unlock();
413 }
414 return NO_ERROR;
415}
416
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800417sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
418{
419 // If pid is already in the mClients wp<> map, then use that entry
420 // (for which promote() is always != 0), otherwise create a new entry and Client.
421 sp<Client> client = mClients.valueFor(pid).promote();
422 if (client == 0) {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
426
427 return client;
428}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429
430// IAudioFlinger interface
431
432
433sp<IAudioTrack> AudioFlinger::createTrack(
434 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800435 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800437 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700438 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800440 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800442 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800443 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int *sessionId,
445 status_t *status)
446{
447 sp<PlaybackThread::Track> track;
448 sp<TrackHandle> trackHandle;
449 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 status_t lStatus;
451 int lSessionId;
452
Glenn Kasten263709e2012-01-06 08:40:01 -0800453 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454 // but if someone uses binder directly they could bypass that and cause us to crash
455 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000456 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 lStatus = BAD_VALUE;
458 goto Exit;
459 }
460
461 {
462 Mutex::Autolock _l(mLock);
463 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700464 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000466 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800471 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
Steve Block3856b092011-10-20 11:56:00 +0100473 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700474 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700475 // check if an effect chain with the same session ID is present on another
476 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700477 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
479 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700481 if (sessions & PlaybackThread::EFFECT_SESSION) {
482 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700483 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700484 }
Eric Laurentde070132010-07-13 04:45:46 -0700485 }
486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 lSessionId = *sessionId;
488 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700489 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700490 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 if (sessionId != NULL) {
492 *sessionId = lSessionId;
493 }
494 }
Steve Block3856b092011-10-20 11:56:00 +0100495 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
497 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800498 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700499
500 // move effect chain to this output thread if an effect on same session was waiting
501 // for a track to be created
502 if (lStatus == NO_ERROR && effectThread != NULL) {
503 Mutex::Autolock _dl(thread->mLock);
504 Mutex::Autolock _sl(effectThread->mLock);
505 moveEffectChain_l(lSessionId, effectThread, thread, true);
506 }
Eric Laurenta011e352012-03-29 15:51:43 -0700507
508 // Look for sync events awaiting for a session to be used.
509 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
510 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
511 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700512 if (lStatus == NO_ERROR) {
513 track->setSyncEvent(mPendingSyncEvents[i]);
514 } else {
515 mPendingSyncEvents[i]->cancel();
516 }
Eric Laurenta011e352012-03-29 15:51:43 -0700517 mPendingSyncEvents.removeAt(i);
518 i--;
519 }
520 }
521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522 }
523 if (lStatus == NO_ERROR) {
524 trackHandle = new TrackHandle(track);
525 } else {
526 // remove local strong reference to Client before deleting the Track so that the Client
527 // destructor is called by the TrackBase destructor with mLock held
528 client.clear();
529 track.clear();
530 }
531
532Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700533 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 *status = lStatus;
535 }
536 return trackHandle;
537}
538
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800539uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540{
541 Mutex::Autolock _l(mLock);
542 PlaybackThread *thread = checkPlaybackThread_l(output);
543 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000544 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 return 0;
546 }
547 return thread->sampleRate();
548}
549
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800550int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551{
552 Mutex::Autolock _l(mLock);
553 PlaybackThread *thread = checkPlaybackThread_l(output);
554 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000555 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 return 0;
557 }
558 return thread->channelCount();
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800567 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 }
569 return thread->format();
570}
571
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573{
574 Mutex::Autolock _l(mLock);
575 PlaybackThread *thread = checkPlaybackThread_l(output);
576 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return 0;
579 }
Glenn Kasten58912562012-04-03 10:45:00 -0700580 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
581 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 return thread->frameCount();
583}
584
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800585uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586{
587 Mutex::Autolock _l(mLock);
588 PlaybackThread *thread = checkPlaybackThread_l(output);
589 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000590 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 return 0;
592 }
593 return thread->latency();
594}
595
596status_t AudioFlinger::setMasterVolume(float value)
597{
Eric Laurenta1884f92011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
John Grossman4ff14ba2012-02-08 16:37:41 -0800608 float swmv = value;
609
Eric Laurenta4c5a552012-03-29 10:12:40 -0700610 Mutex::Autolock _l(mLock);
611
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 if (MVS_NONE != mMasterVolumeSupportLvl) {
614 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
615 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700616 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800617
618 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
619 if (NULL != dev->set_master_volume) {
620 dev->set_master_volume(dev, value);
621 }
622 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800623 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800624
625 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627
John Grossman4ff14ba2012-02-08 16:37:41 -0800628 mMasterVolume = value;
629 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800630 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700631 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632
633 return NO_ERROR;
634}
635
Glenn Kastenf78aee72012-01-04 11:00:47 -0800636status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637{
Eric Laurenta1884f92011-08-23 08:25:03 -0700638 status_t ret = initCheck();
639 if (ret != NO_ERROR) {
640 return ret;
641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642
643 // check calling permissions
644 if (!settingsAllowed()) {
645 return PERMISSION_DENIED;
646 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800647 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000648 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 return BAD_VALUE;
650 }
651
652 { // scope for the lock
653 AutoMutex lock(mHardwareLock);
654 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700655 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 mHardwareStatus = AUDIO_HW_IDLE;
657 }
658
659 if (NO_ERROR == ret) {
660 Mutex::Autolock _l(mLock);
661 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800662 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700663 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 }
665
666 return ret;
667}
668
669status_t AudioFlinger::setMicMute(bool state)
670{
Eric Laurenta1884f92011-08-23 08:25:03 -0700671 status_t ret = initCheck();
672 if (ret != NO_ERROR) {
673 return ret;
674 }
675
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 // check calling permissions
677 if (!settingsAllowed()) {
678 return PERMISSION_DENIED;
679 }
680
681 AutoMutex lock(mHardwareLock);
682 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700683 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 mHardwareStatus = AUDIO_HW_IDLE;
685 return ret;
686}
687
688bool AudioFlinger::getMicMute() const
689{
Eric Laurenta1884f92011-08-23 08:25:03 -0700690 status_t ret = initCheck();
691 if (ret != NO_ERROR) {
692 return false;
693 }
694
Dima Zavinfce7a472011-04-19 22:30:36 -0700695 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800696 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700698 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_IDLE;
700 return state;
701}
702
703status_t AudioFlinger::setMasterMute(bool muted)
704{
705 // check calling permissions
706 if (!settingsAllowed()) {
707 return PERMISSION_DENIED;
708 }
709
Eric Laurent93575202011-01-18 18:39:02 -0800710 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800711 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800713 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700714 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715
716 return NO_ERROR;
717}
718
719float AudioFlinger::masterVolume() const
720{
Glenn Kasten98067102011-12-13 11:47:54 -0800721 Mutex::Autolock _l(mLock);
722 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723}
724
John Grossman4ff14ba2012-02-08 16:37:41 -0800725float AudioFlinger::masterVolumeSW() const
726{
727 Mutex::Autolock _l(mLock);
728 return masterVolumeSW_l();
729}
730
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731bool AudioFlinger::masterMute() const
732{
Glenn Kasten98067102011-12-13 11:47:54 -0800733 Mutex::Autolock _l(mLock);
734 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735}
736
John Grossman4ff14ba2012-02-08 16:37:41 -0800737float AudioFlinger::masterVolume_l() const
738{
739 if (MVS_FULL == mMasterVolumeSupportLvl) {
740 float ret_val;
741 AutoMutex lock(mHardwareLock);
742
743 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800744 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
745 (NULL != mPrimaryHardwareDev->get_master_volume),
746 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800747
748 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
749 mHardwareStatus = AUDIO_HW_IDLE;
750 return ret_val;
751 }
752
753 return mMasterVolume;
754}
755
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800756status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
757 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758{
759 // check calling permissions
760 if (!settingsAllowed()) {
761 return PERMISSION_DENIED;
762 }
763
Glenn Kasten263709e2012-01-06 08:40:01 -0800764 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000765 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 return BAD_VALUE;
767 }
768
769 AutoMutex lock(mLock);
770 PlaybackThread *thread = NULL;
771 if (output) {
772 thread = checkPlaybackThread_l(output);
773 if (thread == NULL) {
774 return BAD_VALUE;
775 }
776 }
777
778 mStreamTypes[stream].volume = value;
779
780 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800781 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700782 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 }
784 } else {
785 thread->setStreamVolume(stream, value);
786 }
787
788 return NO_ERROR;
789}
790
Glenn Kastenfff6d712012-01-12 16:38:12 -0800791status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792{
793 // check calling permissions
794 if (!settingsAllowed()) {
795 return PERMISSION_DENIED;
796 }
797
Glenn Kasten263709e2012-01-06 08:40:01 -0800798 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700799 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000800 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 return BAD_VALUE;
802 }
803
Eric Laurent93575202011-01-18 18:39:02 -0800804 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 mStreamTypes[stream].mute = muted;
806 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700807 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808
809 return NO_ERROR;
810}
811
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800812float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813{
Glenn Kasten263709e2012-01-06 08:40:01 -0800814 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return 0.0f;
816 }
817
818 AutoMutex lock(mLock);
819 float volume;
820 if (output) {
821 PlaybackThread *thread = checkPlaybackThread_l(output);
822 if (thread == NULL) {
823 return 0.0f;
824 }
825 volume = thread->streamVolume(stream);
826 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800827 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
830 return volume;
831}
832
Glenn Kastenfff6d712012-01-12 16:38:12 -0800833bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
Glenn Kasten263709e2012-01-06 08:40:01 -0800835 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return true;
837 }
838
Glenn Kasten6637baa2012-01-09 09:40:36 -0800839 AutoMutex lock(mLock);
840 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841}
842
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800843status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800845 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
847 // check calling permissions
848 if (!settingsAllowed()) {
849 return PERMISSION_DENIED;
850 }
851
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 // ioHandle == 0 means the parameters are global to the audio hardware interface
853 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800856 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857 AutoMutex lock(mHardwareLock);
858 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
861 status_t result = dev->set_parameters(dev, keyValuePairs.string());
862 final_result = result ?: final_result;
863 }
864 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800865 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700866 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
867 AudioParameter param = AudioParameter(keyValuePairs);
868 String8 value;
869 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700870 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
871 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700872 for (size_t i = 0; i < mRecordThreads.size(); i++) {
873 sp<RecordThread> thread = mRecordThreads.valueAt(i);
874 RecordThread::RecordTrack *track = thread->track();
875 if (track != NULL) {
876 audio_devices_t device = (audio_devices_t)(
877 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700878 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 thread->setEffectSuspended(FX_IID_AEC,
880 suspend,
881 track->sessionId());
882 thread->setEffectSuspended(FX_IID_NS,
883 suspend,
884 track->sessionId());
885 }
886 }
Eric Laurentbee53372011-08-29 12:42:48 -0700887 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700888 }
889 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700890 String8 screenState;
891 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
892 bool isOff = screenState == "off";
893 if (isOff != (gScreenState & 1)) {
894 gScreenState = ((gScreenState & ~1) + 2) | isOff;
895 }
896 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700897 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700898 }
899
900 // hold a strong ref on thread in case closeOutput() or closeInput() is called
901 // and the thread is exited once the lock is released
902 sp<ThreadBase> thread;
903 {
904 Mutex::Autolock _l(mLock);
905 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700906 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800908 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700909 // indicate output device change to all input threads for pre processing
910 AudioParameter param = AudioParameter(keyValuePairs);
911 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700912 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
913 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700914 for (size_t i = 0; i < mRecordThreads.size(); i++) {
915 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
916 }
917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
919 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800920 if (thread != 0) {
921 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 }
923 return BAD_VALUE;
924}
925
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800926String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800928// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
930
Eric Laurenta4c5a552012-03-29 10:12:40 -0700931 Mutex::Autolock _l(mLock);
932
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700934 String8 out_s8;
935
Dima Zavin799a70e2011-04-18 16:57:27 -0700936 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800937 char *s;
938 {
939 AutoMutex lock(mHardwareLock);
940 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700941 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800942 s = dev->get_parameters(dev, keys.string());
943 mHardwareStatus = AUDIO_HW_IDLE;
944 }
John Grossmanef7740b2012-02-09 11:28:36 -0800945 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700946 free(s);
947 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700948 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 }
950
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
952 if (playbackThread != NULL) {
953 return playbackThread->getParameters(keys);
954 }
955 RecordThread *recordThread = checkRecordThread_l(ioHandle);
956 if (recordThread != NULL) {
957 return recordThread->getParameters(keys);
958 }
959 return String8("");
960}
961
Glenn Kastendd8104c2012-07-02 12:42:44 -0700962size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
963 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964{
Eric Laurenta1884f92011-08-23 08:25:03 -0700965 status_t ret = initCheck();
966 if (ret != NO_ERROR) {
967 return 0;
968 }
969
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800970 AutoMutex lock(mHardwareLock);
971 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700972 struct audio_config config = {
973 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700974 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700975 format: format,
976 };
977 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800978 mHardwareStatus = AUDIO_HW_IDLE;
979 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980}
981
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800982unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 Mutex::Autolock _l(mLock);
985
986 RecordThread *recordThread = checkRecordThread_l(ioHandle);
987 if (recordThread != NULL) {
988 return recordThread->getInputFramesLost();
989 }
990 return 0;
991}
992
993status_t AudioFlinger::setVoiceVolume(float value)
994{
Eric Laurenta1884f92011-08-23 08:25:03 -0700995 status_t ret = initCheck();
996 if (ret != NO_ERROR) {
997 return ret;
998 }
999
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 // check calling permissions
1001 if (!settingsAllowed()) {
1002 return PERMISSION_DENIED;
1003 }
1004
1005 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001006 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001007 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 mHardwareStatus = AUDIO_HW_IDLE;
1009
1010 return ret;
1011}
1012
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001013status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1014 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015{
1016 status_t status;
1017
1018 Mutex::Autolock _l(mLock);
1019
1020 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1021 if (playbackThread != NULL) {
1022 return playbackThread->getRenderPosition(halFrames, dspFrames);
1023 }
1024
1025 return BAD_VALUE;
1026}
1027
1028void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1029{
1030
1031 Mutex::Autolock _l(mLock);
1032
Glenn Kastenbb001922012-02-03 11:10:26 -08001033 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 if (mNotificationClients.indexOfKey(pid) < 0) {
1035 sp<NotificationClient> notificationClient = new NotificationClient(this,
1036 client,
1037 pid);
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039
1040 mNotificationClients.add(pid, notificationClient);
1041
1042 sp<IBinder> binder = client->asBinder();
1043 binder->linkToDeath(notificationClient);
1044
1045 // the config change is always sent from playback or record threads to avoid deadlock
1046 // with AudioSystem::gLock
1047 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1048 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1049 }
1050
1051 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1052 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1053 }
1054 }
1055}
1056
1057void AudioFlinger::removeNotificationClient(pid_t pid)
1058{
1059 Mutex::Autolock _l(mLock);
1060
Glenn Kastena3b09252012-01-20 09:19:01 -08001061 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001062
Steve Block3856b092011-10-20 11:56:00 +01001063 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001064 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001065 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001066 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001068 ALOGV(" pid %d @ %d", ref->mPid, i);
1069 if (ref->mPid == pid) {
1070 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001071 mAudioSessionRefs.removeAt(i);
1072 delete ref;
1073 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001074 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001075 } else {
1076 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001077 }
1078 }
1079 if (removed) {
1080 purgeStaleEffects_l();
1081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082}
1083
1084// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001085void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086{
1087 size_t size = mNotificationClients.size();
1088 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001089 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1090 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 }
1092}
1093
1094// removeClient_l() must be called with AudioFlinger::mLock held
1095void AudioFlinger::removeClient_l(pid_t pid)
1096{
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 mClients.removeItem(pid);
1099}
1100
Eric Laurent717e1282012-06-29 16:36:52 -07001101// getEffectThread_l() must be called with AudioFlinger::mLock held
1102sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1103{
1104 sp<PlaybackThread> thread;
1105
1106 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1107 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1108 ALOG_ASSERT(thread == 0);
1109 thread = mPlaybackThreads.valueAt(i);
1110 }
1111 }
1112
1113 return thread;
1114}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115
1116// ----------------------------------------------------------------------------
1117
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001118AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1119 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001121 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001122 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001123 // mChannelMask
1124 mChannelCount(0),
1125 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1126 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001127 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001128 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129{
1130}
1131
1132AudioFlinger::ThreadBase::~ThreadBase()
1133{
1134 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001135 // do not lock the mutex in destructor
1136 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001137 if (mPowerManager != 0) {
1138 sp<IBinder> binder = mPowerManager->asBinder();
1139 binder->unlinkToDeath(mDeathRecipient);
1140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141}
1142
1143void AudioFlinger::ThreadBase::exit()
1144{
Steve Block3856b092011-10-20 11:56:00 +01001145 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001147 // This lock prevents the following race in thread (uniprocessor for illustration):
1148 // if (!exitPending()) {
1149 // // context switch from here to exit()
1150 // // exit() calls requestExit(), what exitPending() observes
1151 // // exit() calls signal(), which is dropped since no waiters
1152 // // context switch back from exit() to here
1153 // mWaitWorkCV.wait(...);
1154 // // now thread is hung
1155 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001156 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 requestExit();
1158 mWaitWorkCV.signal();
1159 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001160 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1161 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 requestExitAndWait();
1163}
1164
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1166{
1167 status_t status;
1168
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 Mutex::Autolock _l(mLock);
1171
1172 mNewParameters.add(keyValuePairs);
1173 mWaitWorkCV.signal();
1174 // wait condition with timeout in case the thread loop has exited
1175 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001176 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 status = mParamStatus;
1178 mWaitWorkCV.signal();
1179 } else {
1180 status = TIMED_OUT;
1181 }
1182 return status;
1183}
1184
1185void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1186{
1187 Mutex::Autolock _l(mLock);
1188 sendConfigEvent_l(event, param);
1189}
1190
1191// sendConfigEvent_l() must be called with ThreadBase::mLock held
1192void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1193{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001194 ConfigEvent configEvent;
1195 configEvent.mEvent = event;
1196 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 mWaitWorkCV.signal();
1200}
1201
1202void AudioFlinger::ThreadBase::processConfigEvents()
1203{
1204 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001205 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001207 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 mConfigEvents.removeAt(0);
1209 // release mLock before locking AudioFlinger mLock: lock order is always
1210 // AudioFlinger then ThreadBase to avoid cross deadlock
1211 mLock.unlock();
1212 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001213 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 mLock.lock();
1216 }
1217 mLock.unlock();
1218}
1219
1220status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1221{
1222 const size_t SIZE = 256;
1223 char buffer[SIZE];
1224 String8 result;
1225
1226 bool locked = tryLock(mLock);
1227 if (!locked) {
1228 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1229 write(fd, buffer, strlen(buffer));
1230 }
1231
Eric Laurent612bbb52012-03-14 15:03:26 -07001232 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1233 result.append(buffer);
1234 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1235 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1237 result.append(buffer);
1238 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1239 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001240 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1241 result.append(buffer);
1242 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 result.append(buffer);
1244 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1245 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001246 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1247 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1249 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001250 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 result.append(buffer);
1252
1253 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1254 result.append(buffer);
1255 result.append(" Index Command");
1256 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1257 snprintf(buffer, SIZE, "\n %02d ", i);
1258 result.append(buffer);
1259 result.append(mNewParameters[i]);
1260 }
1261
1262 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1263 result.append(buffer);
1264 snprintf(buffer, SIZE, " Index event param\n");
1265 result.append(buffer);
1266 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001267 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 result.append(buffer);
1269 }
1270 result.append("\n");
1271
1272 write(fd, result.string(), result.size());
1273
1274 if (locked) {
1275 mLock.unlock();
1276 }
1277 return NO_ERROR;
1278}
1279
Eric Laurent1d2bff02011-07-24 17:49:51 -07001280status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1281{
1282 const size_t SIZE = 256;
1283 char buffer[SIZE];
1284 String8 result;
1285
1286 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1287 write(fd, buffer, strlen(buffer));
1288
1289 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1290 sp<EffectChain> chain = mEffectChains[i];
1291 if (chain != 0) {
1292 chain->dump(fd, args);
1293 }
1294 }
1295 return NO_ERROR;
1296}
1297
Eric Laurentfeb0db62011-07-22 09:04:31 -07001298void AudioFlinger::ThreadBase::acquireWakeLock()
1299{
1300 Mutex::Autolock _l(mLock);
1301 acquireWakeLock_l();
1302}
1303
1304void AudioFlinger::ThreadBase::acquireWakeLock_l()
1305{
1306 if (mPowerManager == 0) {
1307 // use checkService() to avoid blocking if power service is not up yet
1308 sp<IBinder> binder =
1309 defaultServiceManager()->checkService(String16("power"));
1310 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001311 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001312 } else {
1313 mPowerManager = interface_cast<IPowerManager>(binder);
1314 binder->linkToDeath(mDeathRecipient);
1315 }
1316 }
1317 if (mPowerManager != 0) {
1318 sp<IBinder> binder = new BBinder();
1319 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1320 binder,
1321 String16(mName));
1322 if (status == NO_ERROR) {
1323 mWakeLockToken = binder;
1324 }
Steve Block3856b092011-10-20 11:56:00 +01001325 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001326 }
1327}
1328
1329void AudioFlinger::ThreadBase::releaseWakeLock()
1330{
1331 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001332 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001333}
1334
1335void AudioFlinger::ThreadBase::releaseWakeLock_l()
1336{
1337 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001339 if (mPowerManager != 0) {
1340 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1341 }
1342 mWakeLockToken.clear();
1343 }
1344}
1345
1346void AudioFlinger::ThreadBase::clearPowerManager()
1347{
1348 Mutex::Autolock _l(mLock);
1349 releaseWakeLock_l();
1350 mPowerManager.clear();
1351}
1352
1353void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1354{
1355 sp<ThreadBase> thread = mThread.promote();
1356 if (thread != 0) {
1357 thread->clearPowerManager();
1358 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001359 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001360}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001361
Eric Laurent59255e42011-07-27 19:49:51 -07001362void AudioFlinger::ThreadBase::setEffectSuspended(
1363 const effect_uuid_t *type, bool suspend, int sessionId)
1364{
1365 Mutex::Autolock _l(mLock);
1366 setEffectSuspended_l(type, suspend, sessionId);
1367}
1368
1369void AudioFlinger::ThreadBase::setEffectSuspended_l(
1370 const effect_uuid_t *type, bool suspend, int sessionId)
1371{
Glenn Kasten090f0192012-01-30 13:00:02 -08001372 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001373 if (chain != 0) {
1374 if (type != NULL) {
1375 chain->setEffectSuspended_l(type, suspend);
1376 } else {
1377 chain->setEffectSuspendedAll_l(suspend);
1378 }
1379 }
1380
1381 updateSuspendedSessions_l(type, suspend, sessionId);
1382}
1383
1384void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1385{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001386 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001387 if (index < 0) {
1388 return;
1389 }
1390
1391 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1392 mSuspendedSessions.editValueAt(index);
1393
1394 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001395 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001396 for (int j = 0; j < desc->mRefCount; j++) {
1397 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1398 chain->setEffectSuspendedAll_l(true);
1399 } else {
Steve Block3856b092011-10-20 11:56:00 +01001400 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001401 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001402 chain->setEffectSuspended_l(&desc->mType, true);
1403 }
1404 }
1405 }
1406}
1407
Eric Laurent59255e42011-07-27 19:49:51 -07001408void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1409 bool suspend,
1410 int sessionId)
1411{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001412 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001413
1414 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1415
1416 if (suspend) {
1417 if (index >= 0) {
1418 sessionEffects = mSuspendedSessions.editValueAt(index);
1419 } else {
1420 mSuspendedSessions.add(sessionId, sessionEffects);
1421 }
1422 } else {
1423 if (index < 0) {
1424 return;
1425 }
1426 sessionEffects = mSuspendedSessions.editValueAt(index);
1427 }
1428
1429
1430 int key = EffectChain::kKeyForSuspendAll;
1431 if (type != NULL) {
1432 key = type->timeLow;
1433 }
1434 index = sessionEffects.indexOfKey(key);
1435
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001436 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001437 if (suspend) {
1438 if (index >= 0) {
1439 desc = sessionEffects.valueAt(index);
1440 } else {
1441 desc = new SuspendedSessionDesc();
1442 if (type != NULL) {
1443 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1444 }
1445 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001446 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001447 }
1448 desc->mRefCount++;
1449 } else {
1450 if (index < 0) {
1451 return;
1452 }
1453 desc = sessionEffects.valueAt(index);
1454 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001455 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001456 sessionEffects.removeItemsAt(index);
1457 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001458 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001459 sessionId);
1460 mSuspendedSessions.removeItem(sessionId);
1461 }
1462 }
1463 }
1464 if (!sessionEffects.isEmpty()) {
1465 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1466 }
1467}
1468
1469void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1470 bool enabled,
1471 int sessionId)
1472{
1473 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001474 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1475}
Eric Laurent59255e42011-07-27 19:49:51 -07001476
Eric Laurenta85a74a2011-10-19 11:44:54 -07001477void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1478 bool enabled,
1479 int sessionId)
1480{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001481 if (mType != RECORD) {
1482 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1483 // another session. This gives the priority to well behaved effect control panels
1484 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001485 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1486 // global effects
1487 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001488 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1489 }
1490 }
Eric Laurent59255e42011-07-27 19:49:51 -07001491
1492 sp<EffectChain> chain = getEffectChain_l(sessionId);
1493 if (chain != 0) {
1494 chain->checkSuspendOnEffectEnabled(effect, enabled);
1495 }
1496}
1497
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498// ----------------------------------------------------------------------------
1499
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001500AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1501 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001502 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001503 uint32_t device,
1504 type_t type)
1505 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001506 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1507 // Assumes constructor is called by AudioFlinger with it's mLock held,
1508 // but it would be safer to explicitly pass initial masterMute as parameter
1509 mMasterMute(audioFlinger->masterMute_l()),
1510 // mStreamTypes[] initialized in constructor body
1511 mOutput(output),
1512 // Assumes constructor is called by AudioFlinger with it's mLock held,
1513 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001514 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001515 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001516 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001517 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001518 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001519 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001520 // index 0 is reserved for normal mixer's submix
1521 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522{
Glenn Kasten480b4682012-02-28 12:30:08 -08001523 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001524
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 readOutputParameters();
1526
Glenn Kasten263709e2012-01-06 08:40:01 -08001527 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001528 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1529 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1530 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001531 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1532 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001534 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1535 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536}
1537
1538AudioFlinger::PlaybackThread::~PlaybackThread()
1539{
1540 delete [] mMixBuffer;
1541}
1542
1543status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1544{
1545 dumpInternals(fd, args);
1546 dumpTracks(fd, args);
1547 dumpEffectChains(fd, args);
1548 return NO_ERROR;
1549}
1550
1551status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1552{
1553 const size_t SIZE = 256;
1554 char buffer[SIZE];
1555 String8 result;
1556
Glenn Kasten58912562012-04-03 10:45:00 -07001557 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1558 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1559 const stream_type_t *st = &mStreamTypes[i];
1560 if (i > 0) {
1561 result.appendFormat(", ");
1562 }
1563 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1564 if (st->mute) {
1565 result.append("M");
1566 }
1567 }
1568 result.append("\n");
1569 write(fd, result.string(), result.length());
1570 result.clear();
1571
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1573 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001574 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 for (size_t i = 0; i < mTracks.size(); ++i) {
1576 sp<Track> track = mTracks[i];
1577 if (track != 0) {
1578 track->dump(buffer, SIZE);
1579 result.append(buffer);
1580 }
1581 }
1582
1583 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1584 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001585 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001587 sp<Track> track = mActiveTracks[i].promote();
1588 if (track != 0) {
1589 track->dump(buffer, SIZE);
1590 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }
1592 }
1593 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001594
1595 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1596 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1597 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1598 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 return NO_ERROR;
1601}
1602
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1604{
1605 const size_t SIZE = 256;
1606 char buffer[SIZE];
1607 String8 result;
1608
1609 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1610 result.append(buffer);
1611 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1612 result.append(buffer);
1613 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1614 result.append(buffer);
1615 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1616 result.append(buffer);
1617 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1618 result.append(buffer);
1619 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1620 result.append(buffer);
1621 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1622 result.append(buffer);
1623 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001624 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625
1626 dumpBase(fd, args);
1627
1628 return NO_ERROR;
1629}
1630
1631// Thread virtuals
1632status_t AudioFlinger::PlaybackThread::readyToRun()
1633{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001634 status_t status = initCheck();
1635 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001636 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001637 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001638 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001640 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641}
1642
1643void AudioFlinger::PlaybackThread::onFirstRef()
1644{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001645 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646}
1647
1648// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001649sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001651 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001653 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001654 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 int frameCount,
1656 const sp<IMemory>& sharedBuffer,
1657 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001658 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001659 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 status_t *status)
1661{
1662 sp<Track> track;
1663 status_t lStatus;
1664
Glenn Kasten73d22752012-03-19 13:38:30 -07001665 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1666
1667 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001668 if (flags & IAudioFlinger::TRACK_FAST) {
1669 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001670 // not timed
1671 (!isTimed) &&
1672 // either of these use cases:
1673 (
1674 // use case 1: shared buffer with any frame count
1675 (
1676 (sharedBuffer != 0)
1677 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001678 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001680 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001682 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001683 )
1684 ) &&
1685 // PCM data
1686 audio_is_linear_pcm(format) &&
1687 // mono or stereo
1688 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1689 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001690#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001691 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001692 (sampleRate == mSampleRate) &&
1693#endif
1694 // normal mixer has an associated fast mixer
1695 hasFastMixer() &&
1696 // there are sufficient fast track slots available
1697 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001698 // FIXME test that MixerThread for this fast track has a capable output HAL
1699 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001700 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1702 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001703 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001705 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001706 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001707 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001708 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001709 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001710 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1711 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1712 audio_is_linear_pcm(format),
1713 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001714 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001715 // For compatibility with AudioTrack calculation, buffer depth is forced
1716 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1717 // This is probably too conservative, but legacy application code may depend on it.
1718 // If you change this calculation, also review the start threshold which is related.
1719 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1720 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1721 if (minBufCount < 2) {
1722 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001723 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001724 int minFrameCount = mNormalFrameCount * minBufCount;
1725 if (frameCount < minFrameCount) {
1726 frameCount = minFrameCount;
1727 }
1728 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001729 }
1730
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001732 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1733 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001734 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001735 "for output %p with format %d",
1736 sampleRate, format, channelMask, mOutput, mFormat);
1737 lStatus = BAD_VALUE;
1738 goto Exit;
1739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 }
1741 } else {
1742 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1743 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001744 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 lStatus = BAD_VALUE;
1746 goto Exit;
1747 }
1748 }
1749
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001750 lStatus = initCheck();
1751 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001752 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 goto Exit;
1754 }
1755
1756 { // scope for mLock
1757 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001758
1759 // all tracks in same audio session must share the same routing strategy otherwise
1760 // conflicts will happen when tracks are moved from one output to another by audio policy
1761 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001762 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001763 for (size_t i = 0; i < mTracks.size(); ++i) {
1764 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001765 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001766 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001767 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001768 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001769 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001770 lStatus = BAD_VALUE;
1771 goto Exit;
1772 }
1773 }
1774 }
1775
John Grossman4ff14ba2012-02-08 16:37:41 -08001776 if (!isTimed) {
1777 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001778 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001779 } else {
1780 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1781 channelMask, frameCount, sharedBuffer, sessionId);
1782 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001783 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 lStatus = NO_MEMORY;
1785 goto Exit;
1786 }
1787 mTracks.add(track);
1788
1789 sp<EffectChain> chain = getEffectChain_l(sessionId);
1790 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001791 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001793 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001794 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 }
1796 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001797
Glenn Kasten3acbd052012-02-28 10:39:56 -08001798 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1799 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1800 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1801 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001802 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001803 if (err != 0) {
1804 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001805 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001806 }
1807 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001808
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 lStatus = NO_ERROR;
1810
1811Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001812 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 *status = lStatus;
1814 }
1815 return track;
1816}
1817
Eric Laurente737cda2012-05-22 18:55:44 -07001818uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1819{
1820 if (mFastMixer != NULL) {
1821 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1822 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1823 }
1824 return latency;
1825}
1826
1827uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1828{
1829 return latency;
1830}
1831
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832uint32_t AudioFlinger::PlaybackThread::latency() const
1833{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001834 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001835 return latency_l();
1836}
1837uint32_t AudioFlinger::PlaybackThread::latency_l() const
1838{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001839 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001840 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001841 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 return 0;
1843 }
1844}
1845
Glenn Kasten6637baa2012-01-09 09:40:36 -08001846void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001848 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850}
1851
Glenn Kasten6637baa2012-01-09 09:40:36 -08001852void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001854 Mutex::Autolock _l(mLock);
1855 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856}
1857
Glenn Kasten6637baa2012-01-09 09:40:36 -08001858void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001860 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862}
1863
Glenn Kasten6637baa2012-01-09 09:40:36 -08001864void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001866 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868}
1869
Glenn Kastenfff6d712012-01-12 16:38:12 -08001870float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001872 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 return mStreamTypes[stream].volume;
1874}
1875
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876// addTrack_l() must be called with ThreadBase::mLock held
1877status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1878{
1879 status_t status = ALREADY_EXISTS;
1880
1881 // set retry count for buffer fill
1882 track->mRetryCount = kMaxTrackStartupRetries;
1883 if (mActiveTracks.indexOf(track) < 0) {
1884 // the track is newly added, make sure it fills up all its
1885 // buffers before playing. This is to ensure the client will
1886 // effectively get the latency it requested.
1887 track->mFillingUpStatus = Track::FS_FILLING;
1888 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001889 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 mActiveTracks.add(track);
1891 if (track->mainBuffer() != mMixBuffer) {
1892 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1893 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001894 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001895 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 }
1897 }
1898
1899 status = NO_ERROR;
1900 }
1901
Steve Block3856b092011-10-20 11:56:00 +01001902 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 mWaitWorkCV.broadcast();
1904
1905 return status;
1906}
1907
1908// destroyTrack_l() must be called with ThreadBase::mLock held
1909void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1910{
1911 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001912 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001914 removeTrack_l(track);
1915 }
1916}
1917
1918void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1919{
Eric Laurent29864602012-05-08 18:57:51 -07001920 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001921 mTracks.remove(track);
1922 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001923 // redundant as track is about to be destroyed, for dumpsys only
1924 track->mName = -1;
1925 if (track->isFastTrack()) {
1926 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001927 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001928 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1929 mFastTrackAvailMask |= 1 << index;
1930 // redundant as track is about to be destroyed, for dumpsys only
1931 track->mFastIndex = -1;
1932 }
Eric Laurentb469b942011-05-09 12:09:06 -07001933 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1934 if (chain != 0) {
1935 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 }
1937}
1938
1939String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1940{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001941 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001942 char *s;
1943
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001944 Mutex::Autolock _l(mLock);
1945 if (initCheck() != NO_ERROR) {
1946 return out_s8;
1947 }
1948
Dima Zavin799a70e2011-04-18 16:57:27 -07001949 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001950 out_s8 = String8(s);
1951 free(s);
1952 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953}
1954
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001955// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1957 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001958 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959
Steve Block3856b092011-10-20 11:56:00 +01001960 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961
1962 switch (event) {
1963 case AudioSystem::OUTPUT_OPENED:
1964 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001965 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 desc.samplingRate = mSampleRate;
1967 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001968 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 desc.latency = latency();
1970 param2 = &desc;
1971 break;
1972
1973 case AudioSystem::STREAM_CONFIG_CHANGED:
1974 param2 = &param;
1975 case AudioSystem::OUTPUT_CLOSED:
1976 default:
1977 break;
1978 }
1979 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1980}
1981
1982void AudioFlinger::PlaybackThread::readOutputParameters()
1983{
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001985 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1986 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001987 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001988 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001989 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001990 if (mFrameCount & 15) {
1991 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1992 mFrameCount);
1993 }
1994
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001995 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001996 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001997 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001998 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001999 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2000 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2001 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2002 maxNormalFrameCount = maxNormalFrameCount & ~15;
2003 if (maxNormalFrameCount < minNormalFrameCount) {
2004 maxNormalFrameCount = minNormalFrameCount;
2005 }
2006 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2007 if (multiplier <= 1.0) {
2008 multiplier = 1.0;
2009 } else if (multiplier <= 2.0) {
2010 if (2 * mFrameCount <= maxNormalFrameCount) {
2011 multiplier = 2.0;
2012 } else {
2013 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2014 }
2015 } else {
2016 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2017 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2018 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2019 // FIXME this rounding up should not be done if no HAL SRC
2020 uint32_t truncMult = (uint32_t) multiplier;
2021 if ((truncMult & 1)) {
2022 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2023 ++truncMult;
2024 }
2025 }
2026 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002027 }
Glenn Kasten58912562012-04-03 10:45:00 -07002028 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002029 mNormalFrameCount = multiplier * mFrameCount;
2030 // round up to nearest 16 frames to satisfy AudioMixer
2031 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002032 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033
Glenn Kastene9dd0172012-01-27 18:08:45 -08002034 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002035 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2036 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037
Eric Laurentde070132010-07-13 04:45:46 -07002038 // force reconfiguration of effect chains and engines to take new buffer size and audio
2039 // parameters into account
2040 // Note that mLock is not held when readOutputParameters() is called from the constructor
2041 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2042 // matter.
2043 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2044 Vector< sp<EffectChain> > effectChains = mEffectChains;
2045 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002046 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048}
2049
Eric Laurente737cda2012-05-22 18:55:44 -07002050
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2052{
Glenn Kastena0d68332012-01-27 16:47:15 -08002053 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 return BAD_VALUE;
2055 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002056 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002057 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 return INVALID_OPERATION;
2059 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002060 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061
Dima Zavin799a70e2011-04-18 16:57:27 -07002062 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063}
2064
Eric Laurent39e94f82010-07-28 01:32:47 -07002065uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066{
2067 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002068 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002070 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 }
2072
2073 for (size_t i = 0; i < mTracks.size(); ++i) {
2074 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002075 if (sessionId == track->sessionId() &&
2076 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002077 result |= TRACK_SESSION;
2078 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 }
2080 }
2081
Eric Laurent39e94f82010-07-28 01:32:47 -07002082 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083}
2084
Eric Laurentde070132010-07-13 04:45:46 -07002085uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2086{
Dima Zavinfce7a472011-04-19 22:30:36 -07002087 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002088 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002089 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2090 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002091 }
2092 for (size_t i = 0; i < mTracks.size(); i++) {
2093 sp<Track> track = mTracks[i];
2094 if (sessionId == track->sessionId() &&
2095 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002096 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002097 }
2098 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002099 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002100}
2101
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102
Glenn Kastenaed850d2012-01-26 09:46:34 -08002103AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002104{
2105 Mutex::Autolock _l(mLock);
2106 return mOutput;
2107}
2108
2109AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2110{
2111 Mutex::Autolock _l(mLock);
2112 AudioStreamOut *output = mOutput;
2113 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002114 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2115 // must push a NULL and wait for ack
2116 mOutputSink.clear();
2117 mPipeSink.clear();
2118 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002119 return output;
2120}
2121
2122// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002123audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002124{
2125 if (mOutput == NULL) {
2126 return NULL;
2127 }
2128 return &mOutput->stream->common;
2129}
2130
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002131uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002132{
Eric Laurentab9071b2012-06-04 13:45:29 -07002133 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002134}
2135
Eric Laurenta011e352012-03-29 15:51:43 -07002136status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2137{
2138 if (!isValidSyncEvent(event)) {
2139 return BAD_VALUE;
2140 }
2141
2142 Mutex::Autolock _l(mLock);
2143
2144 for (size_t i = 0; i < mTracks.size(); ++i) {
2145 sp<Track> track = mTracks[i];
2146 if (event->triggerSession() == track->sessionId()) {
2147 track->setSyncEvent(event);
2148 return NO_ERROR;
2149 }
2150 }
2151
2152 return NAME_NOT_FOUND;
2153}
2154
2155bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2156{
2157 switch (event->type()) {
2158 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2159 return true;
2160 default:
2161 break;
2162 }
2163 return false;
2164}
2165
Eric Laurent44a957f2012-05-15 15:26:05 -07002166void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2167{
2168 size_t count = tracksToRemove.size();
2169 if (CC_UNLIKELY(count)) {
2170 for (size_t i = 0 ; i < count ; i++) {
2171 const sp<Track>& track = tracksToRemove.itemAt(i);
2172 if ((track->sharedBuffer() != 0) &&
2173 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2174 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2175 }
2176 }
2177 }
2178
2179}
2180
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181// ----------------------------------------------------------------------------
2182
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002183AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002184 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002185 : PlaybackThread(audioFlinger, output, id, device, type),
2186 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002187 // mFastMixer below
2188 mFastMixerFutex(0)
2189 // mOutputSink below
2190 // mPipeSink below
2191 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192{
Glenn Kasten58912562012-04-03 10:45:00 -07002193 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002194 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002195 "mFrameCount=%d, mNormalFrameCount=%d",
2196 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2197 mNormalFrameCount);
2198 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2199
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002201 if (mChannelCount != FCC_2) {
2202 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
Glenn Kasten58912562012-04-03 10:45:00 -07002204
2205 // create an NBAIO sink for the HAL output stream, and negotiate
2206 mOutputSink = new AudioStreamOutSink(output->stream);
2207 size_t numCounterOffers = 0;
2208 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2209 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2210 ALOG_ASSERT(index == 0);
2211
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002212 // initialize fast mixer depending on configuration
2213 bool initFastMixer;
2214 switch (kUseFastMixer) {
2215 case FastMixer_Never:
2216 initFastMixer = false;
2217 break;
2218 case FastMixer_Always:
2219 initFastMixer = true;
2220 break;
2221 case FastMixer_Static:
2222 case FastMixer_Dynamic:
2223 initFastMixer = mFrameCount < mNormalFrameCount;
2224 break;
2225 }
2226 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002227
2228 // create a MonoPipe to connect our submix to FastMixer
2229 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002230 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2231 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2232 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2233 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002234 const NBAIO_Format offers[1] = {format};
2235 size_t numCounterOffers = 0;
2236 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2237 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002238 monoPipe->setAvgFrames((mScreenState & 1) ?
2239 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002240 mPipeSink = monoPipe;
2241
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002242#ifdef TEE_SINK_FRAMES
2243 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2244 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2245 numCounterOffers = 0;
2246 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2247 ALOG_ASSERT(index == 0);
2248 mTeeSink = teeSink;
2249 PipeReader *teeSource = new PipeReader(*teeSink);
2250 numCounterOffers = 0;
2251 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2252 ALOG_ASSERT(index == 0);
2253 mTeeSource = teeSource;
2254#endif
2255
Glenn Kasten58912562012-04-03 10:45:00 -07002256 // create fast mixer and configure it initially with just one fast track for our submix
2257 mFastMixer = new FastMixer();
2258 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002259#ifdef STATE_QUEUE_DUMP
2260 sq->setObserverDump(&mStateQueueObserverDump);
2261 sq->setMutatorDump(&mStateQueueMutatorDump);
2262#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002263 FastMixerState *state = sq->begin();
2264 FastTrack *fastTrack = &state->mFastTracks[0];
2265 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2266 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2267 fastTrack->mVolumeProvider = NULL;
2268 fastTrack->mGeneration++;
2269 state->mFastTracksGen++;
2270 state->mTrackMask = 1;
2271 // fast mixer will use the HAL output sink
2272 state->mOutputSink = mOutputSink.get();
2273 state->mOutputSinkGen++;
2274 state->mFrameCount = mFrameCount;
2275 state->mCommand = FastMixerState::COLD_IDLE;
2276 // already done in constructor initialization list
2277 //mFastMixerFutex = 0;
2278 state->mColdFutexAddr = &mFastMixerFutex;
2279 state->mColdGen++;
2280 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002281 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002282 sq->end();
2283 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2284
2285 // start the fast mixer
2286 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002287 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002288 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002289 if (err != 0) {
2290 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002291 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002292 }
Glenn Kasten58912562012-04-03 10:45:00 -07002293
Glenn Kastenc15d6652012-05-30 14:52:57 -07002294#ifdef AUDIO_WATCHDOG
2295 // create and start the watchdog
2296 mAudioWatchdog = new AudioWatchdog();
2297 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2298 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2299 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002300 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002301 if (err != 0) {
2302 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002303 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002304 }
2305#endif
2306
Glenn Kasten58912562012-04-03 10:45:00 -07002307 } else {
2308 mFastMixer = NULL;
2309 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002310
2311 switch (kUseFastMixer) {
2312 case FastMixer_Never:
2313 case FastMixer_Dynamic:
2314 mNormalSink = mOutputSink;
2315 break;
2316 case FastMixer_Always:
2317 mNormalSink = mPipeSink;
2318 break;
2319 case FastMixer_Static:
2320 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2321 break;
2322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323}
2324
2325AudioFlinger::MixerThread::~MixerThread()
2326{
Glenn Kasten58912562012-04-03 10:45:00 -07002327 if (mFastMixer != NULL) {
2328 FastMixerStateQueue *sq = mFastMixer->sq();
2329 FastMixerState *state = sq->begin();
2330 if (state->mCommand == FastMixerState::COLD_IDLE) {
2331 int32_t old = android_atomic_inc(&mFastMixerFutex);
2332 if (old == -1) {
2333 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2334 }
2335 }
2336 state->mCommand = FastMixerState::EXIT;
2337 sq->end();
2338 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2339 mFastMixer->join();
2340 // Though the fast mixer thread has exited, it's state queue is still valid.
2341 // We'll use that extract the final state which contains one remaining fast track
2342 // corresponding to our sub-mix.
2343 state = sq->begin();
2344 ALOG_ASSERT(state->mTrackMask == 1);
2345 FastTrack *fastTrack = &state->mFastTracks[0];
2346 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2347 delete fastTrack->mBufferProvider;
2348 sq->end(false /*didModify*/);
2349 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002350 if (mAudioWatchdog != 0) {
2351 mAudioWatchdog->requestExit();
2352 mAudioWatchdog->requestExitAndWait();
2353 mAudioWatchdog.clear();
2354 }
Glenn Kasten58912562012-04-03 10:45:00 -07002355 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 delete mAudioMixer;
2357}
2358
Glenn Kasten83efdd02012-02-24 07:21:32 -08002359class CpuStats {
2360public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002361 CpuStats();
2362 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002363#ifdef DEBUG_CPU_USAGE
2364private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002365 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2366 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2367
2368 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2369
2370 int mCpuNum; // thread's current CPU number
2371 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002372#endif
2373};
2374
Glenn Kasten190a46f2012-03-06 11:27:10 -08002375CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002376#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002377 : mCpuNum(-1), mCpukHz(-1)
2378#endif
2379{
2380}
2381
2382void CpuStats::sample(const String8 &title) {
2383#ifdef DEBUG_CPU_USAGE
2384 // get current thread's delta CPU time in wall clock ns
2385 double wcNs;
2386 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2387
2388 // record sample for wall clock statistics
2389 if (valid) {
2390 mWcStats.sample(wcNs);
2391 }
2392
2393 // get the current CPU number
2394 int cpuNum = sched_getcpu();
2395
2396 // get the current CPU frequency in kHz
2397 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2398
2399 // check if either CPU number or frequency changed
2400 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2401 mCpuNum = cpuNum;
2402 mCpukHz = cpukHz;
2403 // ignore sample for purposes of cycles
2404 valid = false;
2405 }
2406
2407 // if no change in CPU number or frequency, then record sample for cycle statistics
2408 if (valid && mCpukHz > 0) {
2409 double cycles = wcNs * cpukHz * 0.000001;
2410 mHzStats.sample(cycles);
2411 }
2412
2413 unsigned n = mWcStats.n();
2414 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002415 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002416 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002417 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2418 double perLoop = elapsed / (double) n;
2419 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002420 double perLoop1k = perLoop * 0.001;
2421 double mean = mWcStats.mean();
2422 double stddev = mWcStats.stddev();
2423 double minimum = mWcStats.minimum();
2424 double maximum = mWcStats.maximum();
2425 double meanCycles = mHzStats.mean();
2426 double stddevCycles = mHzStats.stddev();
2427 double minCycles = mHzStats.minimum();
2428 double maxCycles = mHzStats.maximum();
2429 mCpuUsage.resetElapsed();
2430 mWcStats.reset();
2431 mHzStats.reset();
2432 ALOGD("CPU usage for %s over past %.1f secs\n"
2433 " (%u mixer loops at %.1f mean ms per loop):\n"
2434 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2435 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2436 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2437 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002438 elapsed * .000000001, n, perLoop * .000001,
2439 mean * .001,
2440 stddev * .001,
2441 minimum * .001,
2442 maximum * .001,
2443 mean / perLoop100,
2444 stddev / perLoop100,
2445 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002446 maximum / perLoop100,
2447 meanCycles / perLoop1k,
2448 stddevCycles / perLoop1k,
2449 minCycles / perLoop1k,
2450 maxCycles / perLoop1k);
2451
Glenn Kasten83efdd02012-02-24 07:21:32 -08002452 }
2453 }
2454#endif
2455};
2456
Glenn Kasten37d825e2012-02-24 07:21:48 -08002457void AudioFlinger::PlaybackThread::checkSilentMode_l()
2458{
2459 if (!mMasterMute) {
2460 char value[PROPERTY_VALUE_MAX];
2461 if (property_get("ro.audio.silent", value, "0") > 0) {
2462 char *endptr;
2463 unsigned long ul = strtoul(value, &endptr, 0);
2464 if (*endptr == '\0' && ul != 0) {
2465 ALOGD("Silence is golden");
2466 // The setprop command will not allow a property to be changed after
2467 // the first time it is set, so we don't have to worry about un-muting.
2468 setMasterMute_l(true);
2469 }
2470 }
2471 }
2472}
2473
Glenn Kasten000f0e32012-03-01 17:10:56 -08002474bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475{
2476 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002477
Glenn Kasten000f0e32012-03-01 17:10:56 -08002478 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002479
2480 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002482
Glenn Kasten000f0e32012-03-01 17:10:56 -08002483 // DUPLICATING
2484 // FIXME could this be made local to while loop?
2485 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002486
Glenn Kasten66fcab92012-02-24 14:59:21 -08002487 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002488 sleepTime = idleSleepTime;
2489
Glenn Kasten9f34a362012-03-20 16:46:41 -07002490 if (mType == MIXER) {
2491 sleepTimeShift = 0;
2492 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002493
Glenn Kasten83efdd02012-02-24 07:21:32 -08002494 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002495 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496
Eric Laurentfeb0db62011-07-22 09:04:31 -07002497 acquireWakeLock();
2498
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 while (!exitPending())
2500 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002501 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002502
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002503 Vector< sp<EffectChain> > effectChains;
2504
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 processConfigEvents();
2506
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 { // scope for mLock
2508
2509 Mutex::Autolock _l(mLock);
2510
2511 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002512 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 }
2514
Glenn Kastenfa26a852012-03-06 11:28:04 -08002515 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002516
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002518 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002519 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002521
2522 threadLoop_standby();
2523
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 mStandby = true;
2525 mBytesWritten = 0;
2526 }
2527
Glenn Kasten3e074702012-02-28 18:40:35 -08002528 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 // we're about to wait, flush the binder command buffer
2530 IPCThreadState::self()->flushCommands();
2531
Glenn Kastenfa26a852012-03-06 11:28:04 -08002532 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002533
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 if (exitPending()) break;
2535
Eric Laurentfeb0db62011-07-22 09:04:31 -07002536 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002538 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002540 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002541 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542
Eric Laurentda747442012-04-25 18:53:13 -07002543 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002544 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002545
Glenn Kasten37d825e2012-02-24 07:21:48 -08002546 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547
Glenn Kasten000f0e32012-03-01 17:10:56 -08002548 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002550 if (mType == MIXER) {
2551 sleepTimeShift = 0;
2552 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002553
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 continue;
2555 }
2556 }
2557
Glenn Kasten81028042012-04-30 18:15:12 -07002558 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002559 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560
2561 // prevent any changes in effect chain list and in each effect chain
2562 // during mixing and effect process as the audio buffers could be deleted
2563 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002564 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566
Glenn Kastenfec279f2012-03-08 07:47:15 -08002567 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002568 threadLoop_mix();
2569 } else {
2570 threadLoop_sleepTime();
2571 }
2572
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002573 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002574 sleepTime = suspendSleepTimeUs();
2575 }
2576
2577 // only process effects if we're going to write
2578 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002579 for (size_t i = 0; i < effectChains.size(); i ++) {
2580 effectChains[i]->process_l();
2581 }
2582 }
2583
2584 // enable changes in effect chain
2585 unlockEffectChains(effectChains);
2586
2587 // sleepTime == 0 means we must write to audio hardware
2588 if (sleepTime == 0) {
2589
2590 threadLoop_write();
2591
2592if (mType == MIXER) {
2593 // write blocked detection
2594 nsecs_t now = systemTime();
2595 nsecs_t delta = now - mLastWriteTime;
2596 if (!mStandby && delta > maxPeriod) {
2597 mNumDelayedWrites++;
2598 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002599#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002600 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002601#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002602 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2603 ns2ms(delta), mNumDelayedWrites, this);
2604 lastWarning = now;
2605 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002606 }
2607}
2608
2609 mStandby = false;
2610 } else {
2611 usleep(sleepTime);
2612 }
2613
Glenn Kasten58912562012-04-03 10:45:00 -07002614 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002615 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002616 // same lock. This will also mutate and push a new fast mixer state.
2617 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002618 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002619
Glenn Kastenfa26a852012-03-06 11:28:04 -08002620 // FIXME I don't understand the need for this here;
2621 // it was in the original code but maybe the
2622 // assignment in saveOutputTracks() makes this unnecessary?
2623 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002624
2625 // Effect chains will be actually deleted here if they were removed from
2626 // mEffectChains list during mixing or effects processing
2627 effectChains.clear();
2628
2629 // FIXME Note that the above .clear() is no longer necessary since effectChains
2630 // is now local to this block, but will keep it for now (at least until merge done).
2631 }
2632
Glenn Kasten9f34a362012-03-20 16:46:41 -07002633 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2634 if (mType == MIXER || mType == DIRECT) {
2635 // put output stream into standby mode
2636 if (!mStandby) {
2637 mOutput->stream->common.standby(&mOutput->stream->common);
2638 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002639 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002640
2641 releaseWakeLock();
2642
2643 ALOGV("Thread %p type %d exiting", this, mType);
2644 return false;
2645}
2646
Glenn Kasten58912562012-04-03 10:45:00 -07002647void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2648{
Glenn Kasten58912562012-04-03 10:45:00 -07002649 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2650}
2651
2652void AudioFlinger::MixerThread::threadLoop_write()
2653{
2654 // FIXME we should only do one push per cycle; confirm this is true
2655 // Start the fast mixer if it's not already running
2656 if (mFastMixer != NULL) {
2657 FastMixerStateQueue *sq = mFastMixer->sq();
2658 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002659 if (state->mCommand != FastMixerState::MIX_WRITE &&
2660 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002661 if (state->mCommand == FastMixerState::COLD_IDLE) {
2662 int32_t old = android_atomic_inc(&mFastMixerFutex);
2663 if (old == -1) {
2664 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2665 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002666 if (mAudioWatchdog != 0) {
2667 mAudioWatchdog->resume();
2668 }
Glenn Kasten58912562012-04-03 10:45:00 -07002669 }
2670 state->mCommand = FastMixerState::MIX_WRITE;
2671 sq->end();
2672 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002673 if (kUseFastMixer == FastMixer_Dynamic) {
2674 mNormalSink = mPipeSink;
2675 }
Glenn Kasten58912562012-04-03 10:45:00 -07002676 } else {
2677 sq->end(false /*didModify*/);
2678 }
2679 }
2680 PlaybackThread::threadLoop_write();
2681}
2682
Glenn Kasten000f0e32012-03-01 17:10:56 -08002683// shared by MIXER and DIRECT, overridden by DUPLICATING
2684void AudioFlinger::PlaybackThread::threadLoop_write()
2685{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002686 // FIXME rewrite to reduce number of system calls
2687 mLastWriteTime = systemTime();
2688 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002689 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002690
Eric Laurent67c0a582012-05-01 19:31:12 -07002691 // If an NBAIO sink is present, use it to write the normal mixer's submix
2692 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002693#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002694 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002695#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002696 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002697#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002698 // update the setpoint when gScreenState changes
2699 uint32_t screenState = gScreenState;
2700 if (screenState != mScreenState) {
2701 mScreenState = screenState;
2702 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2703 if (pipe != NULL) {
2704 pipe->setAvgFrames((mScreenState & 1) ?
2705 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2706 }
2707 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002708 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002709#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002710 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002711#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002712 if (framesWritten > 0) {
2713 bytesWritten = framesWritten << mBitShift;
2714 } else {
2715 bytesWritten = framesWritten;
2716 }
2717 // otherwise use the HAL / AudioStreamOut directly
2718 } else {
2719 // Direct output thread.
2720 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002721 }
2722
Eric Laurent67c0a582012-05-01 19:31:12 -07002723 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002724 mNumWrites++;
2725 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002726}
2727
Glenn Kasten58912562012-04-03 10:45:00 -07002728void AudioFlinger::MixerThread::threadLoop_standby()
2729{
2730 // Idle the fast mixer if it's currently running
2731 if (mFastMixer != NULL) {
2732 FastMixerStateQueue *sq = mFastMixer->sq();
2733 FastMixerState *state = sq->begin();
2734 if (!(state->mCommand & FastMixerState::IDLE)) {
2735 state->mCommand = FastMixerState::COLD_IDLE;
2736 state->mColdFutexAddr = &mFastMixerFutex;
2737 state->mColdGen++;
2738 mFastMixerFutex = 0;
2739 sq->end();
2740 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2741 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002742 if (kUseFastMixer == FastMixer_Dynamic) {
2743 mNormalSink = mOutputSink;
2744 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002745 if (mAudioWatchdog != 0) {
2746 mAudioWatchdog->pause();
2747 }
Glenn Kasten58912562012-04-03 10:45:00 -07002748 } else {
2749 sq->end(false /*didModify*/);
2750 }
2751 }
2752 PlaybackThread::threadLoop_standby();
2753}
2754
Glenn Kasten000f0e32012-03-01 17:10:56 -08002755// shared by MIXER and DIRECT, overridden by DUPLICATING
2756void AudioFlinger::PlaybackThread::threadLoop_standby()
2757{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002758 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002759 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002760}
2761
2762void AudioFlinger::MixerThread::threadLoop_mix()
2763{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002764 // obtain the presentation timestamp of the next output buffer
2765 int64_t pts;
2766 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002767
Glenn Kasten952eeb22012-03-06 11:30:57 -08002768 if (NULL != mOutput->stream->get_next_write_timestamp) {
2769 status = mOutput->stream->get_next_write_timestamp(
2770 mOutput->stream, &pts);
2771 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002772
Glenn Kasten952eeb22012-03-06 11:30:57 -08002773 if (status != NO_ERROR) {
2774 pts = AudioBufferProvider::kInvalidPTS;
2775 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002776
Glenn Kasten952eeb22012-03-06 11:30:57 -08002777 // mix buffers...
2778 mAudioMixer->process(pts);
2779 // increase sleep time progressively when application underrun condition clears.
2780 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2781 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2782 // such that we would underrun the audio HAL.
2783 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2784 sleepTimeShift--;
2785 }
2786 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002787 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002788 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002789}
2790
2791void AudioFlinger::MixerThread::threadLoop_sleepTime()
2792{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 // If no tracks are ready, sleep once for the duration of an output
2794 // buffer size, then write 0s to the output
2795 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002796 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002797 sleepTime = activeSleepTime >> sleepTimeShift;
2798 if (sleepTime < kMinThreadSleepTimeUs) {
2799 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 // reduce sleep time in case of consecutive application underruns to avoid
2802 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2803 // duration we would end up writing less data than needed by the audio HAL if
2804 // the condition persists.
2805 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2806 sleepTimeShift++;
2807 }
2808 } else {
2809 sleepTime = idleSleepTime;
2810 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002811 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002812 memset (mMixBuffer, 0, mixBufferSize);
2813 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002814 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002815 }
2816 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817}
2818
2819// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002820AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002821 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822{
2823
Glenn Kasten29c23c32012-01-26 13:37:52 -08002824 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002826 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 size_t mixedTracks = 0;
2828 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002829 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002830 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002831 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832
2833 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002834 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835
Eric Laurent571d49c2010-08-11 05:20:11 -07002836 if (masterMute) {
2837 masterVolume = 0;
2838 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002840 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002842 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002843 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844 masterVolume = (float)((v + (1 << 23)) >> 24);
2845 chain.clear();
2846 }
2847
Glenn Kasten288ed212012-04-25 17:52:27 -07002848 // prepare a new state to push
2849 FastMixerStateQueue *sq = NULL;
2850 FastMixerState *state = NULL;
2851 bool didModify = false;
2852 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2853 if (mFastMixer != NULL) {
2854 sq = mFastMixer->sq();
2855 state = sq->begin();
2856 }
2857
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002859 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860 if (t == 0) continue;
2861
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002862 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002864
Glenn Kasten288ed212012-04-25 17:52:27 -07002865 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002866 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002867
2868 // It's theoretically possible (though unlikely) for a fast track to be created
2869 // and then removed within the same normal mix cycle. This is not a problem, as
2870 // the track never becomes active so it's fast mixer slot is never touched.
2871 // The converse, of removing an (active) track and then creating a new track
2872 // at the identical fast mixer slot within the same normal mix cycle,
2873 // is impossible because the slot isn't marked available until the end of each cycle.
2874 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002875 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2876 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002877 FastTrack *fastTrack = &state->mFastTracks[j];
2878
2879 // Determine whether the track is currently in underrun condition,
2880 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002881 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2882 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002883 uint32_t recentFull = (underruns.mBitFields.mFull -
2884 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2885 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2886 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2887 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2888 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2889 uint32_t recentUnderruns = recentPartial + recentEmpty;
2890 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002891 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002892 // or stopped which can occur when flush() is called while active
2893 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002894 track->mUnderrunCount += recentUnderruns;
2895 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002896
Glenn Kastend08f48c2012-05-01 18:14:02 -07002897 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002898 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002899 bool isActive = true;
2900 switch (track->mState) {
2901 case TrackBase::STOPPING_1:
2902 // track stays active in STOPPING_1 state until first underrun
2903 if (recentUnderruns > 0) {
2904 track->mState = TrackBase::STOPPING_2;
2905 }
2906 break;
2907 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002908 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002910 break;
2911 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002912 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002913 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002914 break;
2915 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002916 if (recentFull > 0 || recentPartial > 0) {
2917 // track has provided at least some frames recently: reset retry count
2918 track->mRetryCount = kMaxTrackRetries;
2919 }
2920 if (recentUnderruns == 0) {
2921 // no recent underruns: stay active
2922 break;
2923 }
2924 // there has recently been an underrun of some kind
2925 if (track->sharedBuffer() == 0) {
2926 // were any of the recent underruns "empty" (no frames available)?
2927 if (recentEmpty == 0) {
2928 // no, then ignore the partial underruns as they are allowed indefinitely
2929 break;
2930 }
2931 // there has recently been an "empty" underrun: decrement the retry counter
2932 if (--(track->mRetryCount) > 0) {
2933 break;
2934 }
2935 // indicate to client process that the track was disabled because of underrun;
2936 // it will then automatically call start() when data is available
2937 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2938 // remove from active list, but state remains ACTIVE [confusing but true]
2939 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002940 break;
2941 }
2942 // fall through
2943 case TrackBase::STOPPING_2:
2944 case TrackBase::PAUSED:
2945 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002946 case TrackBase::STOPPED:
2947 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002948 // Check for presentation complete if track is inactive
2949 // We have consumed all the buffers of this track.
2950 // This would be incomplete if we auto-paused on underrun
2951 {
2952 size_t audioHALFrames =
2953 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2954 size_t framesWritten =
2955 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2956 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2957 // track stays in active list until presentation is complete
2958 break;
2959 }
2960 }
2961 if (track->isStopping_2()) {
2962 track->mState = TrackBase::STOPPED;
2963 }
2964 if (track->isStopped()) {
2965 // Can't reset directly, as fast mixer is still polling this track
2966 // track->reset();
2967 // So instead mark this track as needing to be reset after push with ack
2968 resetMask |= 1 << i;
2969 }
2970 isActive = false;
2971 break;
2972 case TrackBase::IDLE:
2973 default:
2974 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002975 }
2976
2977 if (isActive) {
2978 // was it previously inactive?
2979 if (!(state->mTrackMask & (1 << j))) {
2980 ExtendedAudioBufferProvider *eabp = track;
2981 VolumeProvider *vp = track;
2982 fastTrack->mBufferProvider = eabp;
2983 fastTrack->mVolumeProvider = vp;
2984 fastTrack->mSampleRate = track->mSampleRate;
2985 fastTrack->mChannelMask = track->mChannelMask;
2986 fastTrack->mGeneration++;
2987 state->mTrackMask |= 1 << j;
2988 didModify = true;
2989 // no acknowledgement required for newly active tracks
2990 }
2991 // cache the combined master volume and stream type volume for fast mixer; this
2992 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2993 track->mCachedVolume = track->isMuted() ?
2994 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2995 ++fastTracks;
2996 } else {
2997 // was it previously active?
2998 if (state->mTrackMask & (1 << j)) {
2999 fastTrack->mBufferProvider = NULL;
3000 fastTrack->mGeneration++;
3001 state->mTrackMask &= ~(1 << j);
3002 didModify = true;
3003 // If any fast tracks were removed, we must wait for acknowledgement
3004 // because we're about to decrement the last sp<> on those tracks.
3005 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003006 } else {
3007 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003008 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003009 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003010 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003011 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003012 }
3013 continue;
3014 }
3015
3016 { // local variable scope to avoid goto warning
3017
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 audio_track_cblk_t* cblk = track->cblk();
3019
3020 // The first time a track is added we wait
3021 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003022 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003023 // make sure that we have enough frames to mix one full buffer.
3024 // enforce this condition only once to enable draining the buffer in case the client
3025 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003026 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003027 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003028 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003029 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003030 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003031 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003032 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003033 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003034 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003035 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003036 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003037 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003038 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3039 // the minimum track buffer size is normally twice the number of frames necessary
3040 // to fill one buffer and the resampler should not leave more than one buffer worth
3041 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003042 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003043 }
3044 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003045 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 !track->isPaused() && !track->isTerminated())
3047 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003048 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049
3050 mixedTracks++;
3051
3052 // track->mainBuffer() != mMixBuffer means there is an effect chain
3053 // connected to the track
3054 chain.clear();
3055 if (track->mainBuffer() != mMixBuffer) {
3056 chain = getEffectChain_l(track->sessionId());
3057 // Delegate volume control to effect in track effect chain if needed
3058 if (chain != 0) {
3059 tracksWithEffect++;
3060 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003061 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003062 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 }
3064 }
3065
3066
3067 int param = AudioMixer::VOLUME;
3068 if (track->mFillingUpStatus == Track::FS_FILLED) {
3069 // no ramp for the first volume setting
3070 track->mFillingUpStatus = Track::FS_ACTIVE;
3071 if (track->mState == TrackBase::RESUMING) {
3072 track->mState = TrackBase::ACTIVE;
3073 param = AudioMixer::RAMP_VOLUME;
3074 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003075 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 } else if (cblk->server != 0) {
3077 // If the track is stopped before the first frame was mixed,
3078 // do not apply ramp
3079 param = AudioMixer::RAMP_VOLUME;
3080 }
3081
3082 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003083 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003084 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003085 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003086 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 if (track->isPausing()) {
3088 track->setPaused();
3089 }
3090 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003091
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003093 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003095 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003096 vl = vlr & 0xFFFF;
3097 vr = vlr >> 16;
3098 // track volumes come from shared memory, so can't be trusted and must be clamped
3099 if (vl > MAX_GAIN_INT) {
3100 ALOGV("Track left volume out of range: %04X", vl);
3101 vl = MAX_GAIN_INT;
3102 }
3103 if (vr > MAX_GAIN_INT) {
3104 ALOGV("Track right volume out of range: %04X", vr);
3105 vr = MAX_GAIN_INT;
3106 }
3107 // now apply the master volume and stream type volume
3108 vl = (uint32_t)(v * vl) << 12;
3109 vr = (uint32_t)(v * vr) << 12;
3110 // assuming master volume and stream type volume each go up to 1.0,
3111 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112
Glenn Kasten05632a52012-01-03 14:22:33 -08003113 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3114 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003115 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003116 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003117 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003118 }
3119 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003121 // Delegate volume control to effect in track effect chain if needed
3122 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3123 // Do not ramp volume if volume is controlled by effect
3124 param = AudioMixer::VOLUME;
3125 track->mHasVolumeController = true;
3126 } else {
3127 // force no volume ramp when volume controller was just disabled or removed
3128 // from effect chain to avoid volume spike
3129 if (track->mHasVolumeController) {
3130 param = AudioMixer::VOLUME;
3131 }
3132 track->mHasVolumeController = false;
3133 }
3134
3135 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003136 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003137 vl = (vl + (1 << 11)) >> 12;
3138 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3139 vr = (vr + (1 << 11)) >> 12;
3140 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003141
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003142 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 -07003143
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003145 mAudioMixer->setBufferProvider(name, track);
3146 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003148 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3149 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3150 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003152 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 AudioMixer::TRACK,
3154 AudioMixer::FORMAT, (void *)track->format());
3155 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003156 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003158 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003160 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 AudioMixer::RESAMPLE,
3162 AudioMixer::SAMPLE_RATE,
3163 (void *)(cblk->sampleRate));
3164 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003165 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 AudioMixer::TRACK,
3167 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3168 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003169 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 AudioMixer::TRACK,
3171 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3172
3173 // reset retry count
3174 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003175
Eric Laurent27741442012-01-17 19:20:12 -08003176 // If one track is ready, set the mixer ready if:
3177 // - the mixer was not ready during previous round OR
3178 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003179 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003180 mixerStatus != MIXER_TRACKS_ENABLED) {
3181 mixerStatus = MIXER_TRACKS_READY;
3182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003184 // clear effect chain input buffer if an active track underruns to avoid sending
3185 // previous audio buffer again to effects
3186 chain = getEffectChain_l(track->sessionId());
3187 if (chain != 0) {
3188 chain->clearInputBuffer();
3189 }
3190
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003192 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3193 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 // We have consumed all the buffers of this track.
3195 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003196 // TODO: use actual buffer filling status instead of latency when available from
3197 // audio HAL
3198 size_t audioHALFrames =
3199 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3200 size_t framesWritten =
3201 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3202 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003203 if (track->isStopped()) {
3204 track->reset();
3205 }
Eric Laurenta011e352012-03-29 15:51:43 -07003206 tracksToRemove->add(track);
3207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003209 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 // No buffers for this track. Give it a few chances to
3211 // fill a buffer, then remove it from active list.
3212 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003213 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003215 // indicate to client process that the track was disabled because of underrun;
3216 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003217 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003218 // If one track is not ready, mark the mixer also not ready if:
3219 // - the mixer was ready during previous round OR
3220 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003221 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003222 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 mixerStatus = MIXER_TRACKS_ENABLED;
3224 }
3225 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003226 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 }
Glenn Kasten58912562012-04-03 10:45:00 -07003228
3229 } // local variable scope to avoid goto warning
3230track_is_ready: ;
3231
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 }
3233
Glenn Kasten288ed212012-04-25 17:52:27 -07003234 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003235 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003236 if (didModify) {
3237 state->mFastTracksGen++;
3238 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3239 if (kUseFastMixer == FastMixer_Dynamic &&
3240 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3241 state->mCommand = FastMixerState::COLD_IDLE;
3242 state->mColdFutexAddr = &mFastMixerFutex;
3243 state->mColdGen++;
3244 mFastMixerFutex = 0;
3245 if (kUseFastMixer == FastMixer_Dynamic) {
3246 mNormalSink = mOutputSink;
3247 }
3248 // If we go into cold idle, need to wait for acknowledgement
3249 // so that fast mixer stops doing I/O.
3250 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003251 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003252 }
3253 sq->end();
3254 }
3255 if (sq != NULL) {
3256 sq->end(didModify);
3257 sq->push(block);
3258 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003259 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3260 mAudioWatchdog->pause();
3261 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003262
3263 // Now perform the deferred reset on fast tracks that have stopped
3264 while (resetMask != 0) {
3265 size_t i = __builtin_ctz(resetMask);
3266 ALOG_ASSERT(i < count);
3267 resetMask &= ~(1 << i);
3268 sp<Track> t = mActiveTracks[i].promote();
3269 if (t == 0) continue;
3270 Track* track = t.get();
3271 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3272 track->reset();
3273 }
Glenn Kasten58912562012-04-03 10:45:00 -07003274
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 // remove all the tracks that need to be...
3276 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003277 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 for (size_t i=0 ; i<count ; i++) {
3279 const sp<Track>& track = tracksToRemove->itemAt(i);
3280 mActiveTracks.remove(track);
3281 if (track->mainBuffer() != mMixBuffer) {
3282 chain = getEffectChain_l(track->sessionId());
3283 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003284 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003285 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 }
3287 }
3288 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003289 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 }
3291 }
3292 }
3293
3294 // mix buffer must be cleared if all tracks are connected to an
3295 // effect chain as in this case the mixer will not write to
3296 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003297 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3298 // FIXME as a performance optimization, should remember previous zero status
3299 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 }
3301
Glenn Kasten58912562012-04-03 10:45:00 -07003302 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003303 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003304 if (fastTracks > 0) {
3305 mixerStatus = MIXER_TRACKS_READY;
3306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 return mixerStatus;
3308}
3309
Glenn Kasten66fcab92012-02-24 14:59:21 -08003310/*
3311The derived values that are cached:
3312 - mixBufferSize from frame count * frame size
3313 - activeSleepTime from activeSleepTimeUs()
3314 - idleSleepTime from idleSleepTimeUs()
3315 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3316 - maxPeriod from frame count and sample rate (MIXER only)
3317
3318The parameters that affect these derived values are:
3319 - frame count
3320 - frame size
3321 - sample rate
3322 - device type: A2DP or not
3323 - device latency
3324 - format: PCM or not
3325 - active sleep time
3326 - idle sleep time
3327*/
3328
3329void AudioFlinger::PlaybackThread::cacheParameters_l()
3330{
Glenn Kasten58912562012-04-03 10:45:00 -07003331 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003332 activeSleepTime = activeSleepTimeUs();
3333 idleSleepTime = idleSleepTimeUs();
3334}
3335
Eric Laurent22167852012-06-20 12:26:32 -07003336void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337{
Steve Block3856b092011-10-20 11:56:00 +01003338 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003339 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003341
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 size_t size = mTracks.size();
3343 for (size_t i = 0; i < size; i++) {
3344 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003345 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003346 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 }
3349 }
3350}
3351
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003353int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003355 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356}
3357
3358// deleteTrackName_l() must be called with ThreadBase::mLock held
3359void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3360{
Steve Block3856b092011-10-20 11:56:00 +01003361 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 mAudioMixer->deleteTrackName(name);
3363}
3364
3365// checkForNewParameters_l() must be called with ThreadBase::mLock held
3366bool AudioFlinger::MixerThread::checkForNewParameters_l()
3367{
Glenn Kasten58912562012-04-03 10:45:00 -07003368 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3369 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 bool reconfig = false;
3371
3372 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003373
3374 if (mFastMixer != NULL) {
3375 FastMixerStateQueue *sq = mFastMixer->sq();
3376 FastMixerState *state = sq->begin();
3377 if (!(state->mCommand & FastMixerState::IDLE)) {
3378 previousCommand = state->mCommand;
3379 state->mCommand = FastMixerState::HOT_IDLE;
3380 sq->end();
3381 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3382 } else {
3383 sq->end(false /*didModify*/);
3384 }
3385 }
3386
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 status_t status = NO_ERROR;
3388 String8 keyValuePair = mNewParameters[0];
3389 AudioParameter param = AudioParameter(keyValuePair);
3390 int value;
3391
3392 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3393 reconfig = true;
3394 }
3395 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003396 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 status = BAD_VALUE;
3398 } else {
3399 reconfig = true;
3400 }
3401 }
3402 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003403 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 status = BAD_VALUE;
3405 } else {
3406 reconfig = true;
3407 }
3408 }
3409 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3410 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003411 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 // if frame count is changed after track creation
3413 if (!mTracks.isEmpty()) {
3414 status = INVALID_OPERATION;
3415 } else {
3416 reconfig = true;
3417 }
3418 }
3419 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003420#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003421 // when changing the audio output device, call addBatteryData to notify
3422 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003423 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003424 uint32_t params = 0;
3425 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003426 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003427 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3428 }
3429
3430 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003431 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003432 // check if any other device (except speaker) is on
3433 if (value & deviceWithoutSpeaker ) {
3434 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3435 }
3436
3437 if (params != 0) {
3438 addBatteryData(params);
3439 }
3440 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003441#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003442
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 // forward device change to effects that have requested to be
3444 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003445 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003447 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 }
3449 }
3450
3451 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003452 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003453 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003455 mOutput->stream->common.standby(&mOutput->stream->common);
3456 mStandby = true;
3457 mBytesWritten = 0;
3458 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003459 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 }
3461 if (status == NO_ERROR && reconfig) {
3462 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003463 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3464 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003466 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003468 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 if (name < 0) break;
3470 mTracks[i]->mName = name;
3471 // limit track sample rate to 2 x new output sample rate
3472 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3473 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3474 }
3475 }
3476 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3477 }
3478 }
3479
3480 mNewParameters.removeAt(0);
3481
3482 mParamStatus = status;
3483 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003484 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3485 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003486 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 }
Glenn Kasten58912562012-04-03 10:45:00 -07003488
3489 if (!(previousCommand & FastMixerState::IDLE)) {
3490 ALOG_ASSERT(mFastMixer != NULL);
3491 FastMixerStateQueue *sq = mFastMixer->sq();
3492 FastMixerState *state = sq->begin();
3493 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3494 state->mCommand = previousCommand;
3495 sq->end();
3496 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3497 }
3498
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 return reconfig;
3500}
3501
3502status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3503{
3504 const size_t SIZE = 256;
3505 char buffer[SIZE];
3506 String8 result;
3507
3508 PlaybackThread::dumpInternals(fd, args);
3509
3510 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3511 result.append(buffer);
3512 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003513
3514 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3515 FastMixerDumpState copy = mFastMixerDumpState;
3516 copy.dump(fd);
3517
Glenn Kasten39993082012-05-31 13:40:27 -07003518#ifdef STATE_QUEUE_DUMP
3519 // Similar for state queue
3520 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3521 observerCopy.dump(fd);
3522 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3523 mutatorCopy.dump(fd);
3524#endif
3525
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003526 // Write the tee output to a .wav file
3527 NBAIO_Source *teeSource = mTeeSource.get();
3528 if (teeSource != NULL) {
3529 char teePath[64];
3530 struct timeval tv;
3531 gettimeofday(&tv, NULL);
3532 struct tm tm;
3533 localtime_r(&tv.tv_sec, &tm);
3534 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3535 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3536 if (teeFd >= 0) {
3537 char wavHeader[44];
3538 memcpy(wavHeader,
3539 "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",
3540 sizeof(wavHeader));
3541 NBAIO_Format format = teeSource->format();
3542 unsigned channelCount = Format_channelCount(format);
3543 ALOG_ASSERT(channelCount <= FCC_2);
3544 unsigned sampleRate = Format_sampleRate(format);
3545 wavHeader[22] = channelCount; // number of channels
3546 wavHeader[24] = sampleRate; // sample rate
3547 wavHeader[25] = sampleRate >> 8;
3548 wavHeader[32] = channelCount * 2; // block alignment
3549 write(teeFd, wavHeader, sizeof(wavHeader));
3550 size_t total = 0;
3551 bool firstRead = true;
3552 for (;;) {
3553#define TEE_SINK_READ 1024
3554 short buffer[TEE_SINK_READ * FCC_2];
3555 size_t count = TEE_SINK_READ;
3556 ssize_t actual = teeSource->read(buffer, count);
3557 bool wasFirstRead = firstRead;
3558 firstRead = false;
3559 if (actual <= 0) {
3560 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3561 continue;
3562 }
3563 break;
3564 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003565 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003566 write(teeFd, buffer, actual * channelCount * sizeof(short));
3567 total += actual;
3568 }
3569 lseek(teeFd, (off_t) 4, SEEK_SET);
3570 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3571 write(teeFd, &temp, sizeof(temp));
3572 lseek(teeFd, (off_t) 40, SEEK_SET);
3573 temp = total * channelCount * sizeof(short);
3574 write(teeFd, &temp, sizeof(temp));
3575 close(teeFd);
3576 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3577 } else {
3578 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3579 }
3580 }
3581
Glenn Kastenc15d6652012-05-30 14:52:57 -07003582 if (mAudioWatchdog != 0) {
3583 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3584 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3585 wdCopy.dump(fd);
3586 }
3587
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 return NO_ERROR;
3589}
3590
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003591uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592{
Glenn Kasten58912562012-04-03 10:45:00 -07003593 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594}
3595
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003596uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003597{
Glenn Kasten58912562012-04-03 10:45:00 -07003598 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003599}
3600
Glenn Kasten66fcab92012-02-24 14:59:21 -08003601void AudioFlinger::MixerThread::cacheParameters_l()
3602{
3603 PlaybackThread::cacheParameters_l();
3604
3605 // FIXME: Relaxed timing because of a certain device that can't meet latency
3606 // Should be reduced to 2x after the vendor fixes the driver issue
3607 // increase threshold again due to low power audio mode. The way this warning
3608 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003609 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003610}
3611
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003613AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3614 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003615 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003616 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618}
3619
3620AudioFlinger::DirectOutputThread::~DirectOutputThread()
3621{
3622}
3623
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003624AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3625 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003626)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003628 sp<Track> trackToRemove;
3629
Glenn Kastenfec279f2012-03-08 07:47:15 -08003630 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631
Glenn Kasten952eeb22012-03-06 11:30:57 -08003632 // find out which tracks need to be processed
3633 if (mActiveTracks.size() != 0) {
3634 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003635 // The track died recently
3636 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637
Glenn Kasten952eeb22012-03-06 11:30:57 -08003638 Track* const track = t.get();
3639 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640
Glenn Kasten952eeb22012-03-06 11:30:57 -08003641 // The first time a track is added we wait
3642 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003643 uint32_t minFrames;
3644 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3645 minFrames = mNormalFrameCount;
3646 } else {
3647 minFrames = 1;
3648 }
3649 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003650 !track->isPaused() && !track->isTerminated())
3651 {
3652 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653
Glenn Kasten952eeb22012-03-06 11:30:57 -08003654 if (track->mFillingUpStatus == Track::FS_FILLED) {
3655 track->mFillingUpStatus = Track::FS_ACTIVE;
3656 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003657 if (track->mState == TrackBase::RESUMING) {
3658 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003660 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003661
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 // compute volume for this track
3663 float left, right;
3664 if (track->isMuted() || mMasterMute || track->isPausing() ||
3665 mStreamTypes[track->streamType()].mute) {
3666 left = right = 0;
3667 if (track->isPausing()) {
3668 track->setPaused();
3669 }
3670 } else {
3671 float typeVolume = mStreamTypes[track->streamType()].volume;
3672 float v = mMasterVolume * typeVolume;
3673 uint32_t vlr = cblk->getVolumeLR();
3674 float v_clamped = v * (vlr & 0xFFFF);
3675 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3676 left = v_clamped/MAX_GAIN;
3677 v_clamped = v * (vlr >> 16);
3678 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3679 right = v_clamped/MAX_GAIN;
3680 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681
Glenn Kasten952eeb22012-03-06 11:30:57 -08003682 if (left != mLeftVolFloat || right != mRightVolFloat) {
3683 mLeftVolFloat = left;
3684 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 // Convert volumes from float to 8.24
3687 uint32_t vl = (uint32_t)(left * (1 << 24));
3688 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689
Glenn Kasten952eeb22012-03-06 11:30:57 -08003690 // Delegate volume control to effect in track effect chain if needed
3691 // only one effect chain can be present on DirectOutputThread, so if
3692 // there is one, the track is connected to it
3693 if (!mEffectChains.isEmpty()) {
3694 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003695 mEffectChains[0]->setVolume_l(&vl, &vr);
3696 left = (float)vl / (1 << 24);
3697 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003698 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003699 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 }
3701
3702 // reset retry count
3703 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003704 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003705 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003706 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003707 // clear effect chain input buffer if an active track underruns to avoid sending
3708 // previous audio buffer again to effects
3709 if (!mEffectChains.isEmpty()) {
3710 mEffectChains[0]->clearInputBuffer();
3711 }
3712
Glenn Kasten952eeb22012-03-06 11:30:57 -08003713 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003714 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3715 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 // We have consumed all the buffers of this track.
3717 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003718 // TODO: implement behavior for compressed audio
3719 size_t audioHALFrames =
3720 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3721 size_t framesWritten =
3722 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3723 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003724 if (track->isStopped()) {
3725 track->reset();
3726 }
Eric Laurenta011e352012-03-29 15:51:43 -07003727 trackToRemove = track;
3728 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003729 } else {
3730 // No buffers for this track. Give it a few chances to
3731 // fill a buffer, then remove it from active list.
3732 if (--(track->mRetryCount) <= 0) {
3733 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3734 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003736 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737 }
3738 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003739 }
3740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003742 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003743 // remove all the tracks that need to be...
3744 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003745 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 mActiveTracks.remove(trackToRemove);
3747 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003748 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 trackToRemove->sessionId());
3750 mEffectChains[0]->decActiveTrackCnt();
3751 }
3752 if (trackToRemove->isTerminated()) {
3753 removeTrack_l(trackToRemove);
3754 }
3755 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756
Glenn Kastenfec279f2012-03-08 07:47:15 -08003757 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003758}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759
Glenn Kasten000f0e32012-03-01 17:10:56 -08003760void AudioFlinger::DirectOutputThread::threadLoop_mix()
3761{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003762 AudioBufferProvider::Buffer buffer;
3763 size_t frameCount = mFrameCount;
3764 int8_t *curBuf = (int8_t *)mMixBuffer;
3765 // output audio to hardware
3766 while (frameCount) {
3767 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003768 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 if (CC_UNLIKELY(buffer.raw == NULL)) {
3770 memset(curBuf, 0, frameCount * mFrameSize);
3771 break;
3772 }
3773 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3774 frameCount -= buffer.frameCount;
3775 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003776 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003777 }
3778 sleepTime = 0;
3779 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003780 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003781
Glenn Kasten000f0e32012-03-01 17:10:56 -08003782}
3783
3784void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3785{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003787 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003788 sleepTime = activeSleepTime;
3789 } else {
3790 sleepTime = idleSleepTime;
3791 }
3792 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003793 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 sleepTime = 0;
3795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796}
3797
3798// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003799int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800{
3801 return 0;
3802}
3803
3804// deleteTrackName_l() must be called with ThreadBase::mLock held
3805void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3806{
3807}
3808
3809// checkForNewParameters_l() must be called with ThreadBase::mLock held
3810bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3811{
3812 bool reconfig = false;
3813
3814 while (!mNewParameters.isEmpty()) {
3815 status_t status = NO_ERROR;
3816 String8 keyValuePair = mNewParameters[0];
3817 AudioParameter param = AudioParameter(keyValuePair);
3818 int value;
3819
3820 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3821 // do not accept frame count changes if tracks are open as the track buffer
3822 // size depends on frame count and correct behavior would not be garantied
3823 // if frame count is changed after track creation
3824 if (!mTracks.isEmpty()) {
3825 status = INVALID_OPERATION;
3826 } else {
3827 reconfig = true;
3828 }
3829 }
3830 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003831 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003832 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003834 mOutput->stream->common.standby(&mOutput->stream->common);
3835 mStandby = true;
3836 mBytesWritten = 0;
3837 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003838 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 }
3840 if (status == NO_ERROR && reconfig) {
3841 readOutputParameters();
3842 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3843 }
3844 }
3845
3846 mNewParameters.removeAt(0);
3847
3848 mParamStatus = status;
3849 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003850 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3851 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003852 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 }
3854 return reconfig;
3855}
3856
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003857uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858{
3859 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003860 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003861 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003862 } else {
3863 time = 10000;
3864 }
3865 return time;
3866}
3867
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003868uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869{
3870 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003871 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003872 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873 } else {
3874 time = 10000;
3875 }
3876 return time;
3877}
3878
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003879uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003880{
3881 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003882 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003883 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3884 } else {
3885 time = 10000;
3886 }
3887 return time;
3888}
3889
Glenn Kasten66fcab92012-02-24 14:59:21 -08003890void AudioFlinger::DirectOutputThread::cacheParameters_l()
3891{
3892 PlaybackThread::cacheParameters_l();
3893
3894 // use shorter standby delay as on normal output to release
3895 // hardware resources as soon as possible
3896 standbyDelay = microseconds(activeSleepTime*2);
3897}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003898
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899// ----------------------------------------------------------------------------
3900
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003901AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003902 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003903 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3904 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 addOutputTrack(mainThread);
3907}
3908
3909AudioFlinger::DuplicatingThread::~DuplicatingThread()
3910{
3911 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3912 mOutputTracks[i]->destroy();
3913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914}
3915
Glenn Kasten000f0e32012-03-01 17:10:56 -08003916void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003918 // mix buffers...
3919 if (outputsReady(outputTracks)) {
3920 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3921 } else {
3922 memset(mMixBuffer, 0, mixBufferSize);
3923 }
3924 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003925 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003926 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003927}
3928
3929void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3930{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003931 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003932 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003933 sleepTime = activeSleepTime;
3934 } else {
3935 sleepTime = idleSleepTime;
3936 }
3937 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003938 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3939 writeFrames = mNormalFrameCount;
3940 memset(mMixBuffer, 0, mixBufferSize);
3941 } else {
3942 // flush remaining overflow buffers in output tracks
3943 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003944 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003945 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003946 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003947}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948
Glenn Kasten000f0e32012-03-01 17:10:56 -08003949void AudioFlinger::DuplicatingThread::threadLoop_write()
3950{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003951 for (size_t i = 0; i < outputTracks.size(); i++) {
3952 outputTracks[i]->write(mMixBuffer, writeFrames);
3953 }
3954 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003955}
Glenn Kasten688a6402012-02-29 07:57:06 -08003956
Glenn Kasten000f0e32012-03-01 17:10:56 -08003957void AudioFlinger::DuplicatingThread::threadLoop_standby()
3958{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003959 // DuplicatingThread implements standby by stopping all tracks
3960 for (size_t i = 0; i < outputTracks.size(); i++) {
3961 outputTracks[i]->stop();
3962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963}
3964
Glenn Kastenfa26a852012-03-06 11:28:04 -08003965void AudioFlinger::DuplicatingThread::saveOutputTracks()
3966{
3967 outputTracks = mOutputTracks;
3968}
3969
3970void AudioFlinger::DuplicatingThread::clearOutputTracks()
3971{
3972 outputTracks.clear();
3973}
3974
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3976{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003977 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003978 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003979 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003980 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 this,
3982 mSampleRate,
3983 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003984 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985 frameCount);
3986 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003987 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003989 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003990 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 }
3992}
3993
3994void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3995{
3996 Mutex::Autolock _l(mLock);
3997 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003998 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999 mOutputTracks[i]->destroy();
4000 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004001 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 return;
4003 }
4004 }
Steve Block3856b092011-10-20 11:56:00 +01004005 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006}
4007
Glenn Kasten438b0362012-03-06 11:24:48 -08004008// caller must hold mLock
4009void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010{
4011 mWaitTimeMs = UINT_MAX;
4012 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4013 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004014 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4016 if (waitTimeMs < mWaitTimeMs) {
4017 mWaitTimeMs = waitTimeMs;
4018 }
4019 }
4020 }
4021}
4022
4023
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004024bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025{
4026 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004027 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004029 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 return false;
4031 }
4032 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004033 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004035 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 return false;
4037 }
4038 }
4039 return true;
4040}
4041
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004042uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043{
4044 return (mWaitTimeMs * 1000) / 2;
4045}
4046
Glenn Kasten66fcab92012-02-24 14:59:21 -08004047void AudioFlinger::DuplicatingThread::cacheParameters_l()
4048{
4049 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4050 updateWaitTime_l();
4051
4052 MixerThread::cacheParameters_l();
4053}
4054
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055// ----------------------------------------------------------------------------
4056
4057// TrackBase constructor must be called with AudioFlinger::mLock held
4058AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004059 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 const sp<Client>& client,
4061 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004062 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004063 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 const sp<IMemory>& sharedBuffer,
4066 int sessionId)
4067 : RefBase(),
4068 mThread(thread),
4069 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004070 mCblk(NULL),
4071 // mBuffer
4072 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 mFrameCount(0),
4074 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004075 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004077 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004079 // mChannelCount
4080 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081{
Steve Block3856b092011-10-20 11:56:00 +01004082 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083
Steve Blockb8a80522011-12-20 16:23:08 +00004084 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004085 size_t size = sizeof(audio_track_cblk_t);
4086 uint8_t channelCount = popcount(channelMask);
4087 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4088 if (sharedBuffer == 0) {
4089 size += bufferSize;
4090 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004092 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 mCblkMemory = client->heap()->allocate(size);
4094 if (mCblkMemory != 0) {
4095 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004096 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 new(mCblk) audio_track_cblk_t();
4098 // clear all buffers
4099 mCblk->frameCount = frameCount;
4100 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004101// uncomment the following lines to quickly test 32-bit wraparound
4102// mCblk->user = 0xffff0000;
4103// mCblk->server = 0xffff0000;
4104// mCblk->userBase = 0xffff0000;
4105// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004106 mChannelCount = channelCount;
4107 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 if (sharedBuffer == 0) {
4109 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4110 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4111 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004112 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113 mCblk->flags = CBLK_UNDERRUN_ON;
4114 } else {
4115 mBuffer = sharedBuffer->pointer();
4116 }
4117 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4118 }
4119 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004120 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 client->heap()->dump("AudioTrack");
4122 return;
4123 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004124 } else {
4125 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004126 // construct the shared structure in-place.
4127 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;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004136 mChannelCount = channelCount;
4137 mChannelMask = channelMask;
4138 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4139 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4140 // Force underrun condition to avoid false underrun callback until first data is
4141 // written to buffer (other flags are cleared)
4142 mCblk->flags = CBLK_UNDERRUN_ON;
4143 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004144 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145}
4146
4147AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4148{
Glenn Kastena0d68332012-01-27 16:47:15 -08004149 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004150 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004152 } else {
4153 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 }
4155 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004156 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004157 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004158 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004160 // If the client's reference count drops to zero, the associated destructor
4161 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4162 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 mClient.clear();
4164 }
4165}
4166
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004167// AudioBufferProvider interface
4168// getNextBuffer() = 0;
4169// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4171{
Glenn Kastene0feee32011-12-13 11:53:26 -08004172 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004174 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004175 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 buffer->frameCount = 0;
4177}
4178
4179bool AudioFlinger::ThreadBase::TrackBase::step() {
4180 bool result;
4181 audio_track_cblk_t* cblk = this->cblk();
4182
4183 result = cblk->stepServer(mFrameCount);
4184 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004185 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004186 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 }
4188 return result;
4189}
4190
4191void AudioFlinger::ThreadBase::TrackBase::reset() {
4192 audio_track_cblk_t* cblk = this->cblk();
4193
4194 cblk->user = 0;
4195 cblk->server = 0;
4196 cblk->userBase = 0;
4197 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004198 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004199 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200}
4201
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4203 return (int)mCblk->sampleRate;
4204}
4205
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4207 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004208 size_t frameSize = cblk->frameSize;
4209 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4210 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211
4212 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004213 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4214 "TrackBase::getBuffer buffer out of range:\n"
4215 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4216 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004218 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219
4220 return bufferStart;
4221}
4222
Eric Laurenta011e352012-03-29 15:51:43 -07004223status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4224{
4225 mSyncEvents.add(event);
4226 return NO_ERROR;
4227}
4228
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229// ----------------------------------------------------------------------------
4230
4231// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4232AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004233 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004235 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004237 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004238 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 int frameCount,
4240 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004241 int sessionId,
4242 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004243 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004244 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004245 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004246 // mRetryCount initialized later when needed
4247 mSharedBuffer(sharedBuffer),
4248 mStreamType(streamType),
4249 mName(-1), // see note below
4250 mMainBuffer(thread->mixBuffer()),
4251 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004252 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004253 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004254 mFlags(flags),
4255 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004256 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004257 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258{
4259 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4261 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004262 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004263 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004264 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004265 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004266 if (mName < 0) {
4267 ALOGE("no more track names available");
4268 return;
4269 }
4270 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004271 if (flags & IAudioFlinger::TRACK_FAST) {
4272 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4273 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4274 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004275 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004276 // FIXME This is too eager. We allocate a fast track index before the
4277 // fast track becomes active. Since fast tracks are a scarce resource,
4278 // this means we are potentially denying other more important fast tracks from
4279 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004280 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004281 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004282 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004283 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004284 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004287 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288}
4289
4290AudioFlinger::PlaybackThread::Track::~Track()
4291{
Steve Block3856b092011-10-20 11:56:00 +01004292 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 sp<ThreadBase> thread = mThread.promote();
4294 if (thread != 0) {
4295 Mutex::Autolock _l(thread->mLock);
4296 mState = TERMINATED;
4297 }
4298}
4299
4300void AudioFlinger::PlaybackThread::Track::destroy()
4301{
4302 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4303 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004304 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004305 // we must acquire a strong reference on this Track before locking mLock
4306 // here so that the destructor is called only when exiting this function.
4307 // On the other hand, as long as Track::destroy() is only called by
4308 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4309 // this Track with its member mTrack.
4310 sp<Track> keep(this);
4311 { // scope for mLock
4312 sp<ThreadBase> thread = mThread.promote();
4313 if (thread != 0) {
4314 if (!isOutputTrack()) {
4315 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004316 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004317
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004318#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004319 // to track the speaker usage
4320 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004321#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 }
4323 AudioSystem::releaseOutput(thread->id());
4324 }
4325 Mutex::Autolock _l(thread->mLock);
4326 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4327 playbackThread->destroyTrack_l(this);
4328 }
4329 }
4330}
4331
Glenn Kasten288ed212012-04-25 17:52:27 -07004332/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4333{
Glenn Kastene213c862012-04-25 13:46:15 -07004334 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 -07004335 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004336}
4337
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4339{
Glenn Kasten83d86532012-01-17 14:39:34 -08004340 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004341 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004342 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004343 } else {
4344 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4345 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004346 track_state state = mState;
4347 char stateChar;
4348 switch (state) {
4349 case IDLE:
4350 stateChar = 'I';
4351 break;
4352 case TERMINATED:
4353 stateChar = 'T';
4354 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004355 case STOPPING_1:
4356 stateChar = 's';
4357 break;
4358 case STOPPING_2:
4359 stateChar = '5';
4360 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004361 case STOPPED:
4362 stateChar = 'S';
4363 break;
4364 case RESUMING:
4365 stateChar = 'R';
4366 break;
4367 case ACTIVE:
4368 stateChar = 'A';
4369 break;
4370 case PAUSING:
4371 stateChar = 'p';
4372 break;
4373 case PAUSED:
4374 stateChar = 'P';
4375 break;
Eric Laurent29864602012-05-08 18:57:51 -07004376 case FLUSHED:
4377 stateChar = 'F';
4378 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004379 default:
4380 stateChar = '?';
4381 break;
4382 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004383 char nowInUnderrun;
4384 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4385 case UNDERRUN_FULL:
4386 nowInUnderrun = ' ';
4387 break;
4388 case UNDERRUN_PARTIAL:
4389 nowInUnderrun = '<';
4390 break;
4391 case UNDERRUN_EMPTY:
4392 nowInUnderrun = '*';
4393 break;
4394 default:
4395 nowInUnderrun = '?';
4396 break;
4397 }
Glenn Kastene213c862012-04-25 13:46:15 -07004398 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4399 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004400 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401 mStreamType,
4402 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004403 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 mSessionId,
4405 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004406 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004407 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408 mMute,
4409 mFillingUpStatus,
4410 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004411 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4412 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 mCblk->server,
4414 mCblk->user,
4415 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004416 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004417 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004418 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004419 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420}
4421
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004422// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004423status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004424 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004426 audio_track_cblk_t* cblk = this->cblk();
4427 uint32_t framesReady;
4428 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004430 // Check if last stepServer failed, try to step now
4431 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004432 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4433 // Since the fast mixer is higher priority than client callback thread,
4434 // it does not result in priority inversion for client.
4435 // But a non-blocking solution would be preferable to avoid
4436 // fast mixer being unable to tryLock(), and
4437 // to avoid the extra context switches if the client wakes up,
4438 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004439 if (!step()) goto getNextBuffer_exit;
4440 ALOGV("stepServer recovered");
4441 mStepServerFailed = false;
4442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443
Glenn Kasten288ed212012-04-25 17:52:27 -07004444 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004445 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 uint32_t s = cblk->server;
4449 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4450
4451 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4452 if (framesReq > framesReady) {
4453 framesReq = framesReady;
4454 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004455 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004456 framesReq = bufferEnd - s;
4457 }
4458
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004459 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004460 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463
4464getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004465 buffer->raw = NULL;
4466 buffer->frameCount = 0;
4467 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4468 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469}
4470
Glenn Kasten288ed212012-04-25 17:52:27 -07004471// Note that framesReady() takes a mutex on the control block using tryLock().
4472// This could result in priority inversion if framesReady() is called by the normal mixer,
4473// as the normal mixer thread runs at lower
4474// priority than the client's callback thread: there is a short window within framesReady()
4475// during which the normal mixer could be preempted, and the client callback would block.
4476// Another problem can occur if framesReady() is called by the fast mixer:
4477// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4478// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4479size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004480 return mCblk->framesReady();
4481}
4482
Glenn Kasten288ed212012-04-25 17:52:27 -07004483// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004485 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486
John Grossman4ff14ba2012-02-08 16:37:41 -08004487 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4489 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004490 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 return true;
4492 }
4493 return false;
4494}
4495
Glenn Kasten3acbd052012-02-28 10:39:56 -08004496status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004497 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498{
4499 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004500 ALOGV("start(%d), calling pid %d session %d",
4501 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004502
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 sp<ThreadBase> thread = mThread.promote();
4504 if (thread != 0) {
4505 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004506 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507 // here the track could be either new, or restarted
4508 // in both cases "unstop" the track
4509 if (mState == PAUSED) {
4510 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004511 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 } else {
4513 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004514 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 }
4516
4517 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4518 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004519 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004521
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004522#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004523 // to track the speaker usage
4524 if (status == NO_ERROR) {
4525 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4526 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004527#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 }
4529 if (status == NO_ERROR) {
4530 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4531 playbackThread->addTrack_l(this);
4532 } else {
4533 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004534 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 }
4536 } else {
4537 status = BAD_VALUE;
4538 }
4539 return status;
4540}
4541
4542void AudioFlinger::PlaybackThread::Track::stop()
4543{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004544 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 sp<ThreadBase> thread = mThread.promote();
4546 if (thread != 0) {
4547 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004548 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004549 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 // If the track is not active (PAUSED and buffers full), flush buffers
4551 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4552 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4553 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004554 mState = STOPPED;
4555 } else if (!isFastTrack()) {
4556 mState = STOPPED;
4557 } else {
4558 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4559 // and then to STOPPED and reset() when presentation is complete
4560 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004562 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 }
4564 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4565 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004566 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004568
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004569#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004570 // to track the speaker usage
4571 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004572#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 }
4574 }
4575}
4576
4577void AudioFlinger::PlaybackThread::Track::pause()
4578{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004579 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 sp<ThreadBase> thread = mThread.promote();
4581 if (thread != 0) {
4582 Mutex::Autolock _l(thread->mLock);
4583 if (mState == ACTIVE || mState == RESUMING) {
4584 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004585 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 if (!isOutputTrack()) {
4587 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004588 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004590
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004591#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004592 // to track the speaker usage
4593 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004594#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 }
4596 }
4597 }
4598}
4599
4600void AudioFlinger::PlaybackThread::Track::flush()
4601{
Steve Block3856b092011-10-20 11:56:00 +01004602 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 sp<ThreadBase> thread = mThread.promote();
4604 if (thread != 0) {
4605 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004606 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4607 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 return;
4609 }
4610 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004611 // FLUSHED state
4612 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004613 // do not reset the track if it is still in the process of being stopped or paused.
4614 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004615 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004616 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004617 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4618 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4619 reset();
4620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 }
4622}
4623
4624void AudioFlinger::PlaybackThread::Track::reset()
4625{
4626 // Do not reset twice to avoid discarding data written just after a flush and before
4627 // the audioflinger thread detects the track is stopped.
4628 if (!mResetDone) {
4629 TrackBase::reset();
4630 // Force underrun condition to avoid false underrun callback until first data is
4631 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004632 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4633 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 mFillingUpStatus = FS_FILLING;
4635 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004636 if (mState == FLUSHED) {
4637 mState = IDLE;
4638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 }
4640}
4641
4642void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4643{
4644 mMute = muted;
4645}
4646
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4648{
4649 status_t status = DEAD_OBJECT;
4650 sp<ThreadBase> thread = mThread.promote();
4651 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004652 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004653 sp<AudioFlinger> af = mClient->audioFlinger();
4654
4655 Mutex::Autolock _l(af->mLock);
4656
4657 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004658
Eric Laurent109347d2012-07-02 12:31:03 -07004659 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004660 Mutex::Autolock _dl(playbackThread->mLock);
4661 Mutex::Autolock _sl(srcThread->mLock);
4662 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4663 if (chain == 0) {
4664 return INVALID_OPERATION;
4665 }
4666
4667 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4668 if (effect == 0) {
4669 return INVALID_OPERATION;
4670 }
4671 srcThread->removeEffect_l(effect);
4672 playbackThread->addEffect_l(effect);
4673 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4674 if (effect->state() == EffectModule::ACTIVE ||
4675 effect->state() == EffectModule::STOPPING) {
4676 effect->start();
4677 }
4678
4679 sp<EffectChain> dstChain = effect->chain().promote();
4680 if (dstChain == 0) {
4681 srcThread->addEffect_l(effect);
4682 return INVALID_OPERATION;
4683 }
4684 AudioSystem::unregisterEffect(effect->id());
4685 AudioSystem::registerEffect(&effect->desc(),
4686 srcThread->id(),
4687 dstChain->strategy(),
4688 AUDIO_SESSION_OUTPUT_MIX,
4689 effect->id());
4690 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004691 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 }
4693 return status;
4694}
4695
4696void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4697{
4698 mAuxEffectId = EffectId;
4699 mAuxBuffer = buffer;
4700}
4701
Eric Laurenta011e352012-03-29 15:51:43 -07004702bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4703 size_t audioHalFrames)
4704{
4705 // a track is considered presented when the total number of frames written to audio HAL
4706 // corresponds to the number of frames written when presentationComplete() is called for the
4707 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4708 if (mPresentationCompleteFrames == 0) {
4709 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4710 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4711 mPresentationCompleteFrames, audioHalFrames);
4712 }
4713 if (framesWritten >= mPresentationCompleteFrames) {
4714 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4715 mSessionId, framesWritten);
4716 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004717 return true;
4718 }
4719 return false;
4720}
4721
4722void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4723{
4724 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4725 if (mSyncEvents[i]->type() == type) {
4726 mSyncEvents[i]->trigger();
4727 mSyncEvents.removeAt(i);
4728 i--;
4729 }
4730 }
4731}
4732
Glenn Kasten58912562012-04-03 10:45:00 -07004733// implement VolumeBufferProvider interface
4734
4735uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4736{
4737 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4738 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4739 uint32_t vlr = mCblk->getVolumeLR();
4740 uint32_t vl = vlr & 0xFFFF;
4741 uint32_t vr = vlr >> 16;
4742 // track volumes come from shared memory, so can't be trusted and must be clamped
4743 if (vl > MAX_GAIN_INT) {
4744 vl = MAX_GAIN_INT;
4745 }
4746 if (vr > MAX_GAIN_INT) {
4747 vr = MAX_GAIN_INT;
4748 }
4749 // now apply the cached master volume and stream type volume;
4750 // this is trusted but lacks any synchronization or barrier so may be stale
4751 float v = mCachedVolume;
4752 vl *= v;
4753 vr *= v;
4754 // re-combine into U4.16
4755 vlr = (vr << 16) | (vl & 0xFFFF);
4756 // FIXME look at mute, pause, and stop flags
4757 return vlr;
4758}
Eric Laurenta011e352012-03-29 15:51:43 -07004759
Eric Laurent29864602012-05-08 18:57:51 -07004760status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4761{
4762 if (mState == TERMINATED || mState == PAUSED ||
4763 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4764 (mState == STOPPED)))) {
4765 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4766 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4767 event->cancel();
4768 return INVALID_OPERATION;
4769 }
4770 TrackBase::setSyncEvent(event);
4771 return NO_ERROR;
4772}
4773
John Grossman4ff14ba2012-02-08 16:37:41 -08004774// timed audio tracks
4775
4776sp<AudioFlinger::PlaybackThread::TimedTrack>
4777AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004778 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004779 const sp<Client>& client,
4780 audio_stream_type_t streamType,
4781 uint32_t sampleRate,
4782 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004783 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004784 int frameCount,
4785 const sp<IMemory>& sharedBuffer,
4786 int sessionId) {
4787 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004788 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004789
Glenn Kastena0356762012-03-19 10:38:51 -07004790 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004791 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4792 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004793}
4794
4795AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004796 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004797 const sp<Client>& client,
4798 audio_stream_type_t streamType,
4799 uint32_t sampleRate,
4800 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004801 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004802 int frameCount,
4803 const sp<IMemory>& sharedBuffer,
4804 int sessionId)
4805 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004806 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004807 mQueueHeadInFlight(false),
4808 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004809 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004810 mTimedSilenceBuffer(NULL),
4811 mTimedSilenceBufferSize(0),
4812 mTimedAudioOutputOnTime(false),
4813 mMediaTimeTransformValid(false)
4814{
4815 LocalClock lc;
4816 mLocalTimeFreq = lc.getLocalFreq();
4817
4818 mLocalTimeToSampleTransform.a_zero = 0;
4819 mLocalTimeToSampleTransform.b_zero = 0;
4820 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4821 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4822 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4823 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004824
4825 mMediaTimeToSampleTransform.a_zero = 0;
4826 mMediaTimeToSampleTransform.b_zero = 0;
4827 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4828 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4829 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4830 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004831}
4832
4833AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4834 mClient->releaseTimedTrack();
4835 delete [] mTimedSilenceBuffer;
4836}
4837
4838status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4839 size_t size, sp<IMemory>* buffer) {
4840
4841 Mutex::Autolock _l(mTimedBufferQueueLock);
4842
4843 trimTimedBufferQueue_l();
4844
4845 // lazily initialize the shared memory heap for timed buffers
4846 if (mTimedMemoryDealer == NULL) {
4847 const int kTimedBufferHeapSize = 512 << 10;
4848
4849 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4850 "AudioFlingerTimed");
4851 if (mTimedMemoryDealer == NULL)
4852 return NO_MEMORY;
4853 }
4854
4855 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4856 if (newBuffer == NULL) {
4857 newBuffer = mTimedMemoryDealer->allocate(size);
4858 if (newBuffer == NULL)
4859 return NO_MEMORY;
4860 }
4861
4862 *buffer = newBuffer;
4863 return NO_ERROR;
4864}
4865
4866// caller must hold mTimedBufferQueueLock
4867void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4868 int64_t mediaTimeNow;
4869 {
4870 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4871 if (!mMediaTimeTransformValid)
4872 return;
4873
4874 int64_t targetTimeNow;
4875 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4876 ? mCCHelper.getCommonTime(&targetTimeNow)
4877 : mCCHelper.getLocalTime(&targetTimeNow);
4878
4879 if (OK != res)
4880 return;
4881
4882 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4883 &mediaTimeNow)) {
4884 return;
4885 }
4886 }
4887
John Grossman1c345192012-03-27 14:00:17 -07004888 size_t trimEnd;
4889 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004890 int64_t bufEnd;
4891
John Grossmanc95cfbb2012-04-12 11:53:11 -07004892 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4893 // We have a next buffer. Just use its PTS as the PTS of the frame
4894 // following the last frame in this buffer. If the stream is sparse
4895 // (ie, there are deliberate gaps left in the stream which should be
4896 // filled with silence by the TimedAudioTrack), then this can result
4897 // in one extra buffer being left un-trimmed when it could have
4898 // been. In general, this is not typical, and we would rather
4899 // optimized away the TS calculation below for the more common case
4900 // where PTSes are contiguous.
4901 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4902 } else {
4903 // We have no next buffer. Compute the PTS of the frame following
4904 // the last frame in this buffer by computing the duration of of
4905 // this frame in media time units and adding it to the PTS of the
4906 // buffer.
4907 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4908 / mCblk->frameSize;
4909
4910 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4911 &bufEnd)) {
4912 ALOGE("Failed to convert frame count of %lld to media time"
4913 " duration" " (scale factor %d/%u) in %s",
4914 frameCount,
4915 mMediaTimeToSampleTransform.a_to_b_numer,
4916 mMediaTimeToSampleTransform.a_to_b_denom,
4917 __PRETTY_FUNCTION__);
4918 break;
4919 }
4920 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004921 }
John Grossman9fbdee12012-03-26 17:51:46 -07004922
4923 if (bufEnd > mediaTimeNow)
4924 break;
4925
4926 // Is the buffer we want to use in the middle of a mix operation right
4927 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4928 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004929 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004930 mTrimQueueHeadOnRelease = true;
4931 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004932 }
4933
John Grossman9fbdee12012-03-26 17:51:46 -07004934 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004935 if (trimStart < trimEnd) {
4936 // Update the bookkeeping for framesReady()
4937 for (size_t i = trimStart; i < trimEnd; ++i) {
4938 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4939 }
4940
4941 // Now actually remove the buffers from the queue.
4942 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004943 }
4944}
4945
John Grossman1c345192012-03-27 14:00:17 -07004946void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4947 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004948 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4949 "%s called (reason \"%s\"), but timed buffer queue has no"
4950 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004951
4952 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4953 mTimedBufferQueue.removeAt(0);
4954}
4955
4956void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4957 const TimedBuffer& buf,
4958 const char* logTag) {
4959 uint32_t bufBytes = buf.buffer()->size();
4960 uint32_t consumedAlready = buf.position();
4961
Eric Laurentb388e532012-04-14 13:32:48 -07004962 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004963 "Bad bookkeeping while updating frames pending. Timed buffer is"
4964 " only %u bytes long, but claims to have consumed %u"
4965 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004966 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004967
4968 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004969 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4970 "Bad bookkeeping while updating frames pending. Should have at"
4971 " least %u queued frames, but we think we have only %u. (update"
4972 " reason: \"%s\")",
4973 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004974
4975 mFramesPendingInQueue -= bufFrames;
4976}
4977
John Grossman4ff14ba2012-02-08 16:37:41 -08004978status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4979 const sp<IMemory>& buffer, int64_t pts) {
4980
4981 {
4982 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4983 if (!mMediaTimeTransformValid)
4984 return INVALID_OPERATION;
4985 }
4986
4987 Mutex::Autolock _l(mTimedBufferQueueLock);
4988
John Grossman1c345192012-03-27 14:00:17 -07004989 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4990 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004991 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4992
4993 return NO_ERROR;
4994}
4995
4996status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4997 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4998
John Grossman1c345192012-03-27 14:00:17 -07004999 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5000 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5001 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005002
5003 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5004 target == TimedAudioTrack::COMMON_TIME)) {
5005 return BAD_VALUE;
5006 }
5007
5008 Mutex::Autolock lock(mMediaTimeTransformLock);
5009 mMediaTimeTransform = xform;
5010 mMediaTimeTransformTarget = target;
5011 mMediaTimeTransformValid = true;
5012
5013 return NO_ERROR;
5014}
5015
5016#define min(a, b) ((a) < (b) ? (a) : (b))
5017
5018// implementation of getNextBuffer for tracks whose buffers have timestamps
5019status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5020 AudioBufferProvider::Buffer* buffer, int64_t pts)
5021{
5022 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005023 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005024 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005025 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005026 return INVALID_OPERATION;
5027 }
5028
John Grossman4ff14ba2012-02-08 16:37:41 -08005029 Mutex::Autolock _l(mTimedBufferQueueLock);
5030
John Grossman9fbdee12012-03-26 17:51:46 -07005031 ALOG_ASSERT(!mQueueHeadInFlight,
5032 "getNextBuffer called without releaseBuffer!");
5033
John Grossman4ff14ba2012-02-08 16:37:41 -08005034 while (true) {
5035
5036 // if we have no timed buffers, then fail
5037 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005038 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005039 buffer->frameCount = 0;
5040 return NOT_ENOUGH_DATA;
5041 }
5042
5043 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5044
5045 // calculate the PTS of the head of the timed buffer queue expressed in
5046 // local time
5047 int64_t headLocalPTS;
5048 {
5049 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5050
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005051 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005052
5053 if (mMediaTimeTransform.a_to_b_denom == 0) {
5054 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005055 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005056 return NO_ERROR;
5057 }
5058
5059 int64_t transformedPTS;
5060 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5061 &transformedPTS)) {
5062 // the transform failed. this shouldn't happen, but if it does
5063 // then just drop this buffer
5064 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005065 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005066 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005067 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005068 return NO_ERROR;
5069 }
5070
5071 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5072 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5073 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005074 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005075 buffer->frameCount = 0;
5076 return INVALID_OPERATION;
5077 }
5078 } else {
5079 headLocalPTS = transformedPTS;
5080 }
5081 }
5082
5083 // adjust the head buffer's PTS to reflect the portion of the head buffer
5084 // that has already been consumed
5085 int64_t effectivePTS = headLocalPTS +
5086 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5087
5088 // Calculate the delta in samples between the head of the input buffer
5089 // queue and the start of the next output buffer that will be written.
5090 // If the transformation fails because of over or underflow, it means
5091 // that the sample's position in the output stream is so far out of
5092 // whack that it should just be dropped.
5093 int64_t sampleDelta;
5094 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5095 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005096 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5097 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005098 continue;
5099 }
5100 if (!mLocalTimeToSampleTransform.doForwardTransform(
5101 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005102 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005103 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005104 continue;
5105 }
5106
John Grossman1c345192012-03-27 14:00:17 -07005107 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5108 " sampleDelta=[%d.%08x]",
5109 head.pts(), head.position(), pts,
5110 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5111 + (sampleDelta >> 32)),
5112 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005113
5114 // if the delta between the ideal placement for the next input sample and
5115 // the current output position is within this threshold, then we will
5116 // concatenate the next input samples to the previous output
5117 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005118 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005119
5120 // if this is the first buffer of audio that we're emitting from this track
5121 // then it should be almost exactly on time.
5122 const int64_t kSampleStartupThreshold = 1LL << 32;
5123
5124 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005125 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005126 // the next input is close enough to being on time, so concatenate it
5127 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005128 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005129
John Grossman1c345192012-03-27 14:00:17 -07005130 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5131 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005132 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005133 }
5134
5135 // Looks like our output is not on time. Reset our on timed status.
5136 // Next time we mix samples from our input queue, then should be within
5137 // the StartupThreshold.
5138 mTimedAudioOutputOnTime = false;
5139 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005140 // the gap between the current output position and the proper start of
5141 // the next input sample is too big, so fill it with silence
5142 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5143
John Grossman9fbdee12012-03-26 17:51:46 -07005144 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5146 return NO_ERROR;
5147 } else {
5148 // the next input sample is late
5149 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5150 size_t onTimeSamplePosition =
5151 head.position() + lateFrames * mCblk->frameSize;
5152
5153 if (onTimeSamplePosition > head.buffer()->size()) {
5154 // all the remaining samples in the head are too late, so
5155 // drop it and move on
5156 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005157 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005158 continue;
5159 } else {
5160 // skip over the late samples
5161 head.setPosition(onTimeSamplePosition);
5162
5163 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005164 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005165
5166 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5167 return NO_ERROR;
5168 }
5169 }
5170 }
5171}
5172
5173// Yield samples from the timed buffer queue head up to the given output
5174// buffer's capacity.
5175//
5176// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005177void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005178 AudioBufferProvider::Buffer* buffer) {
5179
5180 const TimedBuffer& head = mTimedBufferQueue[0];
5181
5182 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5183 head.position());
5184
5185 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5186 mCblk->frameSize);
5187 size_t framesRequested = buffer->frameCount;
5188 buffer->frameCount = min(framesLeftInHead, framesRequested);
5189
John Grossman9fbdee12012-03-26 17:51:46 -07005190 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005191 mTimedAudioOutputOnTime = true;
5192}
5193
5194// Yield samples of silence up to the given output buffer's capacity
5195//
5196// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005197void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005198 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5199
5200 // lazily allocate a buffer filled with silence
5201 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5202 delete [] mTimedSilenceBuffer;
5203 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5204 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5205 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5206 }
5207
5208 buffer->raw = mTimedSilenceBuffer;
5209 size_t framesRequested = buffer->frameCount;
5210 buffer->frameCount = min(numFrames, framesRequested);
5211
5212 mTimedAudioOutputOnTime = false;
5213}
5214
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005215// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005216void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5217 AudioBufferProvider::Buffer* buffer) {
5218
5219 Mutex::Autolock _l(mTimedBufferQueueLock);
5220
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005221 // If the buffer which was just released is part of the buffer at the head
5222 // of the queue, be sure to update the amt of the buffer which has been
5223 // consumed. If the buffer being returned is not part of the head of the
5224 // queue, its either because the buffer is part of the silence buffer, or
5225 // because the head of the timed queue was trimmed after the mixer called
5226 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005227 if (buffer->raw == mTimedSilenceBuffer) {
5228 ALOG_ASSERT(!mQueueHeadInFlight,
5229 "Queue head in flight during release of silence buffer!");
5230 goto done;
5231 }
5232
5233 ALOG_ASSERT(mQueueHeadInFlight,
5234 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5235 " head in flight.");
5236
5237 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005238 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005239
5240 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005241 void* end = reinterpret_cast<void*>(
5242 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5243 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005244
John Grossman9fbdee12012-03-26 17:51:46 -07005245 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5246 "released buffer not within the head of the timed buffer"
5247 " queue; qHead = [%p, %p], released buffer = %p",
5248 start, end, buffer->raw);
5249
5250 head.setPosition(head.position() +
5251 (buffer->frameCount * mCblk->frameSize));
5252 mQueueHeadInFlight = false;
5253
John Grossman1c345192012-03-27 14:00:17 -07005254 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5255 "Bad bookkeeping during releaseBuffer! Should have at"
5256 " least %u queued frames, but we think we have only %u",
5257 buffer->frameCount, mFramesPendingInQueue);
5258
5259 mFramesPendingInQueue -= buffer->frameCount;
5260
John Grossman9fbdee12012-03-26 17:51:46 -07005261 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5262 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005263 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005264 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 }
John Grossman9fbdee12012-03-26 17:51:46 -07005266 } else {
5267 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5268 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005269 }
5270
John Grossman9fbdee12012-03-26 17:51:46 -07005271done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005272 buffer->raw = 0;
5273 buffer->frameCount = 0;
5274}
5275
Glenn Kasten288ed212012-04-25 17:52:27 -07005276size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005277 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005278 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005279}
5280
5281AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5282 : mPTS(0), mPosition(0) {}
5283
5284AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5285 const sp<IMemory>& buffer, int64_t pts)
5286 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5287
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288// ----------------------------------------------------------------------------
5289
5290// RecordTrack constructor must be called with AudioFlinger::mLock held
5291AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005292 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293 const sp<Client>& client,
5294 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005295 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005296 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 int sessionId)
5299 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005300 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005301 mOverflow(false)
5302{
5303 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005304 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5305 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5306 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5307 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5308 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5309 } else {
5310 mCblk->frameSize = sizeof(int8_t);
5311 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312 }
5313}
5314
5315AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5316{
5317 sp<ThreadBase> thread = mThread.promote();
5318 if (thread != 0) {
5319 AudioSystem::releaseInput(thread->id());
5320 }
5321}
5322
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005323// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005324status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325{
5326 audio_track_cblk_t* cblk = this->cblk();
5327 uint32_t framesAvail;
5328 uint32_t framesReq = buffer->frameCount;
5329
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005330 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005331 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005333 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005334 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335 }
5336
5337 framesAvail = cblk->framesAvailable_l();
5338
Glenn Kastenf6b16782011-12-15 09:51:17 -08005339 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 uint32_t s = cblk->server;
5341 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5342
5343 if (framesReq > framesAvail) {
5344 framesReq = framesAvail;
5345 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005346 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 framesReq = bufferEnd - s;
5348 }
5349
5350 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 buffer->frameCount = framesReq;
5352 return NO_ERROR;
5353 }
5354
5355getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005356 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 buffer->frameCount = 0;
5358 return NOT_ENOUGH_DATA;
5359}
5360
Glenn Kasten3acbd052012-02-28 10:39:56 -08005361status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005362 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005363{
5364 sp<ThreadBase> thread = mThread.promote();
5365 if (thread != 0) {
5366 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005367 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 } else {
5369 return BAD_VALUE;
5370 }
5371}
5372
5373void AudioFlinger::RecordThread::RecordTrack::stop()
5374{
5375 sp<ThreadBase> thread = mThread.promote();
5376 if (thread != 0) {
5377 RecordThread *recordThread = (RecordThread *)thread.get();
5378 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005379 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005380 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005381 // read from buffer
5382 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 }
5384}
5385
5386void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5387{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005388 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005389 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005391 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 mSessionId,
5393 mFrameCount,
5394 mState,
5395 mCblk->sampleRate,
5396 mCblk->server,
5397 mCblk->user);
5398}
5399
5400
5401// ----------------------------------------------------------------------------
5402
5403AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005404 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405 DuplicatingThread *sourceThread,
5406 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005407 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005408 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005410 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5411 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 mActive(false), mSourceThread(sourceThread)
5413{
5414
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 if (mCblk != NULL) {
5416 mCblk->flags |= CBLK_DIRECTION_OUT;
5417 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 mOutBuffer.frameCount = 0;
5419 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005420 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005421 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5422 mCblk, mBuffer, mCblk->buffers,
5423 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005425 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 }
5427}
5428
5429AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5430{
5431 clearBufferQueue();
5432}
5433
Glenn Kasten3acbd052012-02-28 10:39:56 -08005434status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005435 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005437 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 if (status != NO_ERROR) {
5439 return status;
5440 }
5441
5442 mActive = true;
5443 mRetryCount = 127;
5444 return status;
5445}
5446
5447void AudioFlinger::PlaybackThread::OutputTrack::stop()
5448{
5449 Track::stop();
5450 clearBufferQueue();
5451 mOutBuffer.frameCount = 0;
5452 mActive = false;
5453}
5454
5455bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5456{
5457 Buffer *pInBuffer;
5458 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005459 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 bool outputBufferFull = false;
5461 inBuffer.frameCount = frames;
5462 inBuffer.i16 = data;
5463
5464 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5465
5466 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005467 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 sp<ThreadBase> thread = mThread.promote();
5469 if (thread != 0) {
5470 MixerThread *mixerThread = (MixerThread *)thread.get();
5471 if (mCblk->frameCount > frames){
5472 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5473 uint32_t startFrames = (mCblk->frameCount - frames);
5474 pInBuffer = new Buffer;
5475 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5476 pInBuffer->frameCount = startFrames;
5477 pInBuffer->i16 = pInBuffer->mBuffer;
5478 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5479 mBufferQueue.add(pInBuffer);
5480 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005481 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 }
5483 }
5484 }
5485 }
5486
5487 while (waitTimeLeftMs) {
5488 // First write pending buffers, then new data
5489 if (mBufferQueue.size()) {
5490 pInBuffer = mBufferQueue.itemAt(0);
5491 } else {
5492 pInBuffer = &inBuffer;
5493 }
5494
5495 if (pInBuffer->frameCount == 0) {
5496 break;
5497 }
5498
5499 if (mOutBuffer.frameCount == 0) {
5500 mOutBuffer.frameCount = pInBuffer->frameCount;
5501 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005502 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005503 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 outputBufferFull = true;
5505 break;
5506 }
5507 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5508 if (waitTimeLeftMs >= waitTimeMs) {
5509 waitTimeLeftMs -= waitTimeMs;
5510 } else {
5511 waitTimeLeftMs = 0;
5512 }
5513 }
5514
5515 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5516 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5517 mCblk->stepUser(outFrames);
5518 pInBuffer->frameCount -= outFrames;
5519 pInBuffer->i16 += outFrames * channelCount;
5520 mOutBuffer.frameCount -= outFrames;
5521 mOutBuffer.i16 += outFrames * channelCount;
5522
5523 if (pInBuffer->frameCount == 0) {
5524 if (mBufferQueue.size()) {
5525 mBufferQueue.removeAt(0);
5526 delete [] pInBuffer->mBuffer;
5527 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005528 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 } else {
5530 break;
5531 }
5532 }
5533 }
5534
5535 // If we could not write all frames, allocate a buffer and queue it for next time.
5536 if (inBuffer.frameCount) {
5537 sp<ThreadBase> thread = mThread.promote();
5538 if (thread != 0 && !thread->standby()) {
5539 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5540 pInBuffer = new Buffer;
5541 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5542 pInBuffer->frameCount = inBuffer.frameCount;
5543 pInBuffer->i16 = pInBuffer->mBuffer;
5544 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5545 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005546 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005548 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 }
5550 }
5551 }
5552
5553 // Calling write() with a 0 length buffer, means that no more data will be written:
5554 // If no more buffers are pending, fill output track buffer to make sure it is started
5555 // by output mixer.
5556 if (frames == 0 && mBufferQueue.size() == 0) {
5557 if (mCblk->user < mCblk->frameCount) {
5558 frames = mCblk->frameCount - mCblk->user;
5559 pInBuffer = new Buffer;
5560 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5561 pInBuffer->frameCount = frames;
5562 pInBuffer->i16 = pInBuffer->mBuffer;
5563 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5564 mBufferQueue.add(pInBuffer);
5565 } else if (mActive) {
5566 stop();
5567 }
5568 }
5569
5570 return outputBufferFull;
5571}
5572
5573status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5574{
5575 int active;
5576 status_t result;
5577 audio_track_cblk_t* cblk = mCblk;
5578 uint32_t framesReq = buffer->frameCount;
5579
Steve Block3856b092011-10-20 11:56:00 +01005580// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 buffer->frameCount = 0;
5582
5583 uint32_t framesAvail = cblk->framesAvailable();
5584
5585
5586 if (framesAvail == 0) {
5587 Mutex::Autolock _l(cblk->lock);
5588 goto start_loop_here;
5589 while (framesAvail == 0) {
5590 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005591 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005592 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005593 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 }
5595 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5596 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005597 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 }
5599 // read the server count again
5600 start_loop_here:
5601 framesAvail = cblk->framesAvailable_l();
5602 }
5603 }
5604
5605// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005606// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607// }
5608
5609 if (framesReq > framesAvail) {
5610 framesReq = framesAvail;
5611 }
5612
5613 uint32_t u = cblk->user;
5614 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5615
Marco Nelissena1472d92012-03-30 14:36:54 -07005616 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 framesReq = bufferEnd - u;
5618 }
5619
5620 buffer->frameCount = framesReq;
5621 buffer->raw = (void *)cblk->buffer(u);
5622 return NO_ERROR;
5623}
5624
5625
5626void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5627{
5628 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629
5630 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005631 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 delete [] pBuffer->mBuffer;
5633 delete pBuffer;
5634 }
5635 mBufferQueue.clear();
5636}
5637
5638// ----------------------------------------------------------------------------
5639
5640AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5641 : RefBase(),
5642 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005643 // 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 -07005644 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005645 mPid(pid),
5646 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647{
5648 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5649}
5650
5651// Client destructor must be called with AudioFlinger::mLock held
5652AudioFlinger::Client::~Client()
5653{
5654 mAudioFlinger->removeClient_l(mPid);
5655}
5656
Glenn Kasten435dbe62012-01-30 10:15:48 -08005657sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658{
5659 return mMemoryDealer;
5660}
5661
John Grossman4ff14ba2012-02-08 16:37:41 -08005662// Reserve one of the limited slots for a timed audio track associated
5663// with this client
5664bool AudioFlinger::Client::reserveTimedTrack()
5665{
5666 const int kMaxTimedTracksPerClient = 4;
5667
5668 Mutex::Autolock _l(mTimedTrackLock);
5669
5670 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5671 ALOGW("can not create timed track - pid %d has exceeded the limit",
5672 mPid);
5673 return false;
5674 }
5675
5676 mTimedTrackCount++;
5677 return true;
5678}
5679
5680// Release a slot for a timed audio track
5681void AudioFlinger::Client::releaseTimedTrack()
5682{
5683 Mutex::Autolock _l(mTimedTrackLock);
5684 mTimedTrackCount--;
5685}
5686
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687// ----------------------------------------------------------------------------
5688
5689AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5690 const sp<IAudioFlingerClient>& client,
5691 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005692 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693{
5694}
5695
5696AudioFlinger::NotificationClient::~NotificationClient()
5697{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698}
5699
5700void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5701{
5702 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005703 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704}
5705
5706// ----------------------------------------------------------------------------
5707
5708AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5709 : BnAudioTrack(),
5710 mTrack(track)
5711{
5712}
5713
5714AudioFlinger::TrackHandle::~TrackHandle() {
5715 // just stop the track on deletion, associated resources
5716 // will be freed from the main thread once all pending buffers have
5717 // been played. Unless it's not in the active track list, in which
5718 // case we free everything now...
5719 mTrack->destroy();
5720}
5721
Glenn Kasten90716c52012-01-26 13:40:12 -08005722sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5723 return mTrack->getCblk();
5724}
5725
Glenn Kasten3acbd052012-02-28 10:39:56 -08005726status_t AudioFlinger::TrackHandle::start() {
5727 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728}
5729
5730void AudioFlinger::TrackHandle::stop() {
5731 mTrack->stop();
5732}
5733
5734void AudioFlinger::TrackHandle::flush() {
5735 mTrack->flush();
5736}
5737
5738void AudioFlinger::TrackHandle::mute(bool e) {
5739 mTrack->mute(e);
5740}
5741
5742void AudioFlinger::TrackHandle::pause() {
5743 mTrack->pause();
5744}
5745
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5747{
5748 return mTrack->attachAuxEffect(EffectId);
5749}
5750
John Grossman4ff14ba2012-02-08 16:37:41 -08005751status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5752 sp<IMemory>* buffer) {
5753 if (!mTrack->isTimedTrack())
5754 return INVALID_OPERATION;
5755
5756 PlaybackThread::TimedTrack* tt =
5757 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5758 return tt->allocateTimedBuffer(size, buffer);
5759}
5760
5761status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5762 int64_t pts) {
5763 if (!mTrack->isTimedTrack())
5764 return INVALID_OPERATION;
5765
5766 PlaybackThread::TimedTrack* tt =
5767 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5768 return tt->queueTimedBuffer(buffer, pts);
5769}
5770
5771status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5772 const LinearTransform& xform, int target) {
5773
5774 if (!mTrack->isTimedTrack())
5775 return INVALID_OPERATION;
5776
5777 PlaybackThread::TimedTrack* tt =
5778 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5779 return tt->setMediaTimeTransform(
5780 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5781}
5782
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783status_t AudioFlinger::TrackHandle::onTransact(
5784 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5785{
5786 return BnAudioTrack::onTransact(code, data, reply, flags);
5787}
5788
5789// ----------------------------------------------------------------------------
5790
5791sp<IAudioRecord> AudioFlinger::openRecord(
5792 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005793 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005795 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005796 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005797 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005798 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005799 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 int *sessionId,
5801 status_t *status)
5802{
5803 sp<RecordThread::RecordTrack> recordTrack;
5804 sp<RecordHandle> recordHandle;
5805 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806 status_t lStatus;
5807 RecordThread *thread;
5808 size_t inFrameCount;
5809 int lSessionId;
5810
5811 // check calling permissions
5812 if (!recordingAllowed()) {
5813 lStatus = PERMISSION_DENIED;
5814 goto Exit;
5815 }
5816
5817 // add client to list
5818 { // scope for mLock
5819 Mutex::Autolock _l(mLock);
5820 thread = checkRecordThread_l(input);
5821 if (thread == NULL) {
5822 lStatus = BAD_VALUE;
5823 goto Exit;
5824 }
5825
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005826 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827
5828 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005829 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 lSessionId = *sessionId;
5831 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005832 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 if (sessionId != NULL) {
5834 *sessionId = lSessionId;
5835 }
5836 }
5837 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005838 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5839 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005841 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5843 // destructor is called by the TrackBase destructor with mLock held
5844 client.clear();
5845 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846 goto Exit;
5847 }
5848
5849 // return to handle to client
5850 recordHandle = new RecordHandle(recordTrack);
5851 lStatus = NO_ERROR;
5852
5853Exit:
5854 if (status) {
5855 *status = lStatus;
5856 }
5857 return recordHandle;
5858}
5859
5860// ----------------------------------------------------------------------------
5861
5862AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5863 : BnAudioRecord(),
5864 mRecordTrack(recordTrack)
5865{
5866}
5867
5868AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005869 stop_nonvirtual();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870}
5871
Glenn Kasten90716c52012-01-26 13:40:12 -08005872sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5873 return mRecordTrack->getCblk();
5874}
5875
Glenn Kasten3acbd052012-02-28 10:39:56 -08005876status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005877 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005878 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879}
5880
5881void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005882 stop_nonvirtual();
5883}
5884
5885void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005886 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005887 mRecordTrack->stop();
5888}
5889
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890status_t AudioFlinger::RecordHandle::onTransact(
5891 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5892{
5893 return BnAudioRecord::onTransact(code, data, reply, flags);
5894}
5895
5896// ----------------------------------------------------------------------------
5897
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005898AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5899 AudioStreamIn *input,
5900 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005901 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005902 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005903 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005904 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005905 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5906 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005907 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005908 mReqSampleRate(sampleRate)
5909 // mBytesRead is only meaningful while active, and so is cleared in start()
5910 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005911{
Glenn Kasten480b4682012-02-28 12:30:08 -08005912 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005913
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 readInputParameters();
5915}
5916
5917
5918AudioFlinger::RecordThread::~RecordThread()
5919{
5920 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005921 delete mResampler;
5922 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923}
5924
5925void AudioFlinger::RecordThread::onFirstRef()
5926{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005927 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928}
5929
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005930status_t AudioFlinger::RecordThread::readyToRun()
5931{
5932 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005933 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005934 return status;
5935}
5936
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937bool AudioFlinger::RecordThread::threadLoop()
5938{
5939 AudioBufferProvider::Buffer buffer;
5940 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005941 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942
Eric Laurent44d98482010-09-30 16:12:31 -07005943 nsecs_t lastWarning = 0;
5944
Eric Laurentfeb0db62011-07-22 09:04:31 -07005945 acquireWakeLock();
5946
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947 // start recording
5948 while (!exitPending()) {
5949
5950 processConfigEvents();
5951
5952 { // scope for mLock
5953 Mutex::Autolock _l(mLock);
5954 checkForNewParameters_l();
5955 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5956 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005957 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 mStandby = true;
5959 }
5960
5961 if (exitPending()) break;
5962
Eric Laurentfeb0db62011-07-22 09:04:31 -07005963 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005964 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 // go to sleep
5966 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005967 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005968 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 continue;
5970 }
5971 if (mActiveTrack != 0) {
5972 if (mActiveTrack->mState == TrackBase::PAUSING) {
5973 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005974 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 mStandby = true;
5976 }
5977 mActiveTrack.clear();
5978 mStartStopCond.broadcast();
5979 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5980 if (mReqChannelCount != mActiveTrack->channelCount()) {
5981 mActiveTrack.clear();
5982 mStartStopCond.broadcast();
5983 } else if (mBytesRead != 0) {
5984 // record start succeeds only if first read from audio input
5985 // succeeds
5986 if (mBytesRead > 0) {
5987 mActiveTrack->mState = TrackBase::ACTIVE;
5988 } else {
5989 mActiveTrack.clear();
5990 }
5991 mStartStopCond.broadcast();
5992 }
5993 mStandby = false;
5994 }
5995 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005996 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 }
5998
5999 if (mActiveTrack != 0) {
6000 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6001 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006002 unlockEffectChains(effectChains);
6003 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 continue;
6005 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006006 for (size_t i = 0; i < effectChains.size(); i ++) {
6007 effectChains[i]->process_l();
6008 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006009
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006011 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006013 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 // no resampling
6015 while (framesOut) {
6016 size_t framesIn = mFrameCount - mRsmpInIndex;
6017 if (framesIn) {
6018 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6019 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6020 if (framesIn > framesOut)
6021 framesIn = framesOut;
6022 mRsmpInIndex += framesIn;
6023 framesOut -= framesIn;
6024 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006025 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 memcpy(dst, src, framesIn * mFrameSize);
6027 } else {
6028 int16_t *src16 = (int16_t *)src;
6029 int16_t *dst16 = (int16_t *)dst;
6030 if (mChannelCount == 1) {
6031 while (framesIn--) {
6032 *dst16++ = *src16;
6033 *dst16++ = *src16++;
6034 }
6035 } else {
6036 while (framesIn--) {
6037 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6038 src16 += 2;
6039 }
6040 }
6041 }
6042 }
6043 if (framesOut && mFrameCount == mRsmpInIndex) {
6044 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006045 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006046 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 framesOut = 0;
6048 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006049 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 mRsmpInIndex = 0;
6051 }
6052 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006053 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6055 // Force input into standby so that it tries to
6056 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006057 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006058 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 }
6060 mRsmpInIndex = mFrameCount;
6061 framesOut = 0;
6062 buffer.frameCount = 0;
6063 }
6064 }
6065 }
6066 } else {
6067 // resampling
6068
6069 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6070 // alter output frame count as if we were expecting stereo samples
6071 if (mChannelCount == 1 && mReqChannelCount == 1) {
6072 framesOut >>= 1;
6073 }
6074 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6075 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6076 // are 32 bit aligned which should be always true.
6077 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006078 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 // the resampler always outputs stereo samples: do post stereo to mono conversion
6080 int16_t *src = (int16_t *)mRsmpOutBuffer;
6081 int16_t *dst = buffer.i16;
6082 while (framesOut--) {
6083 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6084 src += 2;
6085 }
6086 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006087 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 }
6089
6090 }
Eric Laurenta011e352012-03-29 15:51:43 -07006091 if (mFramestoDrop == 0) {
6092 mActiveTrack->releaseBuffer(&buffer);
6093 } else {
6094 if (mFramestoDrop > 0) {
6095 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006096 if (mFramestoDrop <= 0) {
6097 clearSyncStartEvent();
6098 }
6099 } else {
6100 mFramestoDrop += buffer.frameCount;
6101 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6102 mSyncStartEvent->isCancelled()) {
6103 ALOGW("Synced record %s, session %d, trigger session %d",
6104 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6105 mActiveTrack->sessionId(),
6106 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6107 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006108 }
6109 }
6110 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006111 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112 }
6113 // client isn't retrieving buffers fast enough
6114 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006115 if (!mActiveTrack->setOverflow()) {
6116 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006117 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006118 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006119 lastWarning = now;
6120 }
6121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 // Release the processor for a while before asking for a new buffer.
6123 // This will give the application more chance to read from the buffer and
6124 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 }
6127 }
Eric Laurentec437d82011-07-26 20:54:46 -07006128 // enable changes in effect chain
6129 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006130 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 }
6132
6133 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006134 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 }
6136 mActiveTrack.clear();
6137
6138 mStartStopCond.broadcast();
6139
Eric Laurentfeb0db62011-07-22 09:04:31 -07006140 releaseWakeLock();
6141
Steve Block3856b092011-10-20 11:56:00 +01006142 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 return false;
6144}
6145
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006146
6147sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6148 const sp<AudioFlinger::Client>& client,
6149 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006150 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006151 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006154 IAudioFlinger::track_flags_t flags,
6155 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006156 status_t *status)
6157{
6158 sp<RecordTrack> track;
6159 status_t lStatus;
6160
6161 lStatus = initCheck();
6162 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006163 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006164 goto Exit;
6165 }
6166
Glenn Kasten1879fff2012-07-11 15:36:59 -07006167 // FIXME use flags and tid similar to createTrack_l()
6168
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 { // scope for mLock
6170 Mutex::Autolock _l(mLock);
6171
6172 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006173 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006174
Glenn Kasten7378ca52012-01-20 13:44:40 -08006175 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176 lStatus = NO_MEMORY;
6177 goto Exit;
6178 }
6179
6180 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006181 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6182 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006183 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006184 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6185 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 }
6187 lStatus = NO_ERROR;
6188
6189Exit:
6190 if (status) {
6191 *status = lStatus;
6192 }
6193 return track;
6194}
6195
Eric Laurenta011e352012-03-29 15:51:43 -07006196status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006197 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006198 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199{
Glenn Kasten58912562012-04-03 10:45:00 -07006200 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006201 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006203
6204 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006205 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006206 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6207 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6208 triggerSession,
6209 recordTrack->sessionId(),
6210 syncStartEventCallback,
6211 this);
Eric Laurent29864602012-05-08 18:57:51 -07006212 // Sync event can be cancelled by the trigger session if the track is not in a
6213 // compatible state in which case we start record immediately
6214 if (mSyncStartEvent->isCancelled()) {
6215 clearSyncStartEvent();
6216 } else {
6217 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6218 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6219 }
Eric Laurenta011e352012-03-29 15:51:43 -07006220 }
6221
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006223 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 if (mActiveTrack != 0) {
6225 if (recordTrack != mActiveTrack.get()) {
6226 status = -EBUSY;
6227 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6228 mActiveTrack->mState = TrackBase::ACTIVE;
6229 }
6230 return status;
6231 }
6232
6233 recordTrack->mState = TrackBase::IDLE;
6234 mActiveTrack = recordTrack;
6235 mLock.unlock();
6236 status_t status = AudioSystem::startInput(mId);
6237 mLock.lock();
6238 if (status != NO_ERROR) {
6239 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006240 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 return status;
6242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 mRsmpInIndex = mFrameCount;
6244 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006245 if (mResampler != NULL) {
6246 mResampler->reset();
6247 }
6248 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006250 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 mWaitWorkCV.signal();
6252 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006253 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 mActiveTrack.clear();
6255 status = INVALID_OPERATION;
6256 goto startError;
6257 }
6258 mStartStopCond.wait(mLock);
6259 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006260 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 status = BAD_VALUE;
6262 goto startError;
6263 }
Steve Block3856b092011-10-20 11:56:00 +01006264 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 return status;
6266 }
6267startError:
6268 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006269 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 return status;
6271}
6272
Eric Laurenta011e352012-03-29 15:51:43 -07006273void AudioFlinger::RecordThread::clearSyncStartEvent()
6274{
6275 if (mSyncStartEvent != 0) {
6276 mSyncStartEvent->cancel();
6277 }
6278 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006279 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006280}
6281
6282void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6283{
6284 sp<SyncEvent> strongEvent = event.promote();
6285
6286 if (strongEvent != 0) {
6287 RecordThread *me = (RecordThread *)strongEvent->cookie();
6288 me->handleSyncStartEvent(strongEvent);
6289 }
6290}
6291
6292void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6293{
Eric Laurent29864602012-05-08 18:57:51 -07006294 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006295 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6296 // from audio HAL
6297 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006298 }
6299}
6300
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006302 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006303 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006305 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6307 mActiveTrack->mState = TrackBase::PAUSING;
6308 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006309 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 return;
6311 }
6312 mStartStopCond.wait(mLock);
6313 // if we have been restarted, recordTrack == mActiveTrack.get() here
6314 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6315 mLock.unlock();
6316 AudioSystem::stopInput(mId);
6317 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006318 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006319 }
6320 }
6321 }
6322}
6323
Eric Laurenta011e352012-03-29 15:51:43 -07006324bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6325{
6326 return false;
6327}
6328
6329status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6330{
6331 if (!isValidSyncEvent(event)) {
6332 return BAD_VALUE;
6333 }
6334
6335 Mutex::Autolock _l(mLock);
6336
6337 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6338 mTrack->setSyncEvent(event);
6339 return NO_ERROR;
6340 }
6341 return NAME_NOT_FOUND;
6342}
6343
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6345{
6346 const size_t SIZE = 256;
6347 char buffer[SIZE];
6348 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349
6350 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6351 result.append(buffer);
6352
6353 if (mActiveTrack != 0) {
6354 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006355 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 mActiveTrack->dump(buffer, SIZE);
6357 result.append(buffer);
6358
6359 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6360 result.append(buffer);
6361 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6362 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006363 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 result.append(buffer);
6365 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6366 result.append(buffer);
6367 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6368 result.append(buffer);
6369
6370
6371 } else {
6372 result.append("No record client\n");
6373 }
6374 write(fd, result.string(), result.size());
6375
6376 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006377 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378
6379 return NO_ERROR;
6380}
6381
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006382// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006383status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384{
6385 size_t framesReq = buffer->frameCount;
6386 size_t framesReady = mFrameCount - mRsmpInIndex;
6387 int channelCount;
6388
6389 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006390 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006392 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6394 // Force input into standby so that it tries to
6395 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006396 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006397 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006399 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006400 buffer->frameCount = 0;
6401 return NOT_ENOUGH_DATA;
6402 }
6403 mRsmpInIndex = 0;
6404 framesReady = mFrameCount;
6405 }
6406
6407 if (framesReq > framesReady) {
6408 framesReq = framesReady;
6409 }
6410
6411 if (mChannelCount == 1 && mReqChannelCount == 2) {
6412 channelCount = 1;
6413 } else {
6414 channelCount = 2;
6415 }
6416 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6417 buffer->frameCount = framesReq;
6418 return NO_ERROR;
6419}
6420
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006421// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6423{
6424 mRsmpInIndex += buffer->frameCount;
6425 buffer->frameCount = 0;
6426}
6427
6428bool AudioFlinger::RecordThread::checkForNewParameters_l()
6429{
6430 bool reconfig = false;
6431
6432 while (!mNewParameters.isEmpty()) {
6433 status_t status = NO_ERROR;
6434 String8 keyValuePair = mNewParameters[0];
6435 AudioParameter param = AudioParameter(keyValuePair);
6436 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006437 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 int reqSamplingRate = mReqSampleRate;
6439 int reqChannelCount = mReqChannelCount;
6440
6441 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6442 reqSamplingRate = value;
6443 reconfig = true;
6444 }
6445 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006446 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 reconfig = true;
6448 }
6449 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006450 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 reconfig = true;
6452 }
6453 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6454 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006455 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456 // if frame count is changed after track creation
6457 if (mActiveTrack != 0) {
6458 status = INVALID_OPERATION;
6459 } else {
6460 reconfig = true;
6461 }
6462 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006463 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6464 // forward device change to effects that have requested to be
6465 // aware of attached audio device.
6466 for (size_t i = 0; i < mEffectChains.size(); i++) {
6467 mEffectChains[i]->setDevice_l(value);
6468 }
6469 // store input device and output device but do not forward output device to audio HAL.
6470 // Note that status is ignored by the caller for output device
6471 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006472 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006473 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006474 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006475 status = BAD_VALUE;
6476 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006477 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006478 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6479 if (mTrack != NULL) {
6480 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006481 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006482 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6483 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6484 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006485 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006486 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006487 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006488 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006490 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006492 mInput->stream->common.standby(&mInput->stream->common);
6493 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6494 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495 }
6496 if (reconfig) {
6497 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006498 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006499 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006500 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006501 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6502 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 status = NO_ERROR;
6504 }
6505 if (status == NO_ERROR) {
6506 readInputParameters();
6507 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6508 }
6509 }
6510 }
6511
6512 mNewParameters.removeAt(0);
6513
6514 mParamStatus = status;
6515 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006516 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6517 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006518 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519 }
6520 return reconfig;
6521}
6522
6523String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6524{
Dima Zavinfce7a472011-04-19 22:30:36 -07006525 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006526 String8 out_s8 = String8();
6527
6528 Mutex::Autolock _l(mLock);
6529 if (initCheck() != NO_ERROR) {
6530 return out_s8;
6531 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006532
Dima Zavin799a70e2011-04-18 16:57:27 -07006533 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006534 out_s8 = String8(s);
6535 free(s);
6536 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537}
6538
6539void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6540 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006541 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542
6543 switch (event) {
6544 case AudioSystem::INPUT_OPENED:
6545 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006546 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 desc.samplingRate = mSampleRate;
6548 desc.format = mFormat;
6549 desc.frameCount = mFrameCount;
6550 desc.latency = 0;
6551 param2 = &desc;
6552 break;
6553
6554 case AudioSystem::INPUT_CLOSED:
6555 default:
6556 break;
6557 }
6558 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6559}
6560
6561void AudioFlinger::RecordThread::readInputParameters()
6562{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006563 delete mRsmpInBuffer;
6564 // mRsmpInBuffer is always assigned a new[] below
6565 delete mRsmpOutBuffer;
6566 mRsmpOutBuffer = NULL;
6567 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006568 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569
Dima Zavin799a70e2011-04-18 16:57:27 -07006570 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006571 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6572 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006573 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006574 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006575 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006577 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6579
Glenn Kasten53d76db2012-03-08 12:32:47 -08006580 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 {
6582 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006583 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6584 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 if (mChannelCount == 1 && mReqChannelCount == 2) {
6586 channelCount = 1;
6587 } else {
6588 channelCount = 2;
6589 }
6590 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6591 mResampler->setSampleRate(mSampleRate);
6592 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6593 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6594
6595 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6596 if (mChannelCount == 1 && mReqChannelCount == 1) {
6597 mFrameCount >>= 1;
6598 }
6599
6600 }
6601 mRsmpInIndex = mFrameCount;
6602}
6603
6604unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6605{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006606 Mutex::Autolock _l(mLock);
6607 if (initCheck() != NO_ERROR) {
6608 return 0;
6609 }
6610
Dima Zavin799a70e2011-04-18 16:57:27 -07006611 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612}
6613
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006614uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6615{
6616 Mutex::Autolock _l(mLock);
6617 uint32_t result = 0;
6618 if (getEffectChain_l(sessionId) != 0) {
6619 result = EFFECT_SESSION;
6620 }
6621
6622 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6623 result |= TRACK_SESSION;
6624 }
6625
6626 return result;
6627}
6628
Eric Laurent59bd0da2011-08-01 09:52:20 -07006629AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6630{
6631 Mutex::Autolock _l(mLock);
6632 return mTrack;
6633}
6634
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006635AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6636{
6637 Mutex::Autolock _l(mLock);
6638 AudioStreamIn *input = mInput;
6639 mInput = NULL;
6640 return input;
6641}
6642
6643// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006644audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006645{
6646 if (mInput == NULL) {
6647 return NULL;
6648 }
6649 return &mInput->stream->common;
6650}
6651
6652
Mathias Agopian65ab4712010-07-14 17:59:35 -07006653// ----------------------------------------------------------------------------
6654
Eric Laurenta4c5a552012-03-29 10:12:40 -07006655audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6656{
6657 if (!settingsAllowed()) {
6658 return 0;
6659 }
6660 Mutex::Autolock _l(mLock);
6661 return loadHwModule_l(name);
6662}
6663
6664// loadHwModule_l() must be called with AudioFlinger::mLock held
6665audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6666{
6667 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6668 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6669 ALOGW("loadHwModule() module %s already loaded", name);
6670 return mAudioHwDevs.keyAt(i);
6671 }
6672 }
6673
Eric Laurenta4c5a552012-03-29 10:12:40 -07006674 audio_hw_device_t *dev;
6675
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006676 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006677 if (rc) {
6678 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6679 return 0;
6680 }
6681
6682 mHardwareStatus = AUDIO_HW_INIT;
6683 rc = dev->init_check(dev);
6684 mHardwareStatus = AUDIO_HW_IDLE;
6685 if (rc) {
6686 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6687 return 0;
6688 }
6689
6690 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6691 (NULL != dev->set_master_volume)) {
6692 AutoMutex lock(mHardwareLock);
6693 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6694 dev->set_master_volume(dev, mMasterVolume);
6695 mHardwareStatus = AUDIO_HW_IDLE;
6696 }
6697
6698 audio_module_handle_t handle = nextUniqueId();
6699 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6700
6701 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006702 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006703
6704 return handle;
6705
6706}
6707
6708audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6709 audio_devices_t *pDevices,
6710 uint32_t *pSamplingRate,
6711 audio_format_t *pFormat,
6712 audio_channel_mask_t *pChannelMask,
6713 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006714 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715{
6716 status_t status;
6717 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006718 struct audio_config config = {
6719 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6720 channel_mask: pChannelMask ? *pChannelMask : 0,
6721 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6722 };
6723 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006724 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725
Eric Laurenta4c5a552012-03-29 10:12:40 -07006726 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6727 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006728 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006729 config.sample_rate,
6730 config.format,
6731 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006732 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733
6734 if (pDevices == NULL || *pDevices == 0) {
6735 return 0;
6736 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006737
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 Mutex::Autolock _l(mLock);
6739
Eric Laurenta4c5a552012-03-29 10:12:40 -07006740 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006741 if (outHwDev == NULL)
6742 return 0;
6743
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006744 audio_io_handle_t id = nextUniqueId();
6745
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006746 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006747
6748 status = outHwDev->open_output_stream(outHwDev,
6749 id,
6750 *pDevices,
6751 (audio_output_flags_t)flags,
6752 &config,
6753 &outStream);
6754
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006755 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006756 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006757 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006758 config.sample_rate,
6759 config.format,
6760 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 status);
6762
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006763 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006764 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006765
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006766 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006767 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6768 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006770 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 } else {
6772 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006773 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 }
6775 mPlaybackThreads.add(id, thread);
6776
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006777 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6778 if (pFormat != NULL) *pFormat = config.format;
6779 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006780 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781
6782 // notify client processes of the new output creation
6783 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006784
6785 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006786 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006787 ALOGI("Using module %d has the primary audio interface", module);
6788 mPrimaryHardwareDev = outHwDev;
6789
6790 AutoMutex lock(mHardwareLock);
6791 mHardwareStatus = AUDIO_HW_SET_MODE;
6792 outHwDev->set_mode(outHwDev, mMode);
6793
6794 // Determine the level of master volume support the primary audio HAL has,
6795 // and set the initial master volume at the same time.
6796 float initialVolume = 1.0;
6797 mMasterVolumeSupportLvl = MVS_NONE;
6798
6799 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6800 if ((NULL != outHwDev->get_master_volume) &&
6801 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6802 mMasterVolumeSupportLvl = MVS_FULL;
6803 } else {
6804 mMasterVolumeSupportLvl = MVS_SETONLY;
6805 initialVolume = 1.0;
6806 }
6807
6808 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6809 if ((NULL == outHwDev->set_master_volume) ||
6810 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6811 mMasterVolumeSupportLvl = MVS_NONE;
6812 }
6813 // now that we have a primary device, initialize master volume on other devices
6814 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6815 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6816
6817 if ((dev != mPrimaryHardwareDev) &&
6818 (NULL != dev->set_master_volume)) {
6819 dev->set_master_volume(dev, initialVolume);
6820 }
6821 }
6822 mHardwareStatus = AUDIO_HW_IDLE;
6823 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6824 ? initialVolume
6825 : 1.0;
6826 mMasterVolume = initialVolume;
6827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 return id;
6829 }
6830
6831 return 0;
6832}
6833
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006834audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6835 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836{
6837 Mutex::Autolock _l(mLock);
6838 MixerThread *thread1 = checkMixerThread_l(output1);
6839 MixerThread *thread2 = checkMixerThread_l(output2);
6840
6841 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006842 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843 return 0;
6844 }
6845
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006846 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6848 thread->addOutputTrack(thread2);
6849 mPlaybackThreads.add(id, thread);
6850 // notify client processes of the new output creation
6851 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6852 return id;
6853}
6854
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006855status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856{
Glenn Kastend96c5722012-04-25 13:44:49 -07006857 return closeOutput_nonvirtual(output);
6858}
6859
6860status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6861{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 // keep strong reference on the playback thread so that
6863 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006864 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 {
6866 Mutex::Autolock _l(mLock);
6867 thread = checkPlaybackThread_l(output);
6868 if (thread == NULL) {
6869 return BAD_VALUE;
6870 }
6871
Steve Block3856b092011-10-20 11:56:00 +01006872 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006874 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6878 dupThread->removeOutputTrack((MixerThread *)thread.get());
6879 }
6880 }
6881 }
Glenn Kastena1117922012-01-26 10:53:32 -08006882 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 mPlaybackThreads.removeItem(output);
6884 }
6885 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006886 // The thread entity (active unit of execution) is no longer running here,
6887 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006889 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006890 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006891 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006892 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006893 out->hwDev->close_output_stream(out->hwDev, out->stream);
6894 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895 }
6896 return NO_ERROR;
6897}
6898
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006899status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900{
6901 Mutex::Autolock _l(mLock);
6902 PlaybackThread *thread = checkPlaybackThread_l(output);
6903
6904 if (thread == NULL) {
6905 return BAD_VALUE;
6906 }
6907
Steve Block3856b092011-10-20 11:56:00 +01006908 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 thread->suspend();
6910
6911 return NO_ERROR;
6912}
6913
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006914status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915{
6916 Mutex::Autolock _l(mLock);
6917 PlaybackThread *thread = checkPlaybackThread_l(output);
6918
6919 if (thread == NULL) {
6920 return BAD_VALUE;
6921 }
6922
Steve Block3856b092011-10-20 11:56:00 +01006923 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924
6925 thread->restore();
6926
6927 return NO_ERROR;
6928}
6929
Eric Laurenta4c5a552012-03-29 10:12:40 -07006930audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6931 audio_devices_t *pDevices,
6932 uint32_t *pSamplingRate,
6933 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006934 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935{
6936 status_t status;
6937 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006938 struct audio_config config = {
6939 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6940 channel_mask: pChannelMask ? *pChannelMask : 0,
6941 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6942 };
6943 uint32_t reqSamplingRate = config.sample_rate;
6944 audio_format_t reqFormat = config.format;
6945 audio_channel_mask_t reqChannels = config.channel_mask;
6946 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006947 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948
6949 if (pDevices == NULL || *pDevices == 0) {
6950 return 0;
6951 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006952
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 Mutex::Autolock _l(mLock);
6954
Eric Laurenta4c5a552012-03-29 10:12:40 -07006955 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006956 if (inHwDev == NULL)
6957 return 0;
6958
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006959 audio_io_handle_t id = nextUniqueId();
6960
6961 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006962 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006963 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006964 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006965 config.sample_rate,
6966 config.format,
6967 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 status);
6969
6970 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6971 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6972 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006973 if (status == BAD_VALUE &&
6974 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6975 (config.sample_rate <= 2 * reqSamplingRate) &&
6976 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006977 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006978 inStream = NULL;
6979 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006980 }
6981
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006982 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006983 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6984
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006985 // Start record thread
6986 // RecorThread require both input and output device indication to forward to audio
6987 // pre processing modules
6988 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6989 thread = new RecordThread(this,
6990 input,
6991 reqSamplingRate,
6992 reqChannels,
6993 id,
6994 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006996 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006997 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006998 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006999 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000
Dima Zavin799a70e2011-04-18 16:57:27 -07007001 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002
7003 // notify client processes of the new input creation
7004 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7005 return id;
7006 }
7007
7008 return 0;
7009}
7010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007011status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012{
Glenn Kastend96c5722012-04-25 13:44:49 -07007013 return closeInput_nonvirtual(input);
7014}
7015
7016status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7017{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 // keep strong reference on the record thread so that
7019 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007020 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 {
7022 Mutex::Autolock _l(mLock);
7023 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007024 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 return BAD_VALUE;
7026 }
7027
Steve Block3856b092011-10-20 11:56:00 +01007028 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007029 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 mRecordThreads.removeItem(input);
7031 }
7032 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007033 // The thread entity (active unit of execution) is no longer running here,
7034 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007036 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007037 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007038 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007039 in->hwDev->close_input_stream(in->hwDev, in->stream);
7040 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041
7042 return NO_ERROR;
7043}
7044
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007045status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046{
7047 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007048 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049
7050 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7051 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007052 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054
7055 return NO_ERROR;
7056}
7057
7058
7059int AudioFlinger::newAudioSessionId()
7060{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007061 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062}
7063
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007064void AudioFlinger::acquireAudioSessionId(int audioSession)
7065{
7066 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007067 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007068 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007069 size_t num = mAudioSessionRefs.size();
7070 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007071 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007072 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7073 ref->mCnt++;
7074 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007075 return;
7076 }
7077 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007078 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7079 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007080}
7081
7082void AudioFlinger::releaseAudioSessionId(int audioSession)
7083{
7084 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007085 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007086 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007087 size_t num = mAudioSessionRefs.size();
7088 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007089 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007090 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7091 ref->mCnt--;
7092 ALOGV(" decremented refcount to %d", ref->mCnt);
7093 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007094 mAudioSessionRefs.removeAt(i);
7095 delete ref;
7096 purgeStaleEffects_l();
7097 }
7098 return;
7099 }
7100 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007101 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007102}
7103
7104void AudioFlinger::purgeStaleEffects_l() {
7105
Steve Block3856b092011-10-20 11:56:00 +01007106 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007107
7108 Vector< sp<EffectChain> > chains;
7109
7110 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7111 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7112 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7113 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007114 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7115 chains.push(ec);
7116 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007117 }
7118 }
7119 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7120 sp<RecordThread> t = mRecordThreads.valueAt(i);
7121 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7122 sp<EffectChain> ec = t->mEffectChains[j];
7123 chains.push(ec);
7124 }
7125 }
7126
7127 for (size_t i = 0; i < chains.size(); i++) {
7128 sp<EffectChain> ec = chains[i];
7129 int sessionid = ec->sessionId();
7130 sp<ThreadBase> t = ec->mThread.promote();
7131 if (t == 0) {
7132 continue;
7133 }
7134 size_t numsessionrefs = mAudioSessionRefs.size();
7135 bool found = false;
7136 for (size_t k = 0; k < numsessionrefs; k++) {
7137 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007138 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007139 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007140 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007141 found = true;
7142 break;
7143 }
7144 }
7145 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007146 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007147 // remove all effects from the chain
7148 while (ec->mEffects.size()) {
7149 sp<EffectModule> effect = ec->mEffects[0];
7150 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007151 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007152 if (effect->purgeHandles()) {
7153 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007154 }
7155 AudioSystem::unregisterEffect(effect->id());
7156 }
7157 }
7158 }
7159 return;
7160}
7161
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007163AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164{
Glenn Kastena1117922012-01-26 10:53:32 -08007165 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166}
7167
7168// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007169AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170{
7171 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007172 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173}
7174
7175// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007176AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177{
Glenn Kastena1117922012-01-26 10:53:32 -08007178 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179}
7180
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007181uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007183 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184}
7185
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007186AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007187{
7188 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7189 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007190 AudioStreamOut *output = thread->getOutput();
7191 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007192 return thread;
7193 }
7194 }
7195 return NULL;
7196}
7197
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007198uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007199{
7200 PlaybackThread *thread = primaryPlaybackThread_l();
7201
7202 if (thread == NULL) {
7203 return 0;
7204 }
7205
7206 return thread->device();
7207}
7208
Eric Laurenta011e352012-03-29 15:51:43 -07007209sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7210 int triggerSession,
7211 int listenerSession,
7212 sync_event_callback_t callBack,
7213 void *cookie)
7214{
7215 Mutex::Autolock _l(mLock);
7216
7217 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7218 status_t playStatus = NAME_NOT_FOUND;
7219 status_t recStatus = NAME_NOT_FOUND;
7220 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7221 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7222 if (playStatus == NO_ERROR) {
7223 return event;
7224 }
7225 }
7226 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7227 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7228 if (recStatus == NO_ERROR) {
7229 return event;
7230 }
7231 }
7232 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7233 mPendingSyncEvents.add(event);
7234 } else {
7235 ALOGV("createSyncEvent() invalid event %d", event->type());
7236 event.clear();
7237 }
7238 return event;
7239}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007240
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241// ----------------------------------------------------------------------------
7242// Effect management
7243// ----------------------------------------------------------------------------
7244
7245
Glenn Kastenf587ba52012-01-26 16:25:10 -08007246status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007247{
7248 Mutex::Autolock _l(mLock);
7249 return EffectQueryNumberEffects(numEffects);
7250}
7251
Glenn Kastenf587ba52012-01-26 16:25:10 -08007252status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007253{
7254 Mutex::Autolock _l(mLock);
7255 return EffectQueryEffect(index, descriptor);
7256}
7257
Glenn Kasten5e92a782012-01-30 07:40:52 -08007258status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007259 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260{
7261 Mutex::Autolock _l(mLock);
7262 return EffectGetDescriptor(pUuid, descriptor);
7263}
7264
7265
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7267 effect_descriptor_t *pDesc,
7268 const sp<IEffectClient>& effectClient,
7269 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007270 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 int sessionId,
7272 status_t *status,
7273 int *id,
7274 int *enabled)
7275{
7276 status_t lStatus = NO_ERROR;
7277 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007280 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007281 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282
7283 if (pDesc == NULL) {
7284 lStatus = BAD_VALUE;
7285 goto Exit;
7286 }
7287
Eric Laurent84e9a102010-09-23 16:10:16 -07007288 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007289 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007290 lStatus = PERMISSION_DENIED;
7291 goto Exit;
7292 }
7293
Dima Zavinfce7a472011-04-19 22:30:36 -07007294 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007295 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007296 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007297 lStatus = PERMISSION_DENIED;
7298 goto Exit;
7299 }
7300
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007302 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007303 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007304 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 lStatus = BAD_VALUE;
7306 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007307 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007308 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007309 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007310 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007311 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007312 }
7313 }
7314
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315 {
7316 Mutex::Autolock _l(mLock);
7317
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318
7319 if (!EffectIsNullUuid(&pDesc->uuid)) {
7320 // if uuid is specified, request effect descriptor
7321 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7322 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007323 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 goto Exit;
7325 }
7326 } else {
7327 // if uuid is not specified, look for an available implementation
7328 // of the required type in effect factory
7329 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007330 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 lStatus = BAD_VALUE;
7332 goto Exit;
7333 }
7334 uint32_t numEffects = 0;
7335 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007336 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 bool found = false;
7338
7339 lStatus = EffectQueryNumberEffects(&numEffects);
7340 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007341 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 goto Exit;
7343 }
7344 for (uint32_t i = 0; i < numEffects; i++) {
7345 lStatus = EffectQueryEffect(i, &desc);
7346 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007347 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348 continue;
7349 }
7350 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7351 // If matching type found save effect descriptor. If the session is
7352 // 0 and the effect is not auxiliary, continue enumeration in case
7353 // an auxiliary version of this effect type is available
7354 found = true;
7355 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007356 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7358 break;
7359 }
7360 }
7361 }
7362 if (!found) {
7363 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007364 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 goto Exit;
7366 }
7367 // For same effect type, chose auxiliary version over insert version if
7368 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007369 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7371 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7372 }
7373 }
7374
7375 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007376 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7378 lStatus = INVALID_OPERATION;
7379 goto Exit;
7380 }
7381
Eric Laurent59255e42011-07-27 19:49:51 -07007382 // check recording permission for visualizer
7383 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7384 !recordingAllowed()) {
7385 lStatus = PERMISSION_DENIED;
7386 goto Exit;
7387 }
7388
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 // return effect descriptor
7390 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7391
7392 // If output is not specified try to find a matching audio session ID in one of the
7393 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007394 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7395 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007396 // Note: io is never 0 when creating an effect on an input
7397 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007398 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007399 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7400 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007401 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007402 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007403 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007405 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007406 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7407 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7408 io = mRecordThreads.keyAt(i);
7409 break;
7410 }
7411 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007412 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007413 // If no output thread contains the requested session ID, default to
7414 // first output. The effect chain will be moved to the correct output
7415 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007416 if (io == 0 && mPlaybackThreads.size()) {
7417 io = mPlaybackThreads.keyAt(0);
7418 }
Steve Block3856b092011-10-20 11:56:00 +01007419 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007420 }
7421 ThreadBase *thread = checkRecordThread_l(io);
7422 if (thread == NULL) {
7423 thread = checkPlaybackThread_l(io);
7424 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007425 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426 lStatus = BAD_VALUE;
7427 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007430
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007431 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007433 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007434 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7435 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 if (handle != 0 && id != NULL) {
7437 *id = handle->id();
7438 }
7439 }
7440
7441Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007442 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 *status = lStatus;
7444 }
7445 return handle;
7446}
7447
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007448status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7449 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007450{
Steve Block3856b092011-10-20 11:56:00 +01007451 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007452 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007453 Mutex::Autolock _l(mLock);
7454 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007455 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007456 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 }
Eric Laurentde070132010-07-13 04:45:46 -07007458 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7459 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007461 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462 }
Eric Laurentde070132010-07-13 04:45:46 -07007463 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7464 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007465 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007466 return BAD_VALUE;
7467 }
7468
7469 Mutex::Autolock _dl(dstThread->mLock);
7470 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007471 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007472
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 return NO_ERROR;
7474}
7475
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007476// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007477status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007478 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007479 AudioFlinger::PlaybackThread *dstThread,
7480 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007481{
Steve Block3856b092011-10-20 11:56:00 +01007482 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007483 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007484
Eric Laurent59255e42011-07-27 19:49:51 -07007485 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007486 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007487 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007488 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007489 return INVALID_OPERATION;
7490 }
7491
Eric Laurent39e94f82010-07-28 01:32:47 -07007492 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007493 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007494 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007495 // removed.
7496 srcThread->removeEffectChain_l(chain);
7497
7498 // transfer all effects one by one so that new effect chain is created on new thread with
7499 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007500 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007501 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007502 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007503 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7504 while (effect != 0) {
7505 srcThread->removeEffect_l(effect);
7506 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007507 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7508 if (effect->state() == EffectModule::ACTIVE ||
7509 effect->state() == EffectModule::STOPPING) {
7510 effect->start();
7511 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007512 // if the move request is not received from audio policy manager, the effect must be
7513 // re-registered with the new strategy and output
7514 if (dstChain == 0) {
7515 dstChain = effect->chain().promote();
7516 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007517 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007518 srcThread->addEffect_l(effect);
7519 return NO_INIT;
7520 }
7521 strategy = dstChain->strategy();
7522 }
7523 if (reRegister) {
7524 AudioSystem::unregisterEffect(effect->id());
7525 AudioSystem::registerEffect(&effect->desc(),
7526 dstOutput,
7527 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007528 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007529 effect->id());
7530 }
Eric Laurentde070132010-07-13 04:45:46 -07007531 effect = chain->getEffectFromId_l(0);
7532 }
7533
7534 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535}
7536
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007537
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007539sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 const sp<AudioFlinger::Client>& client,
7541 const sp<IEffectClient>& effectClient,
7542 int32_t priority,
7543 int sessionId,
7544 effect_descriptor_t *desc,
7545 int *enabled,
7546 status_t *status
7547 )
7548{
7549 sp<EffectModule> effect;
7550 sp<EffectHandle> handle;
7551 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007553 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 bool effectCreated = false;
7555 bool effectRegistered = false;
7556
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007557 lStatus = initCheck();
7558 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007559 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 goto Exit;
7561 }
7562
7563 // Do not allow effects with session ID 0 on direct output or duplicating threads
7564 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007565 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007567 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568 lStatus = BAD_VALUE;
7569 goto Exit;
7570 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007571 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007572 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007573 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007574 desc->name, desc->flags, mType);
7575 lStatus = BAD_VALUE;
7576 goto Exit;
7577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578
Steve Block3856b092011-10-20 11:56:00 +01007579 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007580
7581 { // scope for mLock
7582 Mutex::Autolock _l(mLock);
7583
7584 // check for existing effect chain with the requested audio session
7585 chain = getEffectChain_l(sessionId);
7586 if (chain == 0) {
7587 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007588 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589 chain = new EffectChain(this, sessionId);
7590 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007591 chain->setStrategy(getStrategyForSession_l(sessionId));
7592 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007594 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595 }
7596
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007597 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598
7599 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007600 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007602 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603 if (lStatus != NO_ERROR) {
7604 goto Exit;
7605 }
7606 effectRegistered = true;
7607 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007608 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 lStatus = effect->status();
7610 if (lStatus != NO_ERROR) {
7611 goto Exit;
7612 }
Eric Laurentcab11242010-07-15 12:50:15 -07007613 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614 if (lStatus != NO_ERROR) {
7615 goto Exit;
7616 }
7617 effectCreated = true;
7618
7619 effect->setDevice(mDevice);
7620 effect->setMode(mAudioFlinger->getMode());
7621 }
7622 // create effect handle and connect it to effect module
7623 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007624 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007625 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 *enabled = (int)effect->isEnabled();
7627 }
7628 }
7629
7630Exit:
7631 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007632 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007634 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635 }
7636 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007637 AudioSystem::unregisterEffect(effect->id());
7638 }
7639 if (chainCreated) {
7640 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 }
7642 handle.clear();
7643 }
7644
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007645 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007646 *status = lStatus;
7647 }
7648 return handle;
7649}
7650
Eric Laurent717e1282012-06-29 16:36:52 -07007651sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7652{
7653 Mutex::Autolock _l(mLock);
7654 return getEffect_l(sessionId, effectId);
7655}
7656
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007657sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7658{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007659 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007660 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007661}
7662
Eric Laurentde070132010-07-13 04:45:46 -07007663// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7664// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007665status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007666{
7667 // check for existing effect chain with the requested audio session
7668 int sessionId = effect->sessionId();
7669 sp<EffectChain> chain = getEffectChain_l(sessionId);
7670 bool chainCreated = false;
7671
7672 if (chain == 0) {
7673 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007674 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007675 chain = new EffectChain(this, sessionId);
7676 addEffectChain_l(chain);
7677 chain->setStrategy(getStrategyForSession_l(sessionId));
7678 chainCreated = true;
7679 }
Steve Block3856b092011-10-20 11:56:00 +01007680 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007681
7682 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007683 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007684 this, effect->desc().name, chain.get());
7685 return BAD_VALUE;
7686 }
7687
7688 status_t status = chain->addEffect_l(effect);
7689 if (status != NO_ERROR) {
7690 if (chainCreated) {
7691 removeEffectChain_l(chain);
7692 }
7693 return status;
7694 }
7695
7696 effect->setDevice(mDevice);
7697 effect->setMode(mAudioFlinger->getMode());
7698 return NO_ERROR;
7699}
7700
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007701void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007702
Steve Block3856b092011-10-20 11:56:00 +01007703 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007704 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007705 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7706 detachAuxEffect_l(effect->id());
7707 }
7708
7709 sp<EffectChain> chain = effect->chain().promote();
7710 if (chain != 0) {
7711 // remove effect chain if removing last effect
7712 if (chain->removeEffect_l(effect) == 0) {
7713 removeEffectChain_l(chain);
7714 }
7715 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007716 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007717 }
7718}
7719
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007720void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007721 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007722{
7723 effectChains = mEffectChains;
7724 for (size_t i = 0; i < mEffectChains.size(); i++) {
7725 mEffectChains[i]->lock();
7726 }
7727}
7728
7729void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007730 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007731{
7732 for (size_t i = 0; i < effectChains.size(); i++) {
7733 effectChains[i]->unlock();
7734 }
7735}
7736
7737sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7738{
7739 Mutex::Autolock _l(mLock);
7740 return getEffectChain_l(sessionId);
7741}
7742
7743sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7744{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745 size_t size = mEffectChains.size();
7746 for (size_t i = 0; i < size; i++) {
7747 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007748 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007749 }
7750 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007751 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007752}
7753
Glenn Kastenf78aee72012-01-04 11:00:47 -08007754void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007755{
7756 Mutex::Autolock _l(mLock);
7757 size_t size = mEffectChains.size();
7758 for (size_t i = 0; i < size; i++) {
7759 mEffectChains[i]->setMode_l(mode);
7760 }
7761}
7762
7763void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007764 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007765 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007766
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007768 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 // delete the effect module if removing last handle on it
7770 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007771 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007772 removeEffect_l(effect);
7773 AudioSystem::unregisterEffect(effect->id());
7774 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007775 }
7776}
7777
7778status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7779{
7780 int session = chain->sessionId();
7781 int16_t *buffer = mMixBuffer;
7782 bool ownsBuffer = false;
7783
Steve Block3856b092011-10-20 11:56:00 +01007784 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 if (session > 0) {
7786 // Only one effect chain can be present in direct output thread and it uses
7787 // the mix buffer as input
7788 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007789 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 buffer = new int16_t[numSamples];
7791 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007792 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 ownsBuffer = true;
7794 }
7795
7796 // Attach all tracks with same session ID to this chain.
7797 for (size_t i = 0; i < mTracks.size(); ++i) {
7798 sp<Track> track = mTracks[i];
7799 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007800 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007802 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 }
7804 }
7805
7806 // indicate all active tracks in the chain
7807 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7808 sp<Track> track = mActiveTracks[i].promote();
7809 if (track == 0) continue;
7810 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007811 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007812 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007813 }
7814 }
7815 }
7816
7817 chain->setInBuffer(buffer, ownsBuffer);
7818 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007819 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007820 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007821 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7822 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007824 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7825 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007826 // Effect chain for other sessions are inserted at beginning of effect
7827 // chains list to be processed before output mix effects. Relative order between other
7828 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007829 size_t size = mEffectChains.size();
7830 size_t i = 0;
7831 for (i = 0; i < size; i++) {
7832 if (mEffectChains[i]->sessionId() < session) break;
7833 }
7834 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007835 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836
7837 return NO_ERROR;
7838}
7839
7840size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7841{
7842 int session = chain->sessionId();
7843
Steve Block3856b092011-10-20 11:56:00 +01007844 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845
7846 for (size_t i = 0; i < mEffectChains.size(); i++) {
7847 if (chain == mEffectChains[i]) {
7848 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007849 // detach all active tracks from the chain
7850 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7851 sp<Track> track = mActiveTracks[i].promote();
7852 if (track == 0) continue;
7853 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007854 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007855 chain.get(), session);
7856 chain->decActiveTrackCnt();
7857 }
7858 }
7859
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860 // detach all tracks with same session ID from this chain
7861 for (size_t i = 0; i < mTracks.size(); ++i) {
7862 sp<Track> track = mTracks[i];
7863 if (session == track->sessionId()) {
7864 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007865 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866 }
7867 }
Eric Laurentde070132010-07-13 04:45:46 -07007868 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869 }
7870 }
7871 return mEffectChains.size();
7872}
7873
Eric Laurentde070132010-07-13 04:45:46 -07007874status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7875 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876{
7877 Mutex::Autolock _l(mLock);
7878 return attachAuxEffect_l(track, EffectId);
7879}
7880
Eric Laurentde070132010-07-13 04:45:46 -07007881status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7882 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007883{
7884 status_t status = NO_ERROR;
7885
7886 if (EffectId == 0) {
7887 track->setAuxBuffer(0, NULL);
7888 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007889 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7890 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 if (effect != 0) {
7892 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7893 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7894 } else {
7895 status = INVALID_OPERATION;
7896 }
7897 } else {
7898 status = BAD_VALUE;
7899 }
7900 }
7901 return status;
7902}
7903
7904void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7905{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007906 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 sp<Track> track = mTracks[i];
7908 if (track->auxEffectId() == effectId) {
7909 attachAuxEffect_l(track, 0);
7910 }
7911 }
7912}
7913
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007914status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7915{
7916 // only one chain per input thread
7917 if (mEffectChains.size() != 0) {
7918 return INVALID_OPERATION;
7919 }
Steve Block3856b092011-10-20 11:56:00 +01007920 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007921
7922 chain->setInBuffer(NULL);
7923 chain->setOutBuffer(NULL);
7924
Eric Laurent59255e42011-07-27 19:49:51 -07007925 checkSuspendOnAddEffectChain_l(chain);
7926
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007927 mEffectChains.add(chain);
7928
7929 return NO_ERROR;
7930}
7931
7932size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7933{
Steve Block3856b092011-10-20 11:56:00 +01007934 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007935 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007936 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7937 chain.get(), mEffectChains.size(), this);
7938 if (mEffectChains.size() == 1) {
7939 mEffectChains.removeAt(0);
7940 }
7941 return 0;
7942}
7943
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944// ----------------------------------------------------------------------------
7945// EffectModule implementation
7946// ----------------------------------------------------------------------------
7947
7948#undef LOG_TAG
7949#define LOG_TAG "AudioFlinger::EffectModule"
7950
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007951AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952 const wp<AudioFlinger::EffectChain>& chain,
7953 effect_descriptor_t *desc,
7954 int id,
7955 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007956 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7957 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7958 // mDescriptor is set below
7959 // mConfig is set by configure() and not used before then
7960 mEffectInterface(NULL),
7961 mStatus(NO_INIT), mState(IDLE),
7962 // mMaxDisableWaitCnt is set by configure() and not used before then
7963 // mDisableWaitCnt is set by process() and updateState() and not used before then
7964 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965{
Steve Block3856b092011-10-20 11:56:00 +01007966 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007968 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 return;
7970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007971
7972 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7973
7974 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007975 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976
7977 if (mStatus != NO_ERROR) {
7978 return;
7979 }
7980 lStatus = init();
7981 if (lStatus < 0) {
7982 mStatus = lStatus;
7983 goto Error;
7984 }
7985
Steve Block3856b092011-10-20 11:56:00 +01007986 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987 return;
7988Error:
7989 EffectRelease(mEffectInterface);
7990 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007991 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992}
7993
7994AudioFlinger::EffectModule::~EffectModule()
7995{
Steve Block3856b092011-10-20 11:56:00 +01007996 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007998 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7999 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8000 sp<ThreadBase> thread = mThread.promote();
8001 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008002 audio_stream_t *stream = thread->stream();
8003 if (stream != NULL) {
8004 stream->remove_audio_effect(stream, mEffectInterface);
8005 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008006 }
8007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008008 // release effect engine
8009 EffectRelease(mEffectInterface);
8010 }
8011}
8012
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008013status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014{
8015 status_t status;
8016
8017 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 int priority = handle->priority();
8019 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008020 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 size_t i;
8022 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008023 EffectHandle *h = mHandles[i];
8024 if (h == NULL || h->destroyed_l()) continue;
8025 // first non destroyed handle is considered in control
8026 if (controlHandle == NULL)
8027 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008028 if (h->priority() <= priority) break;
8029 }
8030 // if inserted in first place, move effect control from previous owner to this handle
8031 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008032 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008033 if (controlHandle != NULL) {
8034 enabled = controlHandle->enabled();
8035 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036 }
Eric Laurent59255e42011-07-27 19:49:51 -07008037 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008038 status = NO_ERROR;
8039 } else {
8040 status = ALREADY_EXISTS;
8041 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008042 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043 mHandles.insertAt(handle, i);
8044 return status;
8045}
8046
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008047size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048{
8049 Mutex::Autolock _l(mLock);
8050 size_t size = mHandles.size();
8051 size_t i;
8052 for (i = 0; i < size; i++) {
8053 if (mHandles[i] == handle) break;
8054 }
8055 if (i == size) {
8056 return size;
8057 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008058 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008059
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008062 if (i == 0) {
8063 EffectHandle *h = controlHandle_l();
8064 if (h != NULL) {
8065 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 }
8067 }
8068
Eric Laurentec437d82011-07-26 20:54:46 -07008069 // Prevent calls to process() and other functions on effect interface from now on.
8070 // The effect engine will be released by the destructor when the last strong reference on
8071 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008072 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008073 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008074 }
8075
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076 return size;
8077}
8078
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008079// must be called with EffectModule::mLock held
8080AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008081{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008082 // the first valid handle in the list has control over the module
8083 for (size_t i = 0; i < mHandles.size(); i++) {
8084 EffectHandle *h = mHandles[i];
8085 if (h != NULL && !h->destroyed_l()) {
8086 return h;
8087 }
8088 }
8089
8090 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008091}
8092
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008093size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008094{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008095 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096 // keep a strong reference on this EffectModule to avoid calling the
8097 // destructor before we exit
8098 sp<EffectModule> keep(this);
8099 {
8100 sp<ThreadBase> thread = mThread.promote();
8101 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008102 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008103 }
8104 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008105 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106}
8107
8108void AudioFlinger::EffectModule::updateState() {
8109 Mutex::Autolock _l(mLock);
8110
8111 switch (mState) {
8112 case RESTART:
8113 reset_l();
8114 // FALL THROUGH
8115
8116 case STARTING:
8117 // clear auxiliary effect input buffer for next accumulation
8118 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8119 memset(mConfig.inputCfg.buffer.raw,
8120 0,
8121 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8122 }
8123 start_l();
8124 mState = ACTIVE;
8125 break;
8126 case STOPPING:
8127 stop_l();
8128 mDisableWaitCnt = mMaxDisableWaitCnt;
8129 mState = STOPPED;
8130 break;
8131 case STOPPED:
8132 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8133 // turn off sequence.
8134 if (--mDisableWaitCnt == 0) {
8135 reset_l();
8136 mState = IDLE;
8137 }
8138 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008139 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 break;
8141 }
8142}
8143
8144void AudioFlinger::EffectModule::process()
8145{
8146 Mutex::Autolock _l(mLock);
8147
Eric Laurentec437d82011-07-26 20:54:46 -07008148 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149 mConfig.inputCfg.buffer.raw == NULL ||
8150 mConfig.outputCfg.buffer.raw == NULL) {
8151 return;
8152 }
8153
Eric Laurent8f45bd72010-08-31 13:50:07 -07008154 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8156 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008157 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008159 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008160 }
8161
8162 // do the actual processing in the effect engine
8163 int ret = (*mEffectInterface)->process(mEffectInterface,
8164 &mConfig.inputCfg.buffer,
8165 &mConfig.outputCfg.buffer);
8166
8167 // force transition to IDLE state when engine is ready
8168 if (mState == STOPPED && ret == -ENODATA) {
8169 mDisableWaitCnt = 1;
8170 }
8171
8172 // clear auxiliary effect input buffer for next accumulation
8173 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008174 memset(mConfig.inputCfg.buffer.raw, 0,
8175 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008176 }
8177 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008178 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8179 // If an insert effect is idle and input buffer is different from output buffer,
8180 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008182 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008183 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8184 int16_t *in = mConfig.inputCfg.buffer.s16;
8185 int16_t *out = mConfig.outputCfg.buffer.s16;
8186 for (size_t i = 0; i < frameCnt; i++) {
8187 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 }
8190 }
8191}
8192
8193void AudioFlinger::EffectModule::reset_l()
8194{
8195 if (mEffectInterface == NULL) {
8196 return;
8197 }
8198 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8199}
8200
8201status_t AudioFlinger::EffectModule::configure()
8202{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 if (mEffectInterface == NULL) {
8204 return NO_INIT;
8205 }
8206
8207 sp<ThreadBase> thread = mThread.promote();
8208 if (thread == 0) {
8209 return DEAD_OBJECT;
8210 }
8211
8212 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008213 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214
8215 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008216 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008218 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 }
Glenn Kasten254af182012-07-03 14:59:05 -07008220 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008221 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8222 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008223 mConfig.inputCfg.samplingRate = thread->sampleRate();
8224 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8225 mConfig.inputCfg.bufferProvider.cookie = NULL;
8226 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8227 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8228 mConfig.outputCfg.bufferProvider.cookie = NULL;
8229 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8230 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8231 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8232 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008233 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008234 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 // - in other sessions:
8236 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8237 // other effect: overwrites output buffer: input buffer == output buffer
8238 // Auxiliary effect:
8239 // accumulates in output buffer: input buffer != output buffer
8240 // Therefore: accumulate <=> input buffer != output buffer
8241 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8242 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8243 } else {
8244 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8245 }
8246 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8247 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8248 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8249 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8250
Steve Block3856b092011-10-20 11:56:00 +01008251 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008252 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8253
Mathias Agopian65ab4712010-07-14 17:59:35 -07008254 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008255 uint32_t size = sizeof(int);
8256 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008257 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008258 sizeof(effect_config_t),
8259 &mConfig,
8260 &size,
8261 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 if (status == 0) {
8263 status = cmdStatus;
8264 }
8265
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008266 if (status == 0 &&
8267 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8268 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8269 effect_param_t *p = (effect_param_t *)buf32;
8270
8271 p->psize = sizeof(uint32_t);
8272 p->vsize = sizeof(uint32_t);
8273 size = sizeof(int);
8274 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8275
8276 uint32_t latency = 0;
8277 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8278 if (pbt != NULL) {
8279 latency = pbt->latency_l();
8280 }
8281
8282 *((int32_t *)p->data + 1)= latency;
8283 (*mEffectInterface)->command(mEffectInterface,
8284 EFFECT_CMD_SET_PARAM,
8285 sizeof(effect_param_t) + 8,
8286 &buf32,
8287 &size,
8288 &cmdStatus);
8289 }
8290
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8292 (1000 * mConfig.outputCfg.buffer.frameCount);
8293
8294 return status;
8295}
8296
8297status_t AudioFlinger::EffectModule::init()
8298{
8299 Mutex::Autolock _l(mLock);
8300 if (mEffectInterface == NULL) {
8301 return NO_INIT;
8302 }
8303 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008304 uint32_t size = sizeof(status_t);
8305 status_t status = (*mEffectInterface)->command(mEffectInterface,
8306 EFFECT_CMD_INIT,
8307 0,
8308 NULL,
8309 &size,
8310 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311 if (status == 0) {
8312 status = cmdStatus;
8313 }
8314 return status;
8315}
8316
Eric Laurentec35a142011-10-05 17:42:25 -07008317status_t AudioFlinger::EffectModule::start()
8318{
8319 Mutex::Autolock _l(mLock);
8320 return start_l();
8321}
8322
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323status_t AudioFlinger::EffectModule::start_l()
8324{
8325 if (mEffectInterface == NULL) {
8326 return NO_INIT;
8327 }
8328 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008329 uint32_t size = sizeof(status_t);
8330 status_t status = (*mEffectInterface)->command(mEffectInterface,
8331 EFFECT_CMD_ENABLE,
8332 0,
8333 NULL,
8334 &size,
8335 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 if (status == 0) {
8337 status = cmdStatus;
8338 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008339 if (status == 0 &&
8340 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8341 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8342 sp<ThreadBase> thread = mThread.promote();
8343 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008344 audio_stream_t *stream = thread->stream();
8345 if (stream != NULL) {
8346 stream->add_audio_effect(stream, mEffectInterface);
8347 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008348 }
8349 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 return status;
8351}
8352
Eric Laurentec437d82011-07-26 20:54:46 -07008353status_t AudioFlinger::EffectModule::stop()
8354{
8355 Mutex::Autolock _l(mLock);
8356 return stop_l();
8357}
8358
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359status_t AudioFlinger::EffectModule::stop_l()
8360{
8361 if (mEffectInterface == NULL) {
8362 return NO_INIT;
8363 }
8364 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008365 uint32_t size = sizeof(status_t);
8366 status_t status = (*mEffectInterface)->command(mEffectInterface,
8367 EFFECT_CMD_DISABLE,
8368 0,
8369 NULL,
8370 &size,
8371 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 if (status == 0) {
8373 status = cmdStatus;
8374 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008375 if (status == 0 &&
8376 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8377 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8378 sp<ThreadBase> thread = mThread.promote();
8379 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008380 audio_stream_t *stream = thread->stream();
8381 if (stream != NULL) {
8382 stream->remove_audio_effect(stream, mEffectInterface);
8383 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008384 }
8385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008386 return status;
8387}
8388
Eric Laurent25f43952010-07-28 05:40:18 -07008389status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8390 uint32_t cmdSize,
8391 void *pCmdData,
8392 uint32_t *replySize,
8393 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394{
8395 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008396// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008397
Eric Laurentec437d82011-07-26 20:54:46 -07008398 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399 return NO_INIT;
8400 }
Eric Laurent25f43952010-07-28 05:40:18 -07008401 status_t status = (*mEffectInterface)->command(mEffectInterface,
8402 cmdCode,
8403 cmdSize,
8404 pCmdData,
8405 replySize,
8406 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008408 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008410 EffectHandle *h = mHandles[i];
8411 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008412 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8413 }
8414 }
8415 }
8416 return status;
8417}
8418
8419status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8420{
8421 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008422 return setEnabled_l(enabled);
8423}
8424
8425// must be called with EffectModule::mLock held
8426status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8427{
8428
Steve Block3856b092011-10-20 11:56:00 +01008429 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430
8431 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008432 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8433 if (enabled && status != NO_ERROR) {
8434 return status;
8435 }
8436
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437 switch (mState) {
8438 // going from disabled to enabled
8439 case IDLE:
8440 mState = STARTING;
8441 break;
8442 case STOPPED:
8443 mState = RESTART;
8444 break;
8445 case STOPPING:
8446 mState = ACTIVE;
8447 break;
8448
8449 // going from enabled to disabled
8450 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008451 mState = STOPPED;
8452 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008453 case STARTING:
8454 mState = IDLE;
8455 break;
8456 case ACTIVE:
8457 mState = STOPPING;
8458 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008459 case DESTROYED:
8460 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 }
8462 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008463 EffectHandle *h = mHandles[i];
8464 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 h->setEnabled(enabled);
8466 }
8467 }
8468 }
8469 return NO_ERROR;
8470}
8471
Glenn Kastenc59c0042012-02-02 14:06:11 -08008472bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473{
8474 switch (mState) {
8475 case RESTART:
8476 case STARTING:
8477 case ACTIVE:
8478 return true;
8479 case IDLE:
8480 case STOPPING:
8481 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008482 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483 default:
8484 return false;
8485 }
8486}
8487
Glenn Kastenc59c0042012-02-02 14:06:11 -08008488bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008489{
8490 switch (mState) {
8491 case RESTART:
8492 case ACTIVE:
8493 case STOPPING:
8494 case STOPPED:
8495 return true;
8496 case IDLE:
8497 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008498 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008499 default:
8500 return false;
8501 }
8502}
8503
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8505{
8506 Mutex::Autolock _l(mLock);
8507 status_t status = NO_ERROR;
8508
8509 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8510 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008511 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008512 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8513 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008514 status_t cmdStatus;
8515 uint32_t volume[2];
8516 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008517 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 volume[0] = *left;
8519 volume[1] = *right;
8520 if (controller) {
8521 pVolume = volume;
8522 }
Eric Laurent25f43952010-07-28 05:40:18 -07008523 status = (*mEffectInterface)->command(mEffectInterface,
8524 EFFECT_CMD_SET_VOLUME,
8525 size,
8526 volume,
8527 &size,
8528 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008529 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8530 *left = volume[0];
8531 *right = volume[1];
8532 }
8533 }
8534 return status;
8535}
8536
8537status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8538{
8539 Mutex::Autolock _l(mLock);
8540 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008541 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8542 // audio pre processing modules on RecordThread can receive both output and
8543 // input device indication in the same call
8544 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8545 if (dev) {
8546 status_t cmdStatus;
8547 uint32_t size = sizeof(status_t);
8548
8549 status = (*mEffectInterface)->command(mEffectInterface,
8550 EFFECT_CMD_SET_DEVICE,
8551 sizeof(uint32_t),
8552 &dev,
8553 &size,
8554 &cmdStatus);
8555 if (status == NO_ERROR) {
8556 status = cmdStatus;
8557 }
8558 }
8559 dev = device & AUDIO_DEVICE_IN_ALL;
8560 if (dev) {
8561 status_t cmdStatus;
8562 uint32_t size = sizeof(status_t);
8563
8564 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8565 EFFECT_CMD_SET_INPUT_DEVICE,
8566 sizeof(uint32_t),
8567 &dev,
8568 &size,
8569 &cmdStatus);
8570 if (status2 == NO_ERROR) {
8571 status2 = cmdStatus;
8572 }
8573 if (status == NO_ERROR) {
8574 status = status2;
8575 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576 }
8577 }
8578 return status;
8579}
8580
Glenn Kastenf78aee72012-01-04 11:00:47 -08008581status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582{
8583 Mutex::Autolock _l(mLock);
8584 status_t status = NO_ERROR;
8585 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008587 uint32_t size = sizeof(status_t);
8588 status = (*mEffectInterface)->command(mEffectInterface,
8589 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008590 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008591 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008592 &size,
8593 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008594 if (status == NO_ERROR) {
8595 status = cmdStatus;
8596 }
8597 }
8598 return status;
8599}
8600
Eric Laurent59255e42011-07-27 19:49:51 -07008601void AudioFlinger::EffectModule::setSuspended(bool suspended)
8602{
8603 Mutex::Autolock _l(mLock);
8604 mSuspended = suspended;
8605}
Glenn Kastena3a85482012-01-04 11:01:11 -08008606
8607bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008608{
8609 Mutex::Autolock _l(mLock);
8610 return mSuspended;
8611}
8612
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008613bool AudioFlinger::EffectModule::purgeHandles()
8614{
8615 bool enabled = false;
8616 Mutex::Autolock _l(mLock);
8617 for (size_t i = 0; i < mHandles.size(); i++) {
8618 EffectHandle *handle = mHandles[i];
8619 if (handle != NULL && !handle->destroyed_l()) {
8620 handle->effect().clear();
8621 if (handle->hasControl()) {
8622 enabled = handle->enabled();
8623 }
8624 }
8625 }
8626 return enabled;
8627}
8628
Mathias Agopian65ab4712010-07-14 17:59:35 -07008629status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8630{
8631 const size_t SIZE = 256;
8632 char buffer[SIZE];
8633 String8 result;
8634
8635 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8636 result.append(buffer);
8637
8638 bool locked = tryLock(mLock);
8639 // failed to lock - AudioFlinger is probably deadlocked
8640 if (!locked) {
8641 result.append("\t\tCould not lock Fx mutex:\n");
8642 }
8643
8644 result.append("\t\tSession Status State Engine:\n");
8645 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8646 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8647 result.append(buffer);
8648
8649 result.append("\t\tDescriptor:\n");
8650 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8651 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8652 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8653 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8654 result.append(buffer);
8655 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8656 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8657 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8658 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8659 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008660 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008661 mDescriptor.apiVersion,
8662 mDescriptor.flags);
8663 result.append(buffer);
8664 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8665 mDescriptor.name);
8666 result.append(buffer);
8667 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8668 mDescriptor.implementor);
8669 result.append(buffer);
8670
8671 result.append("\t\t- Input configuration:\n");
8672 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8673 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8674 (uint32_t)mConfig.inputCfg.buffer.raw,
8675 mConfig.inputCfg.buffer.frameCount,
8676 mConfig.inputCfg.samplingRate,
8677 mConfig.inputCfg.channels,
8678 mConfig.inputCfg.format);
8679 result.append(buffer);
8680
8681 result.append("\t\t- Output configuration:\n");
8682 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8683 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8684 (uint32_t)mConfig.outputCfg.buffer.raw,
8685 mConfig.outputCfg.buffer.frameCount,
8686 mConfig.outputCfg.samplingRate,
8687 mConfig.outputCfg.channels,
8688 mConfig.outputCfg.format);
8689 result.append(buffer);
8690
8691 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8692 result.append(buffer);
8693 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8694 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008695 EffectHandle *handle = mHandles[i];
8696 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008697 handle->dump(buffer, SIZE);
8698 result.append(buffer);
8699 }
8700 }
8701
8702 result.append("\n");
8703
8704 write(fd, result.string(), result.length());
8705
8706 if (locked) {
8707 mLock.unlock();
8708 }
8709
8710 return NO_ERROR;
8711}
8712
8713// ----------------------------------------------------------------------------
8714// EffectHandle implementation
8715// ----------------------------------------------------------------------------
8716
8717#undef LOG_TAG
8718#define LOG_TAG "AudioFlinger::EffectHandle"
8719
8720AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8721 const sp<AudioFlinger::Client>& client,
8722 const sp<IEffectClient>& effectClient,
8723 int32_t priority)
8724 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008725 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008726 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008727{
Steve Block3856b092011-10-20 11:56:00 +01008728 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008730 if (client == 0) {
8731 return;
8732 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8734 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8735 if (mCblkMemory != 0) {
8736 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8737
Glenn Kastena0d68332012-01-27 16:47:15 -08008738 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 new(mCblk) effect_param_cblk_t();
8740 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008742 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008743 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744 return;
8745 }
8746}
8747
8748AudioFlinger::EffectHandle::~EffectHandle()
8749{
Steve Block3856b092011-10-20 11:56:00 +01008750 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008751
8752 if (mEffect == 0) {
8753 mDestroyed = true;
8754 return;
8755 }
8756 mEffect->lock();
8757 mDestroyed = true;
8758 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008759 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760}
8761
8762status_t AudioFlinger::EffectHandle::enable()
8763{
Steve Block3856b092011-10-20 11:56:00 +01008764 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 if (!mHasControl) return INVALID_OPERATION;
8766 if (mEffect == 0) return DEAD_OBJECT;
8767
Eric Laurentdb7c0792011-08-10 10:37:50 -07008768 if (mEnabled) {
8769 return NO_ERROR;
8770 }
8771
Eric Laurent59255e42011-07-27 19:49:51 -07008772 mEnabled = true;
8773
8774 sp<ThreadBase> thread = mEffect->thread().promote();
8775 if (thread != 0) {
8776 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8777 }
8778
8779 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8780 if (mEffect->suspended()) {
8781 return NO_ERROR;
8782 }
8783
Eric Laurentdb7c0792011-08-10 10:37:50 -07008784 status_t status = mEffect->setEnabled(true);
8785 if (status != NO_ERROR) {
8786 if (thread != 0) {
8787 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8788 }
8789 mEnabled = false;
8790 }
8791 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008792}
8793
8794status_t AudioFlinger::EffectHandle::disable()
8795{
Steve Block3856b092011-10-20 11:56:00 +01008796 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008798 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799
Eric Laurentdb7c0792011-08-10 10:37:50 -07008800 if (!mEnabled) {
8801 return NO_ERROR;
8802 }
Eric Laurent59255e42011-07-27 19:49:51 -07008803 mEnabled = false;
8804
8805 if (mEffect->suspended()) {
8806 return NO_ERROR;
8807 }
8808
8809 status_t status = mEffect->setEnabled(false);
8810
8811 sp<ThreadBase> thread = mEffect->thread().promote();
8812 if (thread != 0) {
8813 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8814 }
8815
8816 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817}
8818
8819void AudioFlinger::EffectHandle::disconnect()
8820{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008821 disconnect(true);
8822}
8823
Glenn Kasten58123c32012-02-03 10:32:24 -08008824void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008825{
Glenn Kasten58123c32012-02-03 10:32:24 -08008826 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008827 if (mEffect == 0) {
8828 return;
8829 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008830 // restore suspended effects if the disconnected handle was enabled and the last one.
8831 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008832 sp<ThreadBase> thread = mEffect->thread().promote();
8833 if (thread != 0) {
8834 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8835 }
Eric Laurent59255e42011-07-27 19:49:51 -07008836 }
8837
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838 // release sp on module => module destructor can be called now
8839 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008841 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008842 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008843 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8844 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008845 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008846 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008847 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8848 mClient.clear();
8849 }
8850}
8851
Eric Laurent25f43952010-07-28 05:40:18 -07008852status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8853 uint32_t cmdSize,
8854 void *pCmdData,
8855 uint32_t *replySize,
8856 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857{
Steve Block3856b092011-10-20 11:56:00 +01008858// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008859// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860
8861 // only get parameter command is permitted for applications not controlling the effect
8862 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8863 return INVALID_OPERATION;
8864 }
8865 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008866 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867
8868 // handle commands that are not forwarded transparently to effect engine
8869 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8870 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8871 // no risk to block the whole media server process or mixer threads is we are stuck here
8872 Mutex::Autolock _l(mCblk->lock);
8873 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8874 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8875 mCblk->serverIndex = 0;
8876 mCblk->clientIndex = 0;
8877 return BAD_VALUE;
8878 }
8879 status_t status = NO_ERROR;
8880 while (mCblk->serverIndex < mCblk->clientIndex) {
8881 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008882 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 int *p = (int *)(mBuffer + mCblk->serverIndex);
8884 int size = *p++;
8885 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008886 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887 break;
8888 }
8889 effect_param_t *param = (effect_param_t *)p;
8890 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008891 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 mCblk->serverIndex += size;
8893 continue;
8894 }
Eric Laurent25f43952010-07-28 05:40:18 -07008895 uint32_t psize = sizeof(effect_param_t) +
8896 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8897 param->vsize;
8898 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8899 psize,
8900 p,
8901 &rsize,
8902 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008903 // stop at first error encountered
8904 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008906 *(int *)pReplyData = reply;
8907 break;
8908 } else if (reply != NO_ERROR) {
8909 *(int *)pReplyData = reply;
8910 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911 }
8912 mCblk->serverIndex += size;
8913 }
8914 mCblk->serverIndex = 0;
8915 mCblk->clientIndex = 0;
8916 return status;
8917 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008918 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919 return enable();
8920 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008921 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922 return disable();
8923 }
8924
8925 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8926}
8927
Eric Laurent59255e42011-07-27 19:49:51 -07008928void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929{
Steve Block3856b092011-10-20 11:56:00 +01008930 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931
8932 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008933 mEnabled = enabled;
8934
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 if (signal && mEffectClient != 0) {
8936 mEffectClient->controlStatusChanged(hasControl);
8937 }
8938}
8939
Eric Laurent25f43952010-07-28 05:40:18 -07008940void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8941 uint32_t cmdSize,
8942 void *pCmdData,
8943 uint32_t replySize,
8944 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945{
8946 if (mEffectClient != 0) {
8947 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8948 }
8949}
8950
8951
8952
8953void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8954{
8955 if (mEffectClient != 0) {
8956 mEffectClient->enableStatusChanged(enabled);
8957 }
8958}
8959
8960status_t AudioFlinger::EffectHandle::onTransact(
8961 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8962{
8963 return BnEffect::onTransact(code, data, reply, flags);
8964}
8965
8966
8967void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8968{
Glenn Kastena0d68332012-01-27 16:47:15 -08008969 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970
8971 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008972 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973 mPriority,
8974 mHasControl,
8975 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008976 mCblk ? mCblk->clientIndex : 0,
8977 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978 );
8979
8980 if (locked) {
8981 mCblk->lock.unlock();
8982 }
8983}
8984
8985#undef LOG_TAG
8986#define LOG_TAG "AudioFlinger::EffectChain"
8987
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008988AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008990 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008991 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8992 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993{
Dima Zavinfce7a472011-04-19 22:30:36 -07008994 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008995 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008996 return;
8997 }
8998 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8999 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009000}
9001
9002AudioFlinger::EffectChain::~EffectChain()
9003{
9004 if (mOwnInBuffer) {
9005 delete mInBuffer;
9006 }
9007
9008}
9009
Eric Laurent59255e42011-07-27 19:49:51 -07009010// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009011sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013 size_t size = mEffects.size();
9014
9015 for (size_t i = 0; i < size; i++) {
9016 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009017 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009018 }
9019 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009020 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021}
9022
Eric Laurent59255e42011-07-27 19:49:51 -07009023// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009024sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009026 size_t size = mEffects.size();
9027
9028 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009029 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9030 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009031 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 }
9033 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009034 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035}
9036
Eric Laurent59255e42011-07-27 19:49:51 -07009037// getEffectFromType_l() must be called with ThreadBase::mLock held
9038sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9039 const effect_uuid_t *type)
9040{
Eric Laurent59255e42011-07-27 19:49:51 -07009041 size_t size = mEffects.size();
9042
9043 for (size_t i = 0; i < size; i++) {
9044 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009045 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009046 }
9047 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009048 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009049}
9050
Eric Laurent91b14c42012-05-30 12:30:29 -07009051void AudioFlinger::EffectChain::clearInputBuffer()
9052{
9053 Mutex::Autolock _l(mLock);
9054 sp<ThreadBase> thread = mThread.promote();
9055 if (thread == 0) {
9056 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9057 return;
9058 }
9059 clearInputBuffer_l(thread);
9060}
9061
9062// Must be called with EffectChain::mLock locked
9063void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9064{
9065 size_t numSamples = thread->frameCount() * thread->channelCount();
9066 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9067
9068}
9069
Mathias Agopian65ab4712010-07-14 17:59:35 -07009070// Must be called with EffectChain::mLock locked
9071void AudioFlinger::EffectChain::process_l()
9072{
Eric Laurentdac69112010-09-28 14:09:57 -07009073 sp<ThreadBase> thread = mThread.promote();
9074 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009075 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009076 return;
9077 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009078 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9079 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009080 // always process effects unless no more tracks are on the session and the effect tail
9081 // has been rendered
9082 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009083 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009084 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009085
Eric Laurent544fe9b2011-11-11 15:42:52 -08009086 if (!tracksOnSession && mTailBufferCount == 0) {
9087 doProcess = false;
9088 }
9089
9090 if (activeTrackCnt() == 0) {
9091 // if no track is active and the effect tail has not been rendered,
9092 // the input buffer must be cleared here as the mixer process will not do it
9093 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009094 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009095 if (mTailBufferCount > 0) {
9096 mTailBufferCount--;
9097 }
9098 }
9099 }
Eric Laurentdac69112010-09-28 14:09:57 -07009100 }
9101
Mathias Agopian65ab4712010-07-14 17:59:35 -07009102 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009103 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009104 for (size_t i = 0; i < size; i++) {
9105 mEffects[i]->process();
9106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009107 }
9108 for (size_t i = 0; i < size; i++) {
9109 mEffects[i]->updateState();
9110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009111}
9112
Eric Laurentcab11242010-07-15 12:50:15 -07009113// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009114status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115{
9116 effect_descriptor_t desc = effect->desc();
9117 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9118
9119 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009120 effect->setChain(this);
9121 sp<ThreadBase> thread = mThread.promote();
9122 if (thread == 0) {
9123 return NO_INIT;
9124 }
9125 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009126
9127 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9128 // Auxiliary effects are inserted at the beginning of mEffects vector as
9129 // they are processed first and accumulated in chain input buffer
9130 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009131
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132 // the input buffer for auxiliary effect contains mono samples in
9133 // 32 bit format. This is to avoid saturation in AudoMixer
9134 // accumulation stage. Saturation is done in EffectModule::process() before
9135 // calling the process in effect engine
9136 size_t numSamples = thread->frameCount();
9137 int32_t *buffer = new int32_t[numSamples];
9138 memset(buffer, 0, numSamples * sizeof(int32_t));
9139 effect->setInBuffer((int16_t *)buffer);
9140 // auxiliary effects output samples to chain input buffer for further processing
9141 // by insert effects
9142 effect->setOutBuffer(mInBuffer);
9143 } else {
9144 // Insert effects are inserted at the end of mEffects vector as they are processed
9145 // after track and auxiliary effects.
9146 // Insert effect order as a function of indicated preference:
9147 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9148 // another effect is present
9149 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9150 // last effect claiming first position
9151 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9152 // first effect claiming last position
9153 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9154 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9155 // already present
9156
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009157 size_t size = mEffects.size();
9158 size_t idx_insert = size;
9159 ssize_t idx_insert_first = -1;
9160 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009161
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009162 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009163 effect_descriptor_t d = mEffects[i]->desc();
9164 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9165 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9166 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9167 // check invalid effect chaining combinations
9168 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9169 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009170 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171 return INVALID_OPERATION;
9172 }
9173 // remember position of first insert effect and by default
9174 // select this as insert position for new effect
9175 if (idx_insert == size) {
9176 idx_insert = i;
9177 }
9178 // remember position of last insert effect claiming
9179 // first position
9180 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9181 idx_insert_first = i;
9182 }
9183 // remember position of first insert effect claiming
9184 // last position
9185 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9186 idx_insert_last == -1) {
9187 idx_insert_last = i;
9188 }
9189 }
9190 }
9191
9192 // modify idx_insert from first position if needed
9193 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9194 if (idx_insert_last != -1) {
9195 idx_insert = idx_insert_last;
9196 } else {
9197 idx_insert = size;
9198 }
9199 } else {
9200 if (idx_insert_first != -1) {
9201 idx_insert = idx_insert_first + 1;
9202 }
9203 }
9204
9205 // always read samples from chain input buffer
9206 effect->setInBuffer(mInBuffer);
9207
9208 // if last effect in the chain, output samples to chain
9209 // output buffer, otherwise to chain input buffer
9210 if (idx_insert == size) {
9211 if (idx_insert != 0) {
9212 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9213 mEffects[idx_insert-1]->configure();
9214 }
9215 effect->setOutBuffer(mOutBuffer);
9216 } else {
9217 effect->setOutBuffer(mInBuffer);
9218 }
9219 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009220
Steve Block3856b092011-10-20 11:56:00 +01009221 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222 }
9223 effect->configure();
9224 return NO_ERROR;
9225}
9226
Eric Laurentcab11242010-07-15 12:50:15 -07009227// removeEffect_l() must be called with PlaybackThread::mLock held
9228size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009229{
9230 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009231 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009232 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9233
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009234 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009236 // calling stop here will remove pre-processing effect from the audio HAL.
9237 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9238 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009239 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9240 mEffects[i]->state() == EffectModule::STOPPING) {
9241 mEffects[i]->stop();
9242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009243 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9244 delete[] effect->inBuffer();
9245 } else {
9246 if (i == size - 1 && i != 0) {
9247 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9248 mEffects[i - 1]->configure();
9249 }
9250 }
9251 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009252 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009253 break;
9254 }
9255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009256
9257 return mEffects.size();
9258}
9259
Eric Laurentcab11242010-07-15 12:50:15 -07009260// setDevice_l() must be called with PlaybackThread::mLock held
9261void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009262{
9263 size_t size = mEffects.size();
9264 for (size_t i = 0; i < size; i++) {
9265 mEffects[i]->setDevice(device);
9266 }
9267}
9268
Eric Laurentcab11242010-07-15 12:50:15 -07009269// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009270void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009271{
9272 size_t size = mEffects.size();
9273 for (size_t i = 0; i < size; i++) {
9274 mEffects[i]->setMode(mode);
9275 }
9276}
9277
Eric Laurentcab11242010-07-15 12:50:15 -07009278// setVolume_l() must be called with PlaybackThread::mLock held
9279bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009280{
9281 uint32_t newLeft = *left;
9282 uint32_t newRight = *right;
9283 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009284 int ctrlIdx = -1;
9285 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009286
Eric Laurentcab11242010-07-15 12:50:15 -07009287 // first update volume controller
9288 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009289 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009290 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9291 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009292 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009293 break;
9294 }
9295 }
9296
9297 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009298 if (hasControl) {
9299 *left = mNewLeftVolume;
9300 *right = mNewRightVolume;
9301 }
9302 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009303 }
9304
9305 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009306 mLeftVolume = newLeft;
9307 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009308
9309 // second get volume update from volume controller
9310 if (ctrlIdx >= 0) {
9311 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009312 mNewLeftVolume = newLeft;
9313 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009314 }
9315 // then indicate volume to all other effects in chain.
9316 // Pass altered volume to effects before volume controller
9317 // and requested volume to effects after controller
9318 uint32_t lVol = newLeft;
9319 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009320
Mathias Agopian65ab4712010-07-14 17:59:35 -07009321 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009322 if ((int)i == ctrlIdx) continue;
9323 // this also works for ctrlIdx == -1 when there is no volume controller
9324 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009325 lVol = *left;
9326 rVol = *right;
9327 }
9328 mEffects[i]->setVolume(&lVol, &rVol, false);
9329 }
9330 *left = newLeft;
9331 *right = newRight;
9332
9333 return hasControl;
9334}
9335
Mathias Agopian65ab4712010-07-14 17:59:35 -07009336status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9337{
9338 const size_t SIZE = 256;
9339 char buffer[SIZE];
9340 String8 result;
9341
9342 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9343 result.append(buffer);
9344
9345 bool locked = tryLock(mLock);
9346 // failed to lock - AudioFlinger is probably deadlocked
9347 if (!locked) {
9348 result.append("\tCould not lock mutex:\n");
9349 }
9350
Eric Laurentcab11242010-07-15 12:50:15 -07009351 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9352 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009353 mEffects.size(),
9354 (uint32_t)mInBuffer,
9355 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356 mActiveTrackCnt);
9357 result.append(buffer);
9358 write(fd, result.string(), result.size());
9359
9360 for (size_t i = 0; i < mEffects.size(); ++i) {
9361 sp<EffectModule> effect = mEffects[i];
9362 if (effect != 0) {
9363 effect->dump(fd, args);
9364 }
9365 }
9366
9367 if (locked) {
9368 mLock.unlock();
9369 }
9370
9371 return NO_ERROR;
9372}
9373
Eric Laurent59255e42011-07-27 19:49:51 -07009374// must be called with ThreadBase::mLock held
9375void AudioFlinger::EffectChain::setEffectSuspended_l(
9376 const effect_uuid_t *type, bool suspend)
9377{
9378 sp<SuspendedEffectDesc> desc;
9379 // use effect type UUID timelow as key as there is no real risk of identical
9380 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009381 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009382 if (suspend) {
9383 if (index >= 0) {
9384 desc = mSuspendedEffects.valueAt(index);
9385 } else {
9386 desc = new SuspendedEffectDesc();
9387 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9388 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009389 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009390 }
9391 if (desc->mRefCount++ == 0) {
9392 sp<EffectModule> effect = getEffectIfEnabled(type);
9393 if (effect != 0) {
9394 desc->mEffect = effect;
9395 effect->setSuspended(true);
9396 effect->setEnabled(false);
9397 }
9398 }
9399 } else {
9400 if (index < 0) {
9401 return;
9402 }
9403 desc = mSuspendedEffects.valueAt(index);
9404 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009405 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009406 desc->mRefCount = 1;
9407 }
9408 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009409 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009410 if (desc->mEffect != 0) {
9411 sp<EffectModule> effect = desc->mEffect.promote();
9412 if (effect != 0) {
9413 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009414 effect->lock();
9415 EffectHandle *handle = effect->controlHandle_l();
9416 if (handle != NULL && !handle->destroyed_l()) {
9417 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009418 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009419 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009420 }
9421 desc->mEffect.clear();
9422 }
9423 mSuspendedEffects.removeItemsAt(index);
9424 }
9425 }
9426}
9427
9428// must be called with ThreadBase::mLock held
9429void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9430{
9431 sp<SuspendedEffectDesc> desc;
9432
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009433 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009434 if (suspend) {
9435 if (index >= 0) {
9436 desc = mSuspendedEffects.valueAt(index);
9437 } else {
9438 desc = new SuspendedEffectDesc();
9439 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009440 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009441 }
9442 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009443 Vector< sp<EffectModule> > effects;
9444 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009445 for (size_t i = 0; i < effects.size(); i++) {
9446 setEffectSuspended_l(&effects[i]->desc().type, true);
9447 }
9448 }
9449 } else {
9450 if (index < 0) {
9451 return;
9452 }
9453 desc = mSuspendedEffects.valueAt(index);
9454 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009455 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009456 desc->mRefCount = 1;
9457 }
9458 if (--desc->mRefCount == 0) {
9459 Vector<const effect_uuid_t *> types;
9460 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9461 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9462 continue;
9463 }
9464 types.add(&mSuspendedEffects.valueAt(i)->mType);
9465 }
9466 for (size_t i = 0; i < types.size(); i++) {
9467 setEffectSuspended_l(types[i], false);
9468 }
Steve Block3856b092011-10-20 11:56:00 +01009469 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009470 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9471 }
9472 }
9473}
9474
Eric Laurent6bffdb82011-09-23 08:40:41 -07009475
9476// The volume effect is used for automated tests only
9477#ifndef OPENSL_ES_H_
9478static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9479 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9480const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9481#endif //OPENSL_ES_H_
9482
Eric Laurentdb7c0792011-08-10 10:37:50 -07009483bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9484{
9485 // auxiliary effects and visualizer are never suspended on output mix
9486 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9487 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009488 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9489 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009490 return false;
9491 }
9492 return true;
9493}
9494
Glenn Kastend0539712012-01-30 12:56:03 -08009495void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009496{
Glenn Kastend0539712012-01-30 12:56:03 -08009497 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009498 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009499 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9500 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009501 }
Eric Laurent59255e42011-07-27 19:49:51 -07009502 }
Eric Laurent59255e42011-07-27 19:49:51 -07009503}
9504
9505sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9506 const effect_uuid_t *type)
9507{
Glenn Kasten090f0192012-01-30 13:00:02 -08009508 sp<EffectModule> effect = getEffectFromType_l(type);
9509 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009510}
9511
9512void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9513 bool enabled)
9514{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009515 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 if (enabled) {
9517 if (index < 0) {
9518 // if the effect is not suspend check if all effects are suspended
9519 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9520 if (index < 0) {
9521 return;
9522 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009523 if (!isEffectEligibleForSuspend(effect->desc())) {
9524 return;
9525 }
Eric Laurent59255e42011-07-27 19:49:51 -07009526 setEffectSuspended_l(&effect->desc().type, enabled);
9527 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009528 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009529 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009530 return;
9531 }
Eric Laurent59255e42011-07-27 19:49:51 -07009532 }
Steve Block3856b092011-10-20 11:56:00 +01009533 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009534 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009535 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9536 // if effect is requested to suspended but was not yet enabled, supend it now.
9537 if (desc->mEffect == 0) {
9538 desc->mEffect = effect;
9539 effect->setEnabled(false);
9540 effect->setSuspended(true);
9541 }
9542 } else {
9543 if (index < 0) {
9544 return;
9545 }
Steve Block3856b092011-10-20 11:56:00 +01009546 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009547 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009548 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9549 desc->mEffect.clear();
9550 effect->setSuspended(false);
9551 }
9552}
9553
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554#undef LOG_TAG
9555#define LOG_TAG "AudioFlinger"
9556
9557// ----------------------------------------------------------------------------
9558
9559status_t AudioFlinger::onTransact(
9560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9561{
9562 return BnAudioFlinger::onTransact(code, data, reply, flags);
9563}
9564
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565}; // namespace android