blob: e66abb163d7878319a325275c25773e4940fac06 [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
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, audio_devices_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) {
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700876 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
Eric Laurentbee53372011-08-29 12:42:48 -0700877 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700878 thread->setEffectSuspended(FX_IID_AEC,
879 suspend,
880 track->sessionId());
881 thread->setEffectSuspended(FX_IID_NS,
882 suspend,
883 track->sessionId());
884 }
885 }
Eric Laurentbee53372011-08-29 12:42:48 -0700886 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700887 }
888 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700889 String8 screenState;
890 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
891 bool isOff = screenState == "off";
892 if (isOff != (gScreenState & 1)) {
893 gScreenState = ((gScreenState & ~1) + 2) | isOff;
894 }
895 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700896 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 }
898
899 // hold a strong ref on thread in case closeOutput() or closeInput() is called
900 // and the thread is exited once the lock is released
901 sp<ThreadBase> thread;
902 {
903 Mutex::Autolock _l(mLock);
904 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700905 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800907 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700908 // indicate output device change to all input threads for pre processing
909 AudioParameter param = AudioParameter(keyValuePairs);
910 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700911 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
912 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700913 for (size_t i = 0; i < mRecordThreads.size(); i++) {
914 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
915 }
916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800919 if (thread != 0) {
920 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922 return BAD_VALUE;
923}
924
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800925String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800927// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
929
Eric Laurenta4c5a552012-03-29 10:12:40 -0700930 Mutex::Autolock _l(mLock);
931
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700933 String8 out_s8;
934
Dima Zavin799a70e2011-04-18 16:57:27 -0700935 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800936 char *s;
937 {
938 AutoMutex lock(mHardwareLock);
939 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700940 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800941 s = dev->get_parameters(dev, keys.string());
942 mHardwareStatus = AUDIO_HW_IDLE;
943 }
John Grossmanef7740b2012-02-09 11:28:36 -0800944 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700945 free(s);
946 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700947 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 }
949
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
951 if (playbackThread != NULL) {
952 return playbackThread->getParameters(keys);
953 }
954 RecordThread *recordThread = checkRecordThread_l(ioHandle);
955 if (recordThread != NULL) {
956 return recordThread->getParameters(keys);
957 }
958 return String8("");
959}
960
Glenn Kastendd8104c2012-07-02 12:42:44 -0700961size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
962 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963{
Eric Laurenta1884f92011-08-23 08:25:03 -0700964 status_t ret = initCheck();
965 if (ret != NO_ERROR) {
966 return 0;
967 }
968
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800969 AutoMutex lock(mHardwareLock);
970 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700971 struct audio_config config = {
972 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700973 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700974 format: format,
975 };
976 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800977 mHardwareStatus = AUDIO_HW_IDLE;
978 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979}
980
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800981unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 Mutex::Autolock _l(mLock);
984
985 RecordThread *recordThread = checkRecordThread_l(ioHandle);
986 if (recordThread != NULL) {
987 return recordThread->getInputFramesLost();
988 }
989 return 0;
990}
991
992status_t AudioFlinger::setVoiceVolume(float value)
993{
Eric Laurenta1884f92011-08-23 08:25:03 -0700994 status_t ret = initCheck();
995 if (ret != NO_ERROR) {
996 return ret;
997 }
998
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 // check calling permissions
1000 if (!settingsAllowed()) {
1001 return PERMISSION_DENIED;
1002 }
1003
1004 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001005 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001006 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 mHardwareStatus = AUDIO_HW_IDLE;
1008
1009 return ret;
1010}
1011
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001012status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1013 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014{
1015 status_t status;
1016
1017 Mutex::Autolock _l(mLock);
1018
1019 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1020 if (playbackThread != NULL) {
1021 return playbackThread->getRenderPosition(halFrames, dspFrames);
1022 }
1023
1024 return BAD_VALUE;
1025}
1026
1027void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1028{
1029
1030 Mutex::Autolock _l(mLock);
1031
Glenn Kastenbb001922012-02-03 11:10:26 -08001032 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 if (mNotificationClients.indexOfKey(pid) < 0) {
1034 sp<NotificationClient> notificationClient = new NotificationClient(this,
1035 client,
1036 pid);
Steve Block3856b092011-10-20 11:56:00 +01001037 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038
1039 mNotificationClients.add(pid, notificationClient);
1040
1041 sp<IBinder> binder = client->asBinder();
1042 binder->linkToDeath(notificationClient);
1043
1044 // the config change is always sent from playback or record threads to avoid deadlock
1045 // with AudioSystem::gLock
1046 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1047 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1048 }
1049
1050 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1051 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1052 }
1053 }
1054}
1055
1056void AudioFlinger::removeNotificationClient(pid_t pid)
1057{
1058 Mutex::Autolock _l(mLock);
1059
Glenn Kastena3b09252012-01-20 09:19:01 -08001060 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001061
Steve Block3856b092011-10-20 11:56:00 +01001062 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001063 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001064 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001065 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001066 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001067 ALOGV(" pid %d @ %d", ref->mPid, i);
1068 if (ref->mPid == pid) {
1069 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 mAudioSessionRefs.removeAt(i);
1071 delete ref;
1072 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001074 } else {
1075 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001076 }
1077 }
1078 if (removed) {
1079 purgeStaleEffects_l();
1080 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081}
1082
1083// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001084void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085{
1086 size_t size = mNotificationClients.size();
1087 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001088 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1089 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090 }
1091}
1092
1093// removeClient_l() must be called with AudioFlinger::mLock held
1094void AudioFlinger::removeClient_l(pid_t pid)
1095{
Steve Block3856b092011-10-20 11:56:00 +01001096 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097 mClients.removeItem(pid);
1098}
1099
Eric Laurent717e1282012-06-29 16:36:52 -07001100// getEffectThread_l() must be called with AudioFlinger::mLock held
1101sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1102{
1103 sp<PlaybackThread> thread;
1104
1105 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1106 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1107 ALOG_ASSERT(thread == 0);
1108 thread = mPlaybackThreads.valueAt(i);
1109 }
1110 }
1111
1112 return thread;
1113}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114
1115// ----------------------------------------------------------------------------
1116
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001117AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001118 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001120 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001121 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001122 // mChannelMask
1123 mChannelCount(0),
1124 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1125 mParamStatus(NO_ERROR),
Glenn Kasten94479fd2012-07-09 15:39:54 -07001126 mStandby(false), mDevice((audio_devices_t) device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001127 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128{
1129}
1130
1131AudioFlinger::ThreadBase::~ThreadBase()
1132{
1133 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001134 // do not lock the mutex in destructor
1135 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001136 if (mPowerManager != 0) {
1137 sp<IBinder> binder = mPowerManager->asBinder();
1138 binder->unlinkToDeath(mDeathRecipient);
1139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140}
1141
1142void AudioFlinger::ThreadBase::exit()
1143{
Steve Block3856b092011-10-20 11:56:00 +01001144 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001146 // This lock prevents the following race in thread (uniprocessor for illustration):
1147 // if (!exitPending()) {
1148 // // context switch from here to exit()
1149 // // exit() calls requestExit(), what exitPending() observes
1150 // // exit() calls signal(), which is dropped since no waiters
1151 // // context switch back from exit() to here
1152 // mWaitWorkCV.wait(...);
1153 // // now thread is hung
1154 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001155 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 requestExit();
1157 mWaitWorkCV.signal();
1158 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001159 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1160 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 requestExitAndWait();
1162}
1163
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1165{
1166 status_t status;
1167
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 Mutex::Autolock _l(mLock);
1170
1171 mNewParameters.add(keyValuePairs);
1172 mWaitWorkCV.signal();
1173 // wait condition with timeout in case the thread loop has exited
1174 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001175 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 status = mParamStatus;
1177 mWaitWorkCV.signal();
1178 } else {
1179 status = TIMED_OUT;
1180 }
1181 return status;
1182}
1183
1184void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1185{
1186 Mutex::Autolock _l(mLock);
1187 sendConfigEvent_l(event, param);
1188}
1189
1190// sendConfigEvent_l() must be called with ThreadBase::mLock held
1191void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1192{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001193 ConfigEvent configEvent;
1194 configEvent.mEvent = event;
1195 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 mWaitWorkCV.signal();
1199}
1200
1201void AudioFlinger::ThreadBase::processConfigEvents()
1202{
1203 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001204 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001205 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001206 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 mConfigEvents.removeAt(0);
1208 // release mLock before locking AudioFlinger mLock: lock order is always
1209 // AudioFlinger then ThreadBase to avoid cross deadlock
1210 mLock.unlock();
1211 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001212 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 mLock.lock();
1215 }
1216 mLock.unlock();
1217}
1218
1219status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1220{
1221 const size_t SIZE = 256;
1222 char buffer[SIZE];
1223 String8 result;
1224
1225 bool locked = tryLock(mLock);
1226 if (!locked) {
1227 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1228 write(fd, buffer, strlen(buffer));
1229 }
1230
Eric Laurent612bbb52012-03-14 15:03:26 -07001231 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1232 result.append(buffer);
1233 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1234 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1236 result.append(buffer);
1237 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1238 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001239 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1240 result.append(buffer);
1241 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 result.append(buffer);
1243 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1244 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001245 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1246 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1248 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001249 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 result.append(buffer);
1251
1252 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1253 result.append(buffer);
1254 result.append(" Index Command");
1255 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1256 snprintf(buffer, SIZE, "\n %02d ", i);
1257 result.append(buffer);
1258 result.append(mNewParameters[i]);
1259 }
1260
1261 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1262 result.append(buffer);
1263 snprintf(buffer, SIZE, " Index event param\n");
1264 result.append(buffer);
1265 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001266 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 result.append(buffer);
1268 }
1269 result.append("\n");
1270
1271 write(fd, result.string(), result.size());
1272
1273 if (locked) {
1274 mLock.unlock();
1275 }
1276 return NO_ERROR;
1277}
1278
Eric Laurent1d2bff02011-07-24 17:49:51 -07001279status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1280{
1281 const size_t SIZE = 256;
1282 char buffer[SIZE];
1283 String8 result;
1284
1285 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1286 write(fd, buffer, strlen(buffer));
1287
1288 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1289 sp<EffectChain> chain = mEffectChains[i];
1290 if (chain != 0) {
1291 chain->dump(fd, args);
1292 }
1293 }
1294 return NO_ERROR;
1295}
1296
Eric Laurentfeb0db62011-07-22 09:04:31 -07001297void AudioFlinger::ThreadBase::acquireWakeLock()
1298{
1299 Mutex::Autolock _l(mLock);
1300 acquireWakeLock_l();
1301}
1302
1303void AudioFlinger::ThreadBase::acquireWakeLock_l()
1304{
1305 if (mPowerManager == 0) {
1306 // use checkService() to avoid blocking if power service is not up yet
1307 sp<IBinder> binder =
1308 defaultServiceManager()->checkService(String16("power"));
1309 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001310 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001311 } else {
1312 mPowerManager = interface_cast<IPowerManager>(binder);
1313 binder->linkToDeath(mDeathRecipient);
1314 }
1315 }
1316 if (mPowerManager != 0) {
1317 sp<IBinder> binder = new BBinder();
1318 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1319 binder,
1320 String16(mName));
1321 if (status == NO_ERROR) {
1322 mWakeLockToken = binder;
1323 }
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001325 }
1326}
1327
1328void AudioFlinger::ThreadBase::releaseWakeLock()
1329{
1330 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001331 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001332}
1333
1334void AudioFlinger::ThreadBase::releaseWakeLock_l()
1335{
1336 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001337 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001338 if (mPowerManager != 0) {
1339 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1340 }
1341 mWakeLockToken.clear();
1342 }
1343}
1344
1345void AudioFlinger::ThreadBase::clearPowerManager()
1346{
1347 Mutex::Autolock _l(mLock);
1348 releaseWakeLock_l();
1349 mPowerManager.clear();
1350}
1351
1352void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1353{
1354 sp<ThreadBase> thread = mThread.promote();
1355 if (thread != 0) {
1356 thread->clearPowerManager();
1357 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001358 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001359}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001360
Eric Laurent59255e42011-07-27 19:49:51 -07001361void AudioFlinger::ThreadBase::setEffectSuspended(
1362 const effect_uuid_t *type, bool suspend, int sessionId)
1363{
1364 Mutex::Autolock _l(mLock);
1365 setEffectSuspended_l(type, suspend, sessionId);
1366}
1367
1368void AudioFlinger::ThreadBase::setEffectSuspended_l(
1369 const effect_uuid_t *type, bool suspend, int sessionId)
1370{
Glenn Kasten090f0192012-01-30 13:00:02 -08001371 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001372 if (chain != 0) {
1373 if (type != NULL) {
1374 chain->setEffectSuspended_l(type, suspend);
1375 } else {
1376 chain->setEffectSuspendedAll_l(suspend);
1377 }
1378 }
1379
1380 updateSuspendedSessions_l(type, suspend, sessionId);
1381}
1382
1383void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1384{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001385 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001386 if (index < 0) {
1387 return;
1388 }
1389
1390 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1391 mSuspendedSessions.editValueAt(index);
1392
1393 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001394 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001395 for (int j = 0; j < desc->mRefCount; j++) {
1396 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1397 chain->setEffectSuspendedAll_l(true);
1398 } else {
Steve Block3856b092011-10-20 11:56:00 +01001399 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001400 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001401 chain->setEffectSuspended_l(&desc->mType, true);
1402 }
1403 }
1404 }
1405}
1406
Eric Laurent59255e42011-07-27 19:49:51 -07001407void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1408 bool suspend,
1409 int sessionId)
1410{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001411 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001412
1413 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1414
1415 if (suspend) {
1416 if (index >= 0) {
1417 sessionEffects = mSuspendedSessions.editValueAt(index);
1418 } else {
1419 mSuspendedSessions.add(sessionId, sessionEffects);
1420 }
1421 } else {
1422 if (index < 0) {
1423 return;
1424 }
1425 sessionEffects = mSuspendedSessions.editValueAt(index);
1426 }
1427
1428
1429 int key = EffectChain::kKeyForSuspendAll;
1430 if (type != NULL) {
1431 key = type->timeLow;
1432 }
1433 index = sessionEffects.indexOfKey(key);
1434
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001435 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001436 if (suspend) {
1437 if (index >= 0) {
1438 desc = sessionEffects.valueAt(index);
1439 } else {
1440 desc = new SuspendedSessionDesc();
1441 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001442 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001443 }
1444 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001445 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001446 }
1447 desc->mRefCount++;
1448 } else {
1449 if (index < 0) {
1450 return;
1451 }
1452 desc = sessionEffects.valueAt(index);
1453 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001454 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001455 sessionEffects.removeItemsAt(index);
1456 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001457 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001458 sessionId);
1459 mSuspendedSessions.removeItem(sessionId);
1460 }
1461 }
1462 }
1463 if (!sessionEffects.isEmpty()) {
1464 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1465 }
1466}
1467
1468void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1469 bool enabled,
1470 int sessionId)
1471{
1472 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001473 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1474}
Eric Laurent59255e42011-07-27 19:49:51 -07001475
Eric Laurenta85a74a2011-10-19 11:44:54 -07001476void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1477 bool enabled,
1478 int sessionId)
1479{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001480 if (mType != RECORD) {
1481 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1482 // another session. This gives the priority to well behaved effect control panels
1483 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001484 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1485 // global effects
1486 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001487 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1488 }
1489 }
Eric Laurent59255e42011-07-27 19:49:51 -07001490
1491 sp<EffectChain> chain = getEffectChain_l(sessionId);
1492 if (chain != 0) {
1493 chain->checkSuspendOnEffectEnabled(effect, enabled);
1494 }
1495}
1496
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497// ----------------------------------------------------------------------------
1498
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001499AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1500 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001501 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001502 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001503 type_t type)
1504 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001505 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1506 // Assumes constructor is called by AudioFlinger with it's mLock held,
1507 // but it would be safer to explicitly pass initial masterMute as parameter
1508 mMasterMute(audioFlinger->masterMute_l()),
1509 // mStreamTypes[] initialized in constructor body
1510 mOutput(output),
1511 // Assumes constructor is called by AudioFlinger with it's mLock held,
1512 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001513 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001514 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001515 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001516 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001517 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001518 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001519 // index 0 is reserved for normal mixer's submix
1520 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521{
Glenn Kasten480b4682012-02-28 12:30:08 -08001522 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001523
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524 readOutputParameters();
1525
Glenn Kasten263709e2012-01-06 08:40:01 -08001526 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001527 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1528 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1529 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001530 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1531 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001533 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1534 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535}
1536
1537AudioFlinger::PlaybackThread::~PlaybackThread()
1538{
1539 delete [] mMixBuffer;
1540}
1541
1542status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1543{
1544 dumpInternals(fd, args);
1545 dumpTracks(fd, args);
1546 dumpEffectChains(fd, args);
1547 return NO_ERROR;
1548}
1549
1550status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1551{
1552 const size_t SIZE = 256;
1553 char buffer[SIZE];
1554 String8 result;
1555
Glenn Kasten58912562012-04-03 10:45:00 -07001556 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1557 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1558 const stream_type_t *st = &mStreamTypes[i];
1559 if (i > 0) {
1560 result.appendFormat(", ");
1561 }
1562 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1563 if (st->mute) {
1564 result.append("M");
1565 }
1566 }
1567 result.append("\n");
1568 write(fd, result.string(), result.length());
1569 result.clear();
1570
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1572 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001573 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 for (size_t i = 0; i < mTracks.size(); ++i) {
1575 sp<Track> track = mTracks[i];
1576 if (track != 0) {
1577 track->dump(buffer, SIZE);
1578 result.append(buffer);
1579 }
1580 }
1581
1582 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1583 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001584 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001586 sp<Track> track = mActiveTracks[i].promote();
1587 if (track != 0) {
1588 track->dump(buffer, SIZE);
1589 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 }
1591 }
1592 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001593
1594 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1595 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1596 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1597 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1598
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 return NO_ERROR;
1600}
1601
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1603{
1604 const size_t SIZE = 256;
1605 char buffer[SIZE];
1606 String8 result;
1607
1608 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1609 result.append(buffer);
1610 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1617 result.append(buffer);
1618 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1621 result.append(buffer);
1622 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001623 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624
1625 dumpBase(fd, args);
1626
1627 return NO_ERROR;
1628}
1629
1630// Thread virtuals
1631status_t AudioFlinger::PlaybackThread::readyToRun()
1632{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001633 status_t status = initCheck();
1634 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001635 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001636 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001637 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001639 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001640}
1641
1642void AudioFlinger::PlaybackThread::onFirstRef()
1643{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001644 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645}
1646
1647// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001648sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001650 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001652 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001653 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 int frameCount,
1655 const sp<IMemory>& sharedBuffer,
1656 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001657 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001658 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 status_t *status)
1660{
1661 sp<Track> track;
1662 status_t lStatus;
1663
Glenn Kasten73d22752012-03-19 13:38:30 -07001664 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1665
1666 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001667 if (flags & IAudioFlinger::TRACK_FAST) {
1668 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001669 // not timed
1670 (!isTimed) &&
1671 // either of these use cases:
1672 (
1673 // use case 1: shared buffer with any frame count
1674 (
1675 (sharedBuffer != 0)
1676 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001678 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001679 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001680 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001681 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001682 )
1683 ) &&
1684 // PCM data
1685 audio_is_linear_pcm(format) &&
1686 // mono or stereo
1687 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1688 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001689#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001690 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001691 (sampleRate == mSampleRate) &&
1692#endif
1693 // normal mixer has an associated fast mixer
1694 hasFastMixer() &&
1695 // there are sufficient fast track slots available
1696 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001697 // FIXME test that MixerThread for this fast track has a capable output HAL
1698 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001700 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1701 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001702 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001703 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001704 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001705 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001706 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001707 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001708 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001709 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1710 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1711 audio_is_linear_pcm(format),
1712 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001713 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001714 // For compatibility with AudioTrack calculation, buffer depth is forced
1715 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1716 // This is probably too conservative, but legacy application code may depend on it.
1717 // If you change this calculation, also review the start threshold which is related.
1718 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1719 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1720 if (minBufCount < 2) {
1721 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001722 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001723 int minFrameCount = mNormalFrameCount * minBufCount;
1724 if (frameCount < minFrameCount) {
1725 frameCount = minFrameCount;
1726 }
1727 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001728 }
1729
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001731 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1732 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001733 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001734 "for output %p with format %d",
1735 sampleRate, format, channelMask, mOutput, mFormat);
1736 lStatus = BAD_VALUE;
1737 goto Exit;
1738 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 }
1740 } else {
1741 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1742 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001743 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 lStatus = BAD_VALUE;
1745 goto Exit;
1746 }
1747 }
1748
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001749 lStatus = initCheck();
1750 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001751 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 goto Exit;
1753 }
1754
1755 { // scope for mLock
1756 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001757
1758 // all tracks in same audio session must share the same routing strategy otherwise
1759 // conflicts will happen when tracks are moved from one output to another by audio policy
1760 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001761 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001762 for (size_t i = 0; i < mTracks.size(); ++i) {
1763 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001764 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001765 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001766 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001767 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001768 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001769 lStatus = BAD_VALUE;
1770 goto Exit;
1771 }
1772 }
1773 }
1774
John Grossman4ff14ba2012-02-08 16:37:41 -08001775 if (!isTimed) {
1776 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001777 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001778 } else {
1779 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1780 channelMask, frameCount, sharedBuffer, sessionId);
1781 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001782 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783 lStatus = NO_MEMORY;
1784 goto Exit;
1785 }
1786 mTracks.add(track);
1787
1788 sp<EffectChain> chain = getEffectChain_l(sessionId);
1789 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001790 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001792 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001793 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 }
1795 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001796
Glenn Kasten3acbd052012-02-28 10:39:56 -08001797 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1798 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1799 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1800 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001801 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001802 if (err != 0) {
1803 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001804 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001805 }
1806 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001807
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 lStatus = NO_ERROR;
1809
1810Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001811 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 *status = lStatus;
1813 }
1814 return track;
1815}
1816
Eric Laurente737cda2012-05-22 18:55:44 -07001817uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1818{
1819 if (mFastMixer != NULL) {
1820 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1821 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1822 }
1823 return latency;
1824}
1825
1826uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1827{
1828 return latency;
1829}
1830
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831uint32_t AudioFlinger::PlaybackThread::latency() const
1832{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001833 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001834 return latency_l();
1835}
1836uint32_t AudioFlinger::PlaybackThread::latency_l() const
1837{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001838 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001839 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001840 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 return 0;
1842 }
1843}
1844
Glenn Kasten6637baa2012-01-09 09:40:36 -08001845void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001847 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849}
1850
Glenn Kasten6637baa2012-01-09 09:40:36 -08001851void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001853 Mutex::Autolock _l(mLock);
1854 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855}
1856
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001859 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001865 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Glenn Kastenfff6d712012-01-12 16:38:12 -08001869float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001871 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 return mStreamTypes[stream].volume;
1873}
1874
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875// addTrack_l() must be called with ThreadBase::mLock held
1876status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1877{
1878 status_t status = ALREADY_EXISTS;
1879
1880 // set retry count for buffer fill
1881 track->mRetryCount = kMaxTrackStartupRetries;
1882 if (mActiveTracks.indexOf(track) < 0) {
1883 // the track is newly added, make sure it fills up all its
1884 // buffers before playing. This is to ensure the client will
1885 // effectively get the latency it requested.
1886 track->mFillingUpStatus = Track::FS_FILLING;
1887 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001888 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 mActiveTracks.add(track);
1890 if (track->mainBuffer() != mMixBuffer) {
1891 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1892 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001893 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001894 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 }
1896 }
1897
1898 status = NO_ERROR;
1899 }
1900
Steve Block3856b092011-10-20 11:56:00 +01001901 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 mWaitWorkCV.broadcast();
1903
1904 return status;
1905}
1906
1907// destroyTrack_l() must be called with ThreadBase::mLock held
1908void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1909{
1910 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001911 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001913 removeTrack_l(track);
1914 }
1915}
1916
1917void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1918{
Eric Laurent29864602012-05-08 18:57:51 -07001919 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001920 mTracks.remove(track);
1921 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001922 // redundant as track is about to be destroyed, for dumpsys only
1923 track->mName = -1;
1924 if (track->isFastTrack()) {
1925 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001926 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001927 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1928 mFastTrackAvailMask |= 1 << index;
1929 // redundant as track is about to be destroyed, for dumpsys only
1930 track->mFastIndex = -1;
1931 }
Eric Laurentb469b942011-05-09 12:09:06 -07001932 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1933 if (chain != 0) {
1934 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 }
1936}
1937
1938String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1939{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001940 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001941 char *s;
1942
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001943 Mutex::Autolock _l(mLock);
1944 if (initCheck() != NO_ERROR) {
1945 return out_s8;
1946 }
1947
Dima Zavin799a70e2011-04-18 16:57:27 -07001948 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001949 out_s8 = String8(s);
1950 free(s);
1951 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952}
1953
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1956 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001957 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958
Steve Block3856b092011-10-20 11:56:00 +01001959 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
1961 switch (event) {
1962 case AudioSystem::OUTPUT_OPENED:
1963 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001964 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 desc.samplingRate = mSampleRate;
1966 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001967 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 desc.latency = latency();
1969 param2 = &desc;
1970 break;
1971
1972 case AudioSystem::STREAM_CONFIG_CHANGED:
1973 param2 = &param;
1974 case AudioSystem::OUTPUT_CLOSED:
1975 default:
1976 break;
1977 }
1978 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1979}
1980
1981void AudioFlinger::PlaybackThread::readOutputParameters()
1982{
Dima Zavin799a70e2011-04-18 16:57:27 -07001983 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001984 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1985 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001986 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001987 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001988 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001989 if (mFrameCount & 15) {
1990 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1991 mFrameCount);
1992 }
1993
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001994 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001995 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001996 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001997 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001998 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1999 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2000 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2001 maxNormalFrameCount = maxNormalFrameCount & ~15;
2002 if (maxNormalFrameCount < minNormalFrameCount) {
2003 maxNormalFrameCount = minNormalFrameCount;
2004 }
2005 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2006 if (multiplier <= 1.0) {
2007 multiplier = 1.0;
2008 } else if (multiplier <= 2.0) {
2009 if (2 * mFrameCount <= maxNormalFrameCount) {
2010 multiplier = 2.0;
2011 } else {
2012 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2013 }
2014 } else {
2015 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2016 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2017 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2018 // FIXME this rounding up should not be done if no HAL SRC
2019 uint32_t truncMult = (uint32_t) multiplier;
2020 if ((truncMult & 1)) {
2021 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2022 ++truncMult;
2023 }
2024 }
2025 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002026 }
Glenn Kasten58912562012-04-03 10:45:00 -07002027 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002028 mNormalFrameCount = multiplier * mFrameCount;
2029 // round up to nearest 16 frames to satisfy AudioMixer
2030 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002031 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032
Glenn Kastene9dd0172012-01-27 18:08:45 -08002033 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002034 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2035 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036
Eric Laurentde070132010-07-13 04:45:46 -07002037 // force reconfiguration of effect chains and engines to take new buffer size and audio
2038 // parameters into account
2039 // Note that mLock is not held when readOutputParameters() is called from the constructor
2040 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2041 // matter.
2042 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2043 Vector< sp<EffectChain> > effectChains = mEffectChains;
2044 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002045 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047}
2048
Eric Laurente737cda2012-05-22 18:55:44 -07002049
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2051{
Glenn Kastena0d68332012-01-27 16:47:15 -08002052 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 return BAD_VALUE;
2054 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002055 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002056 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 return INVALID_OPERATION;
2058 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002059 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062}
2063
Eric Laurent39e94f82010-07-28 01:32:47 -07002064uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065{
2066 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002067 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002069 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 }
2071
2072 for (size_t i = 0; i < mTracks.size(); ++i) {
2073 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002074 if (sessionId == track->sessionId() &&
2075 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002076 result |= TRACK_SESSION;
2077 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 }
2079 }
2080
Eric Laurent39e94f82010-07-28 01:32:47 -07002081 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082}
2083
Eric Laurentde070132010-07-13 04:45:46 -07002084uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2085{
Dima Zavinfce7a472011-04-19 22:30:36 -07002086 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002087 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002088 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2089 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002090 }
2091 for (size_t i = 0; i < mTracks.size(); i++) {
2092 sp<Track> track = mTracks[i];
2093 if (sessionId == track->sessionId() &&
2094 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002095 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002096 }
2097 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002098 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002099}
2100
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101
Glenn Kastenaed850d2012-01-26 09:46:34 -08002102AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002103{
2104 Mutex::Autolock _l(mLock);
2105 return mOutput;
2106}
2107
2108AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2109{
2110 Mutex::Autolock _l(mLock);
2111 AudioStreamOut *output = mOutput;
2112 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002113 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2114 // must push a NULL and wait for ack
2115 mOutputSink.clear();
2116 mPipeSink.clear();
2117 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002118 return output;
2119}
2120
2121// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002122audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002123{
2124 if (mOutput == NULL) {
2125 return NULL;
2126 }
2127 return &mOutput->stream->common;
2128}
2129
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002130uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002131{
Eric Laurentab9071b2012-06-04 13:45:29 -07002132 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002133}
2134
Eric Laurenta011e352012-03-29 15:51:43 -07002135status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2136{
2137 if (!isValidSyncEvent(event)) {
2138 return BAD_VALUE;
2139 }
2140
2141 Mutex::Autolock _l(mLock);
2142
2143 for (size_t i = 0; i < mTracks.size(); ++i) {
2144 sp<Track> track = mTracks[i];
2145 if (event->triggerSession() == track->sessionId()) {
2146 track->setSyncEvent(event);
2147 return NO_ERROR;
2148 }
2149 }
2150
2151 return NAME_NOT_FOUND;
2152}
2153
2154bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2155{
2156 switch (event->type()) {
2157 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2158 return true;
2159 default:
2160 break;
2161 }
2162 return false;
2163}
2164
Eric Laurent44a957f2012-05-15 15:26:05 -07002165void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2166{
2167 size_t count = tracksToRemove.size();
2168 if (CC_UNLIKELY(count)) {
2169 for (size_t i = 0 ; i < count ; i++) {
2170 const sp<Track>& track = tracksToRemove.itemAt(i);
2171 if ((track->sharedBuffer() != 0) &&
2172 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2173 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2174 }
2175 }
2176 }
2177
2178}
2179
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180// ----------------------------------------------------------------------------
2181
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002182AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002183 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002184 : PlaybackThread(audioFlinger, output, id, device, type),
2185 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002186 // mFastMixer below
2187 mFastMixerFutex(0)
2188 // mOutputSink below
2189 // mPipeSink below
2190 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002192 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002193 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002194 "mFrameCount=%d, mNormalFrameCount=%d",
2195 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2196 mNormalFrameCount);
2197 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2198
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002200 if (mChannelCount != FCC_2) {
2201 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202 }
Glenn Kasten58912562012-04-03 10:45:00 -07002203
2204 // create an NBAIO sink for the HAL output stream, and negotiate
2205 mOutputSink = new AudioStreamOutSink(output->stream);
2206 size_t numCounterOffers = 0;
2207 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2208 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2209 ALOG_ASSERT(index == 0);
2210
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002211 // initialize fast mixer depending on configuration
2212 bool initFastMixer;
2213 switch (kUseFastMixer) {
2214 case FastMixer_Never:
2215 initFastMixer = false;
2216 break;
2217 case FastMixer_Always:
2218 initFastMixer = true;
2219 break;
2220 case FastMixer_Static:
2221 case FastMixer_Dynamic:
2222 initFastMixer = mFrameCount < mNormalFrameCount;
2223 break;
2224 }
2225 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002226
2227 // create a MonoPipe to connect our submix to FastMixer
2228 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002229 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2230 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2231 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2232 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002233 const NBAIO_Format offers[1] = {format};
2234 size_t numCounterOffers = 0;
2235 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2236 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002237 monoPipe->setAvgFrames((mScreenState & 1) ?
2238 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002239 mPipeSink = monoPipe;
2240
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002241#ifdef TEE_SINK_FRAMES
2242 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2243 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2244 numCounterOffers = 0;
2245 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2246 ALOG_ASSERT(index == 0);
2247 mTeeSink = teeSink;
2248 PipeReader *teeSource = new PipeReader(*teeSink);
2249 numCounterOffers = 0;
2250 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2251 ALOG_ASSERT(index == 0);
2252 mTeeSource = teeSource;
2253#endif
2254
Glenn Kasten58912562012-04-03 10:45:00 -07002255 // create fast mixer and configure it initially with just one fast track for our submix
2256 mFastMixer = new FastMixer();
2257 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002258#ifdef STATE_QUEUE_DUMP
2259 sq->setObserverDump(&mStateQueueObserverDump);
2260 sq->setMutatorDump(&mStateQueueMutatorDump);
2261#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002262 FastMixerState *state = sq->begin();
2263 FastTrack *fastTrack = &state->mFastTracks[0];
2264 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2265 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2266 fastTrack->mVolumeProvider = NULL;
2267 fastTrack->mGeneration++;
2268 state->mFastTracksGen++;
2269 state->mTrackMask = 1;
2270 // fast mixer will use the HAL output sink
2271 state->mOutputSink = mOutputSink.get();
2272 state->mOutputSinkGen++;
2273 state->mFrameCount = mFrameCount;
2274 state->mCommand = FastMixerState::COLD_IDLE;
2275 // already done in constructor initialization list
2276 //mFastMixerFutex = 0;
2277 state->mColdFutexAddr = &mFastMixerFutex;
2278 state->mColdGen++;
2279 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002280 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002281 sq->end();
2282 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2283
2284 // start the fast mixer
2285 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002286 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002287 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002288 if (err != 0) {
2289 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002290 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002291 }
Glenn Kasten58912562012-04-03 10:45:00 -07002292
Glenn Kastenc15d6652012-05-30 14:52:57 -07002293#ifdef AUDIO_WATCHDOG
2294 // create and start the watchdog
2295 mAudioWatchdog = new AudioWatchdog();
2296 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2297 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2298 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002299 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002300 if (err != 0) {
2301 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002302 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002303 }
2304#endif
2305
Glenn Kasten58912562012-04-03 10:45:00 -07002306 } else {
2307 mFastMixer = NULL;
2308 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002309
2310 switch (kUseFastMixer) {
2311 case FastMixer_Never:
2312 case FastMixer_Dynamic:
2313 mNormalSink = mOutputSink;
2314 break;
2315 case FastMixer_Always:
2316 mNormalSink = mPipeSink;
2317 break;
2318 case FastMixer_Static:
2319 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2320 break;
2321 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322}
2323
2324AudioFlinger::MixerThread::~MixerThread()
2325{
Glenn Kasten58912562012-04-03 10:45:00 -07002326 if (mFastMixer != NULL) {
2327 FastMixerStateQueue *sq = mFastMixer->sq();
2328 FastMixerState *state = sq->begin();
2329 if (state->mCommand == FastMixerState::COLD_IDLE) {
2330 int32_t old = android_atomic_inc(&mFastMixerFutex);
2331 if (old == -1) {
2332 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2333 }
2334 }
2335 state->mCommand = FastMixerState::EXIT;
2336 sq->end();
2337 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2338 mFastMixer->join();
2339 // Though the fast mixer thread has exited, it's state queue is still valid.
2340 // We'll use that extract the final state which contains one remaining fast track
2341 // corresponding to our sub-mix.
2342 state = sq->begin();
2343 ALOG_ASSERT(state->mTrackMask == 1);
2344 FastTrack *fastTrack = &state->mFastTracks[0];
2345 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2346 delete fastTrack->mBufferProvider;
2347 sq->end(false /*didModify*/);
2348 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002349 if (mAudioWatchdog != 0) {
2350 mAudioWatchdog->requestExit();
2351 mAudioWatchdog->requestExitAndWait();
2352 mAudioWatchdog.clear();
2353 }
Glenn Kasten58912562012-04-03 10:45:00 -07002354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 delete mAudioMixer;
2356}
2357
Glenn Kasten83efdd02012-02-24 07:21:32 -08002358class CpuStats {
2359public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002360 CpuStats();
2361 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002362#ifdef DEBUG_CPU_USAGE
2363private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002364 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2365 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2366
2367 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2368
2369 int mCpuNum; // thread's current CPU number
2370 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002371#endif
2372};
2373
Glenn Kasten190a46f2012-03-06 11:27:10 -08002374CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002375#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002376 : mCpuNum(-1), mCpukHz(-1)
2377#endif
2378{
2379}
2380
2381void CpuStats::sample(const String8 &title) {
2382#ifdef DEBUG_CPU_USAGE
2383 // get current thread's delta CPU time in wall clock ns
2384 double wcNs;
2385 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2386
2387 // record sample for wall clock statistics
2388 if (valid) {
2389 mWcStats.sample(wcNs);
2390 }
2391
2392 // get the current CPU number
2393 int cpuNum = sched_getcpu();
2394
2395 // get the current CPU frequency in kHz
2396 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2397
2398 // check if either CPU number or frequency changed
2399 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2400 mCpuNum = cpuNum;
2401 mCpukHz = cpukHz;
2402 // ignore sample for purposes of cycles
2403 valid = false;
2404 }
2405
2406 // if no change in CPU number or frequency, then record sample for cycle statistics
2407 if (valid && mCpukHz > 0) {
2408 double cycles = wcNs * cpukHz * 0.000001;
2409 mHzStats.sample(cycles);
2410 }
2411
2412 unsigned n = mWcStats.n();
2413 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002414 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002415 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002416 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2417 double perLoop = elapsed / (double) n;
2418 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002419 double perLoop1k = perLoop * 0.001;
2420 double mean = mWcStats.mean();
2421 double stddev = mWcStats.stddev();
2422 double minimum = mWcStats.minimum();
2423 double maximum = mWcStats.maximum();
2424 double meanCycles = mHzStats.mean();
2425 double stddevCycles = mHzStats.stddev();
2426 double minCycles = mHzStats.minimum();
2427 double maxCycles = mHzStats.maximum();
2428 mCpuUsage.resetElapsed();
2429 mWcStats.reset();
2430 mHzStats.reset();
2431 ALOGD("CPU usage for %s over past %.1f secs\n"
2432 " (%u mixer loops at %.1f mean ms per loop):\n"
2433 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2434 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2435 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2436 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002437 elapsed * .000000001, n, perLoop * .000001,
2438 mean * .001,
2439 stddev * .001,
2440 minimum * .001,
2441 maximum * .001,
2442 mean / perLoop100,
2443 stddev / perLoop100,
2444 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 maximum / perLoop100,
2446 meanCycles / perLoop1k,
2447 stddevCycles / perLoop1k,
2448 minCycles / perLoop1k,
2449 maxCycles / perLoop1k);
2450
Glenn Kasten83efdd02012-02-24 07:21:32 -08002451 }
2452 }
2453#endif
2454};
2455
Glenn Kasten37d825e2012-02-24 07:21:48 -08002456void AudioFlinger::PlaybackThread::checkSilentMode_l()
2457{
2458 if (!mMasterMute) {
2459 char value[PROPERTY_VALUE_MAX];
2460 if (property_get("ro.audio.silent", value, "0") > 0) {
2461 char *endptr;
2462 unsigned long ul = strtoul(value, &endptr, 0);
2463 if (*endptr == '\0' && ul != 0) {
2464 ALOGD("Silence is golden");
2465 // The setprop command will not allow a property to be changed after
2466 // the first time it is set, so we don't have to worry about un-muting.
2467 setMasterMute_l(true);
2468 }
2469 }
2470 }
2471}
2472
Glenn Kasten000f0e32012-03-01 17:10:56 -08002473bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474{
2475 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002476
Glenn Kasten000f0e32012-03-01 17:10:56 -08002477 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002478
2479 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002481
Glenn Kasten000f0e32012-03-01 17:10:56 -08002482 // DUPLICATING
2483 // FIXME could this be made local to while loop?
2484 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002485
Glenn Kasten66fcab92012-02-24 14:59:21 -08002486 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002487 sleepTime = idleSleepTime;
2488
Glenn Kasten9f34a362012-03-20 16:46:41 -07002489 if (mType == MIXER) {
2490 sleepTimeShift = 0;
2491 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002492
Glenn Kasten83efdd02012-02-24 07:21:32 -08002493 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002494 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495
Eric Laurentfeb0db62011-07-22 09:04:31 -07002496 acquireWakeLock();
2497
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 while (!exitPending())
2499 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002500 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002501
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002502 Vector< sp<EffectChain> > effectChains;
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 processConfigEvents();
2505
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 { // scope for mLock
2507
2508 Mutex::Autolock _l(mLock);
2509
2510 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002511 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 }
2513
Glenn Kastenfa26a852012-03-06 11:28:04 -08002514 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002515
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002517 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002518 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520
2521 threadLoop_standby();
2522
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 mStandby = true;
2524 mBytesWritten = 0;
2525 }
2526
Glenn Kasten3e074702012-02-28 18:40:35 -08002527 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 // we're about to wait, flush the binder command buffer
2529 IPCThreadState::self()->flushCommands();
2530
Glenn Kastenfa26a852012-03-06 11:28:04 -08002531 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002532
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 if (exitPending()) break;
2534
Eric Laurentfeb0db62011-07-22 09:04:31 -07002535 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002537 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002539 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002540 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541
Eric Laurentda747442012-04-25 18:53:13 -07002542 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002543 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002544
Glenn Kasten37d825e2012-02-24 07:21:48 -08002545 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546
Glenn Kasten000f0e32012-03-01 17:10:56 -08002547 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002549 if (mType == MIXER) {
2550 sleepTimeShift = 0;
2551 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002552
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 continue;
2554 }
2555 }
2556
Glenn Kasten81028042012-04-30 18:15:12 -07002557 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002558 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559
2560 // prevent any changes in effect chain list and in each effect chain
2561 // during mixing and effect process as the audio buffers could be deleted
2562 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002563 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565
Glenn Kastenfec279f2012-03-08 07:47:15 -08002566 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002567 threadLoop_mix();
2568 } else {
2569 threadLoop_sleepTime();
2570 }
2571
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002572 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002573 sleepTime = suspendSleepTimeUs();
2574 }
2575
2576 // only process effects if we're going to write
2577 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002578 for (size_t i = 0; i < effectChains.size(); i ++) {
2579 effectChains[i]->process_l();
2580 }
2581 }
2582
2583 // enable changes in effect chain
2584 unlockEffectChains(effectChains);
2585
2586 // sleepTime == 0 means we must write to audio hardware
2587 if (sleepTime == 0) {
2588
2589 threadLoop_write();
2590
2591if (mType == MIXER) {
2592 // write blocked detection
2593 nsecs_t now = systemTime();
2594 nsecs_t delta = now - mLastWriteTime;
2595 if (!mStandby && delta > maxPeriod) {
2596 mNumDelayedWrites++;
2597 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002598#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002599 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002600#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002601 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2602 ns2ms(delta), mNumDelayedWrites, this);
2603 lastWarning = now;
2604 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002605 }
2606}
2607
2608 mStandby = false;
2609 } else {
2610 usleep(sleepTime);
2611 }
2612
Glenn Kasten58912562012-04-03 10:45:00 -07002613 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002614 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002615 // same lock. This will also mutate and push a new fast mixer state.
2616 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002617 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002618
Glenn Kastenfa26a852012-03-06 11:28:04 -08002619 // FIXME I don't understand the need for this here;
2620 // it was in the original code but maybe the
2621 // assignment in saveOutputTracks() makes this unnecessary?
2622 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002623
2624 // Effect chains will be actually deleted here if they were removed from
2625 // mEffectChains list during mixing or effects processing
2626 effectChains.clear();
2627
2628 // FIXME Note that the above .clear() is no longer necessary since effectChains
2629 // is now local to this block, but will keep it for now (at least until merge done).
2630 }
2631
Glenn Kasten9f34a362012-03-20 16:46:41 -07002632 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2633 if (mType == MIXER || mType == DIRECT) {
2634 // put output stream into standby mode
2635 if (!mStandby) {
2636 mOutput->stream->common.standby(&mOutput->stream->common);
2637 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002639
2640 releaseWakeLock();
2641
2642 ALOGV("Thread %p type %d exiting", this, mType);
2643 return false;
2644}
2645
Glenn Kasten58912562012-04-03 10:45:00 -07002646void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2647{
Glenn Kasten58912562012-04-03 10:45:00 -07002648 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2649}
2650
2651void AudioFlinger::MixerThread::threadLoop_write()
2652{
2653 // FIXME we should only do one push per cycle; confirm this is true
2654 // Start the fast mixer if it's not already running
2655 if (mFastMixer != NULL) {
2656 FastMixerStateQueue *sq = mFastMixer->sq();
2657 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002658 if (state->mCommand != FastMixerState::MIX_WRITE &&
2659 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002660 if (state->mCommand == FastMixerState::COLD_IDLE) {
2661 int32_t old = android_atomic_inc(&mFastMixerFutex);
2662 if (old == -1) {
2663 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2664 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002665 if (mAudioWatchdog != 0) {
2666 mAudioWatchdog->resume();
2667 }
Glenn Kasten58912562012-04-03 10:45:00 -07002668 }
2669 state->mCommand = FastMixerState::MIX_WRITE;
2670 sq->end();
2671 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002672 if (kUseFastMixer == FastMixer_Dynamic) {
2673 mNormalSink = mPipeSink;
2674 }
Glenn Kasten58912562012-04-03 10:45:00 -07002675 } else {
2676 sq->end(false /*didModify*/);
2677 }
2678 }
2679 PlaybackThread::threadLoop_write();
2680}
2681
Glenn Kasten000f0e32012-03-01 17:10:56 -08002682// shared by MIXER and DIRECT, overridden by DUPLICATING
2683void AudioFlinger::PlaybackThread::threadLoop_write()
2684{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002685 // FIXME rewrite to reduce number of system calls
2686 mLastWriteTime = systemTime();
2687 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002688 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002689
Eric Laurent67c0a582012-05-01 19:31:12 -07002690 // If an NBAIO sink is present, use it to write the normal mixer's submix
2691 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002692#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002693 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002694#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002695 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002696#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002697 // update the setpoint when gScreenState changes
2698 uint32_t screenState = gScreenState;
2699 if (screenState != mScreenState) {
2700 mScreenState = screenState;
2701 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2702 if (pipe != NULL) {
2703 pipe->setAvgFrames((mScreenState & 1) ?
2704 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2705 }
2706 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002707 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002708#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002709 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002710#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002711 if (framesWritten > 0) {
2712 bytesWritten = framesWritten << mBitShift;
2713 } else {
2714 bytesWritten = framesWritten;
2715 }
2716 // otherwise use the HAL / AudioStreamOut directly
2717 } else {
2718 // Direct output thread.
2719 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002720 }
2721
Eric Laurent67c0a582012-05-01 19:31:12 -07002722 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002723 mNumWrites++;
2724 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002725}
2726
Glenn Kasten58912562012-04-03 10:45:00 -07002727void AudioFlinger::MixerThread::threadLoop_standby()
2728{
2729 // Idle the fast mixer if it's currently running
2730 if (mFastMixer != NULL) {
2731 FastMixerStateQueue *sq = mFastMixer->sq();
2732 FastMixerState *state = sq->begin();
2733 if (!(state->mCommand & FastMixerState::IDLE)) {
2734 state->mCommand = FastMixerState::COLD_IDLE;
2735 state->mColdFutexAddr = &mFastMixerFutex;
2736 state->mColdGen++;
2737 mFastMixerFutex = 0;
2738 sq->end();
2739 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2740 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002741 if (kUseFastMixer == FastMixer_Dynamic) {
2742 mNormalSink = mOutputSink;
2743 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002744 if (mAudioWatchdog != 0) {
2745 mAudioWatchdog->pause();
2746 }
Glenn Kasten58912562012-04-03 10:45:00 -07002747 } else {
2748 sq->end(false /*didModify*/);
2749 }
2750 }
2751 PlaybackThread::threadLoop_standby();
2752}
2753
Glenn Kasten000f0e32012-03-01 17:10:56 -08002754// shared by MIXER and DIRECT, overridden by DUPLICATING
2755void AudioFlinger::PlaybackThread::threadLoop_standby()
2756{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002757 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002758 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002759}
2760
2761void AudioFlinger::MixerThread::threadLoop_mix()
2762{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002763 // obtain the presentation timestamp of the next output buffer
2764 int64_t pts;
2765 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002766
Glenn Kasten952eeb22012-03-06 11:30:57 -08002767 if (NULL != mOutput->stream->get_next_write_timestamp) {
2768 status = mOutput->stream->get_next_write_timestamp(
2769 mOutput->stream, &pts);
2770 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002771
Glenn Kasten952eeb22012-03-06 11:30:57 -08002772 if (status != NO_ERROR) {
2773 pts = AudioBufferProvider::kInvalidPTS;
2774 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002775
Glenn Kasten952eeb22012-03-06 11:30:57 -08002776 // mix buffers...
2777 mAudioMixer->process(pts);
2778 // increase sleep time progressively when application underrun condition clears.
2779 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2780 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2781 // such that we would underrun the audio HAL.
2782 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2783 sleepTimeShift--;
2784 }
2785 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002786 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002787 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002788}
2789
2790void AudioFlinger::MixerThread::threadLoop_sleepTime()
2791{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002792 // If no tracks are ready, sleep once for the duration of an output
2793 // buffer size, then write 0s to the output
2794 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002795 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002796 sleepTime = activeSleepTime >> sleepTimeShift;
2797 if (sleepTime < kMinThreadSleepTimeUs) {
2798 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002800 // reduce sleep time in case of consecutive application underruns to avoid
2801 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2802 // duration we would end up writing less data than needed by the audio HAL if
2803 // the condition persists.
2804 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2805 sleepTimeShift++;
2806 }
2807 } else {
2808 sleepTime = idleSleepTime;
2809 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002810 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002811 memset (mMixBuffer, 0, mixBufferSize);
2812 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002813 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002814 }
2815 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816}
2817
2818// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002819AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002820 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821{
2822
Glenn Kasten29c23c32012-01-26 13:37:52 -08002823 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002825 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 size_t mixedTracks = 0;
2827 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002828 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002829 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002830 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831
2832 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002833 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834
Eric Laurent571d49c2010-08-11 05:20:11 -07002835 if (masterMute) {
2836 masterVolume = 0;
2837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002839 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002841 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002842 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843 masterVolume = (float)((v + (1 << 23)) >> 24);
2844 chain.clear();
2845 }
2846
Glenn Kasten288ed212012-04-25 17:52:27 -07002847 // prepare a new state to push
2848 FastMixerStateQueue *sq = NULL;
2849 FastMixerState *state = NULL;
2850 bool didModify = false;
2851 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2852 if (mFastMixer != NULL) {
2853 sq = mFastMixer->sq();
2854 state = sq->begin();
2855 }
2856
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002858 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 if (t == 0) continue;
2860
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002861 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002863
Glenn Kasten288ed212012-04-25 17:52:27 -07002864 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002865 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002866
2867 // It's theoretically possible (though unlikely) for a fast track to be created
2868 // and then removed within the same normal mix cycle. This is not a problem, as
2869 // the track never becomes active so it's fast mixer slot is never touched.
2870 // The converse, of removing an (active) track and then creating a new track
2871 // at the identical fast mixer slot within the same normal mix cycle,
2872 // is impossible because the slot isn't marked available until the end of each cycle.
2873 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002874 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2875 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002876 FastTrack *fastTrack = &state->mFastTracks[j];
2877
2878 // Determine whether the track is currently in underrun condition,
2879 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002880 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2881 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002882 uint32_t recentFull = (underruns.mBitFields.mFull -
2883 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2884 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2885 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2886 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2887 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2888 uint32_t recentUnderruns = recentPartial + recentEmpty;
2889 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002890 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002891 // or stopped which can occur when flush() is called while active
2892 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002893 track->mUnderrunCount += recentUnderruns;
2894 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002895
Glenn Kastend08f48c2012-05-01 18:14:02 -07002896 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002897 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002898 bool isActive = true;
2899 switch (track->mState) {
2900 case TrackBase::STOPPING_1:
2901 // track stays active in STOPPING_1 state until first underrun
2902 if (recentUnderruns > 0) {
2903 track->mState = TrackBase::STOPPING_2;
2904 }
2905 break;
2906 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002907 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002908 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002909 break;
2910 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002911 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002912 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002913 break;
2914 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002915 if (recentFull > 0 || recentPartial > 0) {
2916 // track has provided at least some frames recently: reset retry count
2917 track->mRetryCount = kMaxTrackRetries;
2918 }
2919 if (recentUnderruns == 0) {
2920 // no recent underruns: stay active
2921 break;
2922 }
2923 // there has recently been an underrun of some kind
2924 if (track->sharedBuffer() == 0) {
2925 // were any of the recent underruns "empty" (no frames available)?
2926 if (recentEmpty == 0) {
2927 // no, then ignore the partial underruns as they are allowed indefinitely
2928 break;
2929 }
2930 // there has recently been an "empty" underrun: decrement the retry counter
2931 if (--(track->mRetryCount) > 0) {
2932 break;
2933 }
2934 // indicate to client process that the track was disabled because of underrun;
2935 // it will then automatically call start() when data is available
2936 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2937 // remove from active list, but state remains ACTIVE [confusing but true]
2938 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002939 break;
2940 }
2941 // fall through
2942 case TrackBase::STOPPING_2:
2943 case TrackBase::PAUSED:
2944 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002945 case TrackBase::STOPPED:
2946 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002947 // Check for presentation complete if track is inactive
2948 // We have consumed all the buffers of this track.
2949 // This would be incomplete if we auto-paused on underrun
2950 {
2951 size_t audioHALFrames =
2952 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2953 size_t framesWritten =
2954 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2955 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2956 // track stays in active list until presentation is complete
2957 break;
2958 }
2959 }
2960 if (track->isStopping_2()) {
2961 track->mState = TrackBase::STOPPED;
2962 }
2963 if (track->isStopped()) {
2964 // Can't reset directly, as fast mixer is still polling this track
2965 // track->reset();
2966 // So instead mark this track as needing to be reset after push with ack
2967 resetMask |= 1 << i;
2968 }
2969 isActive = false;
2970 break;
2971 case TrackBase::IDLE:
2972 default:
2973 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002974 }
2975
2976 if (isActive) {
2977 // was it previously inactive?
2978 if (!(state->mTrackMask & (1 << j))) {
2979 ExtendedAudioBufferProvider *eabp = track;
2980 VolumeProvider *vp = track;
2981 fastTrack->mBufferProvider = eabp;
2982 fastTrack->mVolumeProvider = vp;
2983 fastTrack->mSampleRate = track->mSampleRate;
2984 fastTrack->mChannelMask = track->mChannelMask;
2985 fastTrack->mGeneration++;
2986 state->mTrackMask |= 1 << j;
2987 didModify = true;
2988 // no acknowledgement required for newly active tracks
2989 }
2990 // cache the combined master volume and stream type volume for fast mixer; this
2991 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2992 track->mCachedVolume = track->isMuted() ?
2993 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2994 ++fastTracks;
2995 } else {
2996 // was it previously active?
2997 if (state->mTrackMask & (1 << j)) {
2998 fastTrack->mBufferProvider = NULL;
2999 fastTrack->mGeneration++;
3000 state->mTrackMask &= ~(1 << j);
3001 didModify = true;
3002 // If any fast tracks were removed, we must wait for acknowledgement
3003 // because we're about to decrement the last sp<> on those tracks.
3004 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003005 } else {
3006 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003007 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003008 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003009 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003010 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003011 }
3012 continue;
3013 }
3014
3015 { // local variable scope to avoid goto warning
3016
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 audio_track_cblk_t* cblk = track->cblk();
3018
3019 // The first time a track is added we wait
3020 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003021 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003022 // make sure that we have enough frames to mix one full buffer.
3023 // enforce this condition only once to enable draining the buffer in case the client
3024 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003025 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003026 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003027 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003028 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003029 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003030 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003031 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003032 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003033 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003034 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003035 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003036 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003037 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3038 // the minimum track buffer size is normally twice the number of frames necessary
3039 // to fill one buffer and the resampler should not leave more than one buffer worth
3040 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003041 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003042 }
3043 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003044 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 !track->isPaused() && !track->isTerminated())
3046 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003047 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048
3049 mixedTracks++;
3050
3051 // track->mainBuffer() != mMixBuffer means there is an effect chain
3052 // connected to the track
3053 chain.clear();
3054 if (track->mainBuffer() != mMixBuffer) {
3055 chain = getEffectChain_l(track->sessionId());
3056 // Delegate volume control to effect in track effect chain if needed
3057 if (chain != 0) {
3058 tracksWithEffect++;
3059 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003060 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003061 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 }
3063 }
3064
3065
3066 int param = AudioMixer::VOLUME;
3067 if (track->mFillingUpStatus == Track::FS_FILLED) {
3068 // no ramp for the first volume setting
3069 track->mFillingUpStatus = Track::FS_ACTIVE;
3070 if (track->mState == TrackBase::RESUMING) {
3071 track->mState = TrackBase::ACTIVE;
3072 param = AudioMixer::RAMP_VOLUME;
3073 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003074 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075 } else if (cblk->server != 0) {
3076 // If the track is stopped before the first frame was mixed,
3077 // do not apply ramp
3078 param = AudioMixer::RAMP_VOLUME;
3079 }
3080
3081 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003082 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003083 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003084 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003085 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 if (track->isPausing()) {
3087 track->setPaused();
3088 }
3089 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003090
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003092 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003094 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003095 vl = vlr & 0xFFFF;
3096 vr = vlr >> 16;
3097 // track volumes come from shared memory, so can't be trusted and must be clamped
3098 if (vl > MAX_GAIN_INT) {
3099 ALOGV("Track left volume out of range: %04X", vl);
3100 vl = MAX_GAIN_INT;
3101 }
3102 if (vr > MAX_GAIN_INT) {
3103 ALOGV("Track right volume out of range: %04X", vr);
3104 vr = MAX_GAIN_INT;
3105 }
3106 // now apply the master volume and stream type volume
3107 vl = (uint32_t)(v * vl) << 12;
3108 vr = (uint32_t)(v * vr) << 12;
3109 // assuming master volume and stream type volume each go up to 1.0,
3110 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111
Glenn Kasten05632a52012-01-03 14:22:33 -08003112 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3113 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003114 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003115 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003116 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003117 }
3118 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003120 // Delegate volume control to effect in track effect chain if needed
3121 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3122 // Do not ramp volume if volume is controlled by effect
3123 param = AudioMixer::VOLUME;
3124 track->mHasVolumeController = true;
3125 } else {
3126 // force no volume ramp when volume controller was just disabled or removed
3127 // from effect chain to avoid volume spike
3128 if (track->mHasVolumeController) {
3129 param = AudioMixer::VOLUME;
3130 }
3131 track->mHasVolumeController = false;
3132 }
3133
3134 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003135 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003136 vl = (vl + (1 << 11)) >> 12;
3137 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3138 vr = (vr + (1 << 11)) >> 12;
3139 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003140
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003141 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 -07003142
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003144 mAudioMixer->setBufferProvider(name, track);
3145 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003147 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3148 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3149 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003151 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 AudioMixer::TRACK,
3153 AudioMixer::FORMAT, (void *)track->format());
3154 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003155 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003157 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003159 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 AudioMixer::RESAMPLE,
3161 AudioMixer::SAMPLE_RATE,
3162 (void *)(cblk->sampleRate));
3163 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003164 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 AudioMixer::TRACK,
3166 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3167 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003168 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 AudioMixer::TRACK,
3170 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3171
3172 // reset retry count
3173 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003174
Eric Laurent27741442012-01-17 19:20:12 -08003175 // If one track is ready, set the mixer ready if:
3176 // - the mixer was not ready during previous round OR
3177 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003178 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003179 mixerStatus != MIXER_TRACKS_ENABLED) {
3180 mixerStatus = MIXER_TRACKS_READY;
3181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003183 // clear effect chain input buffer if an active track underruns to avoid sending
3184 // previous audio buffer again to effects
3185 chain = getEffectChain_l(track->sessionId());
3186 if (chain != 0) {
3187 chain->clearInputBuffer();
3188 }
3189
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003190 //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 -07003191 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3192 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 // We have consumed all the buffers of this track.
3194 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003195 // TODO: use actual buffer filling status instead of latency when available from
3196 // audio HAL
3197 size_t audioHALFrames =
3198 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3199 size_t framesWritten =
3200 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3201 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003202 if (track->isStopped()) {
3203 track->reset();
3204 }
Eric Laurenta011e352012-03-29 15:51:43 -07003205 tracksToRemove->add(track);
3206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003208 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 // No buffers for this track. Give it a few chances to
3210 // fill a buffer, then remove it from active list.
3211 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003212 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003214 // indicate to client process that the track was disabled because of underrun;
3215 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003216 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003217 // If one track is not ready, mark the mixer also not ready if:
3218 // - the mixer was ready during previous round OR
3219 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003220 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003221 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 mixerStatus = MIXER_TRACKS_ENABLED;
3223 }
3224 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003225 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 }
Glenn Kasten58912562012-04-03 10:45:00 -07003227
3228 } // local variable scope to avoid goto warning
3229track_is_ready: ;
3230
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 }
3232
Glenn Kasten288ed212012-04-25 17:52:27 -07003233 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003234 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003235 if (didModify) {
3236 state->mFastTracksGen++;
3237 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3238 if (kUseFastMixer == FastMixer_Dynamic &&
3239 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3240 state->mCommand = FastMixerState::COLD_IDLE;
3241 state->mColdFutexAddr = &mFastMixerFutex;
3242 state->mColdGen++;
3243 mFastMixerFutex = 0;
3244 if (kUseFastMixer == FastMixer_Dynamic) {
3245 mNormalSink = mOutputSink;
3246 }
3247 // If we go into cold idle, need to wait for acknowledgement
3248 // so that fast mixer stops doing I/O.
3249 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003250 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003251 }
3252 sq->end();
3253 }
3254 if (sq != NULL) {
3255 sq->end(didModify);
3256 sq->push(block);
3257 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003258 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3259 mAudioWatchdog->pause();
3260 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003261
3262 // Now perform the deferred reset on fast tracks that have stopped
3263 while (resetMask != 0) {
3264 size_t i = __builtin_ctz(resetMask);
3265 ALOG_ASSERT(i < count);
3266 resetMask &= ~(1 << i);
3267 sp<Track> t = mActiveTracks[i].promote();
3268 if (t == 0) continue;
3269 Track* track = t.get();
3270 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3271 track->reset();
3272 }
Glenn Kasten58912562012-04-03 10:45:00 -07003273
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 // remove all the tracks that need to be...
3275 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003276 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 for (size_t i=0 ; i<count ; i++) {
3278 const sp<Track>& track = tracksToRemove->itemAt(i);
3279 mActiveTracks.remove(track);
3280 if (track->mainBuffer() != mMixBuffer) {
3281 chain = getEffectChain_l(track->sessionId());
3282 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003283 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003284 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 }
3286 }
3287 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003288 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 }
3290 }
3291 }
3292
3293 // mix buffer must be cleared if all tracks are connected to an
3294 // effect chain as in this case the mixer will not write to
3295 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003296 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3297 // FIXME as a performance optimization, should remember previous zero status
3298 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 }
3300
Glenn Kasten58912562012-04-03 10:45:00 -07003301 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003302 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003303 if (fastTracks > 0) {
3304 mixerStatus = MIXER_TRACKS_READY;
3305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 return mixerStatus;
3307}
3308
Glenn Kasten66fcab92012-02-24 14:59:21 -08003309/*
3310The derived values that are cached:
3311 - mixBufferSize from frame count * frame size
3312 - activeSleepTime from activeSleepTimeUs()
3313 - idleSleepTime from idleSleepTimeUs()
3314 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3315 - maxPeriod from frame count and sample rate (MIXER only)
3316
3317The parameters that affect these derived values are:
3318 - frame count
3319 - frame size
3320 - sample rate
3321 - device type: A2DP or not
3322 - device latency
3323 - format: PCM or not
3324 - active sleep time
3325 - idle sleep time
3326*/
3327
3328void AudioFlinger::PlaybackThread::cacheParameters_l()
3329{
Glenn Kasten58912562012-04-03 10:45:00 -07003330 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003331 activeSleepTime = activeSleepTimeUs();
3332 idleSleepTime = idleSleepTimeUs();
3333}
3334
Eric Laurent22167852012-06-20 12:26:32 -07003335void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336{
Steve Block3856b092011-10-20 11:56:00 +01003337 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003338 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003340
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 size_t size = mTracks.size();
3342 for (size_t i = 0; i < size; i++) {
3343 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003344 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003345 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 }
3348 }
3349}
3350
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003352int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003354 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355}
3356
3357// deleteTrackName_l() must be called with ThreadBase::mLock held
3358void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3359{
Steve Block3856b092011-10-20 11:56:00 +01003360 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 mAudioMixer->deleteTrackName(name);
3362}
3363
3364// checkForNewParameters_l() must be called with ThreadBase::mLock held
3365bool AudioFlinger::MixerThread::checkForNewParameters_l()
3366{
Glenn Kasten58912562012-04-03 10:45:00 -07003367 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3368 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 bool reconfig = false;
3370
3371 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003372
3373 if (mFastMixer != NULL) {
3374 FastMixerStateQueue *sq = mFastMixer->sq();
3375 FastMixerState *state = sq->begin();
3376 if (!(state->mCommand & FastMixerState::IDLE)) {
3377 previousCommand = state->mCommand;
3378 state->mCommand = FastMixerState::HOT_IDLE;
3379 sq->end();
3380 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3381 } else {
3382 sq->end(false /*didModify*/);
3383 }
3384 }
3385
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 status_t status = NO_ERROR;
3387 String8 keyValuePair = mNewParameters[0];
3388 AudioParameter param = AudioParameter(keyValuePair);
3389 int value;
3390
3391 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3392 reconfig = true;
3393 }
3394 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003395 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 status = BAD_VALUE;
3397 } else {
3398 reconfig = true;
3399 }
3400 }
3401 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003402 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 status = BAD_VALUE;
3404 } else {
3405 reconfig = true;
3406 }
3407 }
3408 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3409 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003410 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 // if frame count is changed after track creation
3412 if (!mTracks.isEmpty()) {
3413 status = INVALID_OPERATION;
3414 } else {
3415 reconfig = true;
3416 }
3417 }
3418 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003419#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003420 // when changing the audio output device, call addBatteryData to notify
3421 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003422 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003423 uint32_t params = 0;
3424 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003425 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003426 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3427 }
3428
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003429 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003430 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003431 // check if any other device (except speaker) is on
3432 if (value & deviceWithoutSpeaker ) {
3433 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3434 }
3435
3436 if (params != 0) {
3437 addBatteryData(params);
3438 }
3439 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003440#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003441
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 // forward device change to effects that have requested to be
3443 // aware of attached audio device.
Glenn Kasten94479fd2012-07-09 15:39:54 -07003444 mDevice = (audio_devices_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003446 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 }
3448 }
3449
3450 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003451 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003452 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003454 mOutput->stream->common.standby(&mOutput->stream->common);
3455 mStandby = true;
3456 mBytesWritten = 0;
3457 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003458 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003459 }
3460 if (status == NO_ERROR && reconfig) {
3461 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003462 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3463 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003465 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003467 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 if (name < 0) break;
3469 mTracks[i]->mName = name;
3470 // limit track sample rate to 2 x new output sample rate
3471 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3472 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3473 }
3474 }
3475 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3476 }
3477 }
3478
3479 mNewParameters.removeAt(0);
3480
3481 mParamStatus = status;
3482 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003483 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3484 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003485 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
Glenn Kasten58912562012-04-03 10:45:00 -07003487
3488 if (!(previousCommand & FastMixerState::IDLE)) {
3489 ALOG_ASSERT(mFastMixer != NULL);
3490 FastMixerStateQueue *sq = mFastMixer->sq();
3491 FastMixerState *state = sq->begin();
3492 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3493 state->mCommand = previousCommand;
3494 sq->end();
3495 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3496 }
3497
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 return reconfig;
3499}
3500
3501status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3502{
3503 const size_t SIZE = 256;
3504 char buffer[SIZE];
3505 String8 result;
3506
3507 PlaybackThread::dumpInternals(fd, args);
3508
3509 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3510 result.append(buffer);
3511 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003512
3513 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3514 FastMixerDumpState copy = mFastMixerDumpState;
3515 copy.dump(fd);
3516
Glenn Kasten39993082012-05-31 13:40:27 -07003517#ifdef STATE_QUEUE_DUMP
3518 // Similar for state queue
3519 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3520 observerCopy.dump(fd);
3521 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3522 mutatorCopy.dump(fd);
3523#endif
3524
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003525 // Write the tee output to a .wav file
3526 NBAIO_Source *teeSource = mTeeSource.get();
3527 if (teeSource != NULL) {
3528 char teePath[64];
3529 struct timeval tv;
3530 gettimeofday(&tv, NULL);
3531 struct tm tm;
3532 localtime_r(&tv.tv_sec, &tm);
3533 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3534 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3535 if (teeFd >= 0) {
3536 char wavHeader[44];
3537 memcpy(wavHeader,
3538 "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",
3539 sizeof(wavHeader));
3540 NBAIO_Format format = teeSource->format();
3541 unsigned channelCount = Format_channelCount(format);
3542 ALOG_ASSERT(channelCount <= FCC_2);
3543 unsigned sampleRate = Format_sampleRate(format);
3544 wavHeader[22] = channelCount; // number of channels
3545 wavHeader[24] = sampleRate; // sample rate
3546 wavHeader[25] = sampleRate >> 8;
3547 wavHeader[32] = channelCount * 2; // block alignment
3548 write(teeFd, wavHeader, sizeof(wavHeader));
3549 size_t total = 0;
3550 bool firstRead = true;
3551 for (;;) {
3552#define TEE_SINK_READ 1024
3553 short buffer[TEE_SINK_READ * FCC_2];
3554 size_t count = TEE_SINK_READ;
3555 ssize_t actual = teeSource->read(buffer, count);
3556 bool wasFirstRead = firstRead;
3557 firstRead = false;
3558 if (actual <= 0) {
3559 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3560 continue;
3561 }
3562 break;
3563 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003564 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003565 write(teeFd, buffer, actual * channelCount * sizeof(short));
3566 total += actual;
3567 }
3568 lseek(teeFd, (off_t) 4, SEEK_SET);
3569 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3570 write(teeFd, &temp, sizeof(temp));
3571 lseek(teeFd, (off_t) 40, SEEK_SET);
3572 temp = total * channelCount * sizeof(short);
3573 write(teeFd, &temp, sizeof(temp));
3574 close(teeFd);
3575 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3576 } else {
3577 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3578 }
3579 }
3580
Glenn Kastenc15d6652012-05-30 14:52:57 -07003581 if (mAudioWatchdog != 0) {
3582 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3583 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3584 wdCopy.dump(fd);
3585 }
3586
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 return NO_ERROR;
3588}
3589
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003590uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591{
Glenn Kasten58912562012-04-03 10:45:00 -07003592 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593}
3594
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003595uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003596{
Glenn Kasten58912562012-04-03 10:45:00 -07003597 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003598}
3599
Glenn Kasten66fcab92012-02-24 14:59:21 -08003600void AudioFlinger::MixerThread::cacheParameters_l()
3601{
3602 PlaybackThread::cacheParameters_l();
3603
3604 // FIXME: Relaxed timing because of a certain device that can't meet latency
3605 // Should be reduced to 2x after the vendor fixes the driver issue
3606 // increase threshold again due to low power audio mode. The way this warning
3607 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003608 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003609}
3610
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003612AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003613 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003614 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003615 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617}
3618
3619AudioFlinger::DirectOutputThread::~DirectOutputThread()
3620{
3621}
3622
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003623AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3624 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003625)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003627 sp<Track> trackToRemove;
3628
Glenn Kastenfec279f2012-03-08 07:47:15 -08003629 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630
Glenn Kasten952eeb22012-03-06 11:30:57 -08003631 // find out which tracks need to be processed
3632 if (mActiveTracks.size() != 0) {
3633 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003634 // The track died recently
3635 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636
Glenn Kasten952eeb22012-03-06 11:30:57 -08003637 Track* const track = t.get();
3638 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639
Glenn Kasten952eeb22012-03-06 11:30:57 -08003640 // The first time a track is added we wait
3641 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003642 uint32_t minFrames;
3643 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3644 minFrames = mNormalFrameCount;
3645 } else {
3646 minFrames = 1;
3647 }
3648 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003649 !track->isPaused() && !track->isTerminated())
3650 {
3651 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652
Glenn Kasten952eeb22012-03-06 11:30:57 -08003653 if (track->mFillingUpStatus == Track::FS_FILLED) {
3654 track->mFillingUpStatus = Track::FS_ACTIVE;
3655 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 if (track->mState == TrackBase::RESUMING) {
3657 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003658 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003660
Glenn Kasten952eeb22012-03-06 11:30:57 -08003661 // compute volume for this track
3662 float left, right;
3663 if (track->isMuted() || mMasterMute || track->isPausing() ||
3664 mStreamTypes[track->streamType()].mute) {
3665 left = right = 0;
3666 if (track->isPausing()) {
3667 track->setPaused();
3668 }
3669 } else {
3670 float typeVolume = mStreamTypes[track->streamType()].volume;
3671 float v = mMasterVolume * typeVolume;
3672 uint32_t vlr = cblk->getVolumeLR();
3673 float v_clamped = v * (vlr & 0xFFFF);
3674 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3675 left = v_clamped/MAX_GAIN;
3676 v_clamped = v * (vlr >> 16);
3677 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3678 right = v_clamped/MAX_GAIN;
3679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 if (left != mLeftVolFloat || right != mRightVolFloat) {
3682 mLeftVolFloat = left;
3683 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684
Glenn Kasten952eeb22012-03-06 11:30:57 -08003685 // Convert volumes from float to 8.24
3686 uint32_t vl = (uint32_t)(left * (1 << 24));
3687 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 // Delegate volume control to effect in track effect chain if needed
3690 // only one effect chain can be present on DirectOutputThread, so if
3691 // there is one, the track is connected to it
3692 if (!mEffectChains.isEmpty()) {
3693 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003694 mEffectChains[0]->setVolume_l(&vl, &vr);
3695 left = (float)vl / (1 << 24);
3696 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003697 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003698 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 }
3700
3701 // reset retry count
3702 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003703 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003704 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003705 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003706 // clear effect chain input buffer if an active track underruns to avoid sending
3707 // previous audio buffer again to effects
3708 if (!mEffectChains.isEmpty()) {
3709 mEffectChains[0]->clearInputBuffer();
3710 }
3711
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003713 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3714 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003715 // We have consumed all the buffers of this track.
3716 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003717 // TODO: implement behavior for compressed audio
3718 size_t audioHALFrames =
3719 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3720 size_t framesWritten =
3721 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3722 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003723 if (track->isStopped()) {
3724 track->reset();
3725 }
Eric Laurenta011e352012-03-29 15:51:43 -07003726 trackToRemove = track;
3727 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003728 } else {
3729 // No buffers for this track. Give it a few chances to
3730 // fill a buffer, then remove it from active list.
3731 if (--(track->mRetryCount) <= 0) {
3732 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3733 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003735 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 }
3737 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003738 }
3739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003741 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 // remove all the tracks that need to be...
3743 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003744 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 mActiveTracks.remove(trackToRemove);
3746 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003747 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 trackToRemove->sessionId());
3749 mEffectChains[0]->decActiveTrackCnt();
3750 }
3751 if (trackToRemove->isTerminated()) {
3752 removeTrack_l(trackToRemove);
3753 }
3754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755
Glenn Kastenfec279f2012-03-08 07:47:15 -08003756 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003757}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758
Glenn Kasten000f0e32012-03-01 17:10:56 -08003759void AudioFlinger::DirectOutputThread::threadLoop_mix()
3760{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003761 AudioBufferProvider::Buffer buffer;
3762 size_t frameCount = mFrameCount;
3763 int8_t *curBuf = (int8_t *)mMixBuffer;
3764 // output audio to hardware
3765 while (frameCount) {
3766 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003767 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003768 if (CC_UNLIKELY(buffer.raw == NULL)) {
3769 memset(curBuf, 0, frameCount * mFrameSize);
3770 break;
3771 }
3772 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3773 frameCount -= buffer.frameCount;
3774 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003775 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003776 }
3777 sleepTime = 0;
3778 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003779 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003780
Glenn Kasten000f0e32012-03-01 17:10:56 -08003781}
3782
3783void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3784{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003785 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003786 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003787 sleepTime = activeSleepTime;
3788 } else {
3789 sleepTime = idleSleepTime;
3790 }
3791 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003792 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 sleepTime = 0;
3794 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795}
3796
3797// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003798int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799{
3800 return 0;
3801}
3802
3803// deleteTrackName_l() must be called with ThreadBase::mLock held
3804void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3805{
3806}
3807
3808// checkForNewParameters_l() must be called with ThreadBase::mLock held
3809bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3810{
3811 bool reconfig = false;
3812
3813 while (!mNewParameters.isEmpty()) {
3814 status_t status = NO_ERROR;
3815 String8 keyValuePair = mNewParameters[0];
3816 AudioParameter param = AudioParameter(keyValuePair);
3817 int value;
3818
3819 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3820 // do not accept frame count changes if tracks are open as the track buffer
3821 // size depends on frame count and correct behavior would not be garantied
3822 // if frame count is changed after track creation
3823 if (!mTracks.isEmpty()) {
3824 status = INVALID_OPERATION;
3825 } else {
3826 reconfig = true;
3827 }
3828 }
3829 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003830 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003831 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003833 mOutput->stream->common.standby(&mOutput->stream->common);
3834 mStandby = true;
3835 mBytesWritten = 0;
3836 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003837 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 }
3839 if (status == NO_ERROR && reconfig) {
3840 readOutputParameters();
3841 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3842 }
3843 }
3844
3845 mNewParameters.removeAt(0);
3846
3847 mParamStatus = status;
3848 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003849 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3850 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003851 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 }
3853 return reconfig;
3854}
3855
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003856uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857{
3858 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003859 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003860 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 } else {
3862 time = 10000;
3863 }
3864 return time;
3865}
3866
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003867uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003868{
3869 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003870 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003871 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 } else {
3873 time = 10000;
3874 }
3875 return time;
3876}
3877
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003878uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003879{
3880 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003881 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003882 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3883 } else {
3884 time = 10000;
3885 }
3886 return time;
3887}
3888
Glenn Kasten66fcab92012-02-24 14:59:21 -08003889void AudioFlinger::DirectOutputThread::cacheParameters_l()
3890{
3891 PlaybackThread::cacheParameters_l();
3892
3893 // use shorter standby delay as on normal output to release
3894 // hardware resources as soon as possible
3895 standbyDelay = microseconds(activeSleepTime*2);
3896}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003897
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898// ----------------------------------------------------------------------------
3899
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003900AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003901 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003902 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3903 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 addOutputTrack(mainThread);
3906}
3907
3908AudioFlinger::DuplicatingThread::~DuplicatingThread()
3909{
3910 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3911 mOutputTracks[i]->destroy();
3912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913}
3914
Glenn Kasten000f0e32012-03-01 17:10:56 -08003915void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003917 // mix buffers...
3918 if (outputsReady(outputTracks)) {
3919 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3920 } else {
3921 memset(mMixBuffer, 0, mixBufferSize);
3922 }
3923 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003924 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003925 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003926}
3927
3928void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3929{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003930 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003931 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003932 sleepTime = activeSleepTime;
3933 } else {
3934 sleepTime = idleSleepTime;
3935 }
3936 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003937 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3938 writeFrames = mNormalFrameCount;
3939 memset(mMixBuffer, 0, mixBufferSize);
3940 } else {
3941 // flush remaining overflow buffers in output tracks
3942 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003943 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003944 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003945 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003946}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947
Glenn Kasten000f0e32012-03-01 17:10:56 -08003948void AudioFlinger::DuplicatingThread::threadLoop_write()
3949{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003950 for (size_t i = 0; i < outputTracks.size(); i++) {
3951 outputTracks[i]->write(mMixBuffer, writeFrames);
3952 }
3953 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003954}
Glenn Kasten688a6402012-02-29 07:57:06 -08003955
Glenn Kasten000f0e32012-03-01 17:10:56 -08003956void AudioFlinger::DuplicatingThread::threadLoop_standby()
3957{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003958 // DuplicatingThread implements standby by stopping all tracks
3959 for (size_t i = 0; i < outputTracks.size(); i++) {
3960 outputTracks[i]->stop();
3961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962}
3963
Glenn Kastenfa26a852012-03-06 11:28:04 -08003964void AudioFlinger::DuplicatingThread::saveOutputTracks()
3965{
3966 outputTracks = mOutputTracks;
3967}
3968
3969void AudioFlinger::DuplicatingThread::clearOutputTracks()
3970{
3971 outputTracks.clear();
3972}
3973
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3975{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003976 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003977 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003978 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003979 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 this,
3981 mSampleRate,
3982 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003983 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 frameCount);
3985 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003986 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003988 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003989 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 }
3991}
3992
3993void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3994{
3995 Mutex::Autolock _l(mLock);
3996 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003997 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 mOutputTracks[i]->destroy();
3999 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004000 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 return;
4002 }
4003 }
Steve Block3856b092011-10-20 11:56:00 +01004004 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005}
4006
Glenn Kasten438b0362012-03-06 11:24:48 -08004007// caller must hold mLock
4008void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009{
4010 mWaitTimeMs = UINT_MAX;
4011 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4012 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004013 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4015 if (waitTimeMs < mWaitTimeMs) {
4016 mWaitTimeMs = waitTimeMs;
4017 }
4018 }
4019 }
4020}
4021
4022
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004023bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024{
4025 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004026 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004028 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029 return false;
4030 }
4031 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004032 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004034 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035 return false;
4036 }
4037 }
4038 return true;
4039}
4040
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004041uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042{
4043 return (mWaitTimeMs * 1000) / 2;
4044}
4045
Glenn Kasten66fcab92012-02-24 14:59:21 -08004046void AudioFlinger::DuplicatingThread::cacheParameters_l()
4047{
4048 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4049 updateWaitTime_l();
4050
4051 MixerThread::cacheParameters_l();
4052}
4053
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054// ----------------------------------------------------------------------------
4055
4056// TrackBase constructor must be called with AudioFlinger::mLock held
4057AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004058 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059 const sp<Client>& client,
4060 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004061 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004062 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 const sp<IMemory>& sharedBuffer,
4065 int sessionId)
4066 : RefBase(),
4067 mThread(thread),
4068 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004069 mCblk(NULL),
4070 // mBuffer
4071 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072 mFrameCount(0),
4073 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004074 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004076 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004078 // mChannelCount
4079 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080{
Steve Block3856b092011-10-20 11:56:00 +01004081 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082
Steve Blockb8a80522011-12-20 16:23:08 +00004083 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004084 size_t size = sizeof(audio_track_cblk_t);
4085 uint8_t channelCount = popcount(channelMask);
4086 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4087 if (sharedBuffer == 0) {
4088 size += bufferSize;
4089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004091 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092 mCblkMemory = client->heap()->allocate(size);
4093 if (mCblkMemory != 0) {
4094 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004095 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 new(mCblk) audio_track_cblk_t();
4097 // clear all buffers
4098 mCblk->frameCount = frameCount;
4099 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004100// uncomment the following lines to quickly test 32-bit wraparound
4101// mCblk->user = 0xffff0000;
4102// mCblk->server = 0xffff0000;
4103// mCblk->userBase = 0xffff0000;
4104// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004105 mChannelCount = channelCount;
4106 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 if (sharedBuffer == 0) {
4108 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4109 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4110 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004111 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 mCblk->flags = CBLK_UNDERRUN_ON;
4113 } else {
4114 mBuffer = sharedBuffer->pointer();
4115 }
4116 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4117 }
4118 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004119 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 client->heap()->dump("AudioTrack");
4121 return;
4122 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004123 } else {
4124 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004125 // construct the shared structure in-place.
4126 new(mCblk) audio_track_cblk_t();
4127 // clear all buffers
4128 mCblk->frameCount = frameCount;
4129 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004130// uncomment the following lines to quickly test 32-bit wraparound
4131// mCblk->user = 0xffff0000;
4132// mCblk->server = 0xffff0000;
4133// mCblk->userBase = 0xffff0000;
4134// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004135 mChannelCount = channelCount;
4136 mChannelMask = channelMask;
4137 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4138 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4139 // Force underrun condition to avoid false underrun callback until first data is
4140 // written to buffer (other flags are cleared)
4141 mCblk->flags = CBLK_UNDERRUN_ON;
4142 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144}
4145
4146AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4147{
Glenn Kastena0d68332012-01-27 16:47:15 -08004148 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004149 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004151 } else {
4152 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 }
4154 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004155 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004156 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004157 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004159 // If the client's reference count drops to zero, the associated destructor
4160 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4161 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 mClient.clear();
4163 }
4164}
4165
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004166// AudioBufferProvider interface
4167// getNextBuffer() = 0;
4168// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4170{
Glenn Kastene0feee32011-12-13 11:53:26 -08004171 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004173 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004174 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 buffer->frameCount = 0;
4176}
4177
4178bool AudioFlinger::ThreadBase::TrackBase::step() {
4179 bool result;
4180 audio_track_cblk_t* cblk = this->cblk();
4181
4182 result = cblk->stepServer(mFrameCount);
4183 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004184 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004185 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 }
4187 return result;
4188}
4189
4190void AudioFlinger::ThreadBase::TrackBase::reset() {
4191 audio_track_cblk_t* cblk = this->cblk();
4192
4193 cblk->user = 0;
4194 cblk->server = 0;
4195 cblk->userBase = 0;
4196 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004197 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004198 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199}
4200
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4202 return (int)mCblk->sampleRate;
4203}
4204
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4206 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004207 size_t frameSize = cblk->frameSize;
4208 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4209 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210
4211 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004212 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4213 "TrackBase::getBuffer buffer out of range:\n"
4214 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4215 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004217 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218
4219 return bufferStart;
4220}
4221
Eric Laurenta011e352012-03-29 15:51:43 -07004222status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4223{
4224 mSyncEvents.add(event);
4225 return NO_ERROR;
4226}
4227
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228// ----------------------------------------------------------------------------
4229
4230// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4231AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004232 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004234 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004236 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004237 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238 int frameCount,
4239 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004240 int sessionId,
4241 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004242 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004243 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004244 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004245 // mRetryCount initialized later when needed
4246 mSharedBuffer(sharedBuffer),
4247 mStreamType(streamType),
4248 mName(-1), // see note below
4249 mMainBuffer(thread->mixBuffer()),
4250 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004251 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004252 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004253 mFlags(flags),
4254 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004255 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004256 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257{
4258 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4260 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004261 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004262 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004263 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004264 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004265 if (mName < 0) {
4266 ALOGE("no more track names available");
4267 return;
4268 }
4269 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004270 if (flags & IAudioFlinger::TRACK_FAST) {
4271 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4272 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4273 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004274 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004275 // FIXME This is too eager. We allocate a fast track index before the
4276 // fast track becomes active. Since fast tracks are a scarce resource,
4277 // this means we are potentially denying other more important fast tracks from
4278 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004279 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004280 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004281 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004282 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004283 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004286 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287}
4288
4289AudioFlinger::PlaybackThread::Track::~Track()
4290{
Steve Block3856b092011-10-20 11:56:00 +01004291 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 sp<ThreadBase> thread = mThread.promote();
4293 if (thread != 0) {
4294 Mutex::Autolock _l(thread->mLock);
4295 mState = TERMINATED;
4296 }
4297}
4298
4299void AudioFlinger::PlaybackThread::Track::destroy()
4300{
4301 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4302 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004303 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304 // we must acquire a strong reference on this Track before locking mLock
4305 // here so that the destructor is called only when exiting this function.
4306 // On the other hand, as long as Track::destroy() is only called by
4307 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4308 // this Track with its member mTrack.
4309 sp<Track> keep(this);
4310 { // scope for mLock
4311 sp<ThreadBase> thread = mThread.promote();
4312 if (thread != 0) {
4313 if (!isOutputTrack()) {
4314 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004315 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004316
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004317#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004318 // to track the speaker usage
4319 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004320#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 }
4322 AudioSystem::releaseOutput(thread->id());
4323 }
4324 Mutex::Autolock _l(thread->mLock);
4325 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4326 playbackThread->destroyTrack_l(this);
4327 }
4328 }
4329}
4330
Glenn Kasten288ed212012-04-25 17:52:27 -07004331/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4332{
Glenn Kastene213c862012-04-25 13:46:15 -07004333 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 -07004334 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004335}
4336
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4338{
Glenn Kasten83d86532012-01-17 14:39:34 -08004339 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004340 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004341 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004342 } else {
4343 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4344 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004345 track_state state = mState;
4346 char stateChar;
4347 switch (state) {
4348 case IDLE:
4349 stateChar = 'I';
4350 break;
4351 case TERMINATED:
4352 stateChar = 'T';
4353 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004354 case STOPPING_1:
4355 stateChar = 's';
4356 break;
4357 case STOPPING_2:
4358 stateChar = '5';
4359 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004360 case STOPPED:
4361 stateChar = 'S';
4362 break;
4363 case RESUMING:
4364 stateChar = 'R';
4365 break;
4366 case ACTIVE:
4367 stateChar = 'A';
4368 break;
4369 case PAUSING:
4370 stateChar = 'p';
4371 break;
4372 case PAUSED:
4373 stateChar = 'P';
4374 break;
Eric Laurent29864602012-05-08 18:57:51 -07004375 case FLUSHED:
4376 stateChar = 'F';
4377 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004378 default:
4379 stateChar = '?';
4380 break;
4381 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004382 char nowInUnderrun;
4383 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4384 case UNDERRUN_FULL:
4385 nowInUnderrun = ' ';
4386 break;
4387 case UNDERRUN_PARTIAL:
4388 nowInUnderrun = '<';
4389 break;
4390 case UNDERRUN_EMPTY:
4391 nowInUnderrun = '*';
4392 break;
4393 default:
4394 nowInUnderrun = '?';
4395 break;
4396 }
Glenn Kastene213c862012-04-25 13:46:15 -07004397 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4398 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004399 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 mStreamType,
4401 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004402 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403 mSessionId,
4404 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004405 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004406 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407 mMute,
4408 mFillingUpStatus,
4409 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004410 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4411 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 mCblk->server,
4413 mCblk->user,
4414 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004415 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004416 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004417 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004418 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004419}
4420
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004421// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004422status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004423 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004425 audio_track_cblk_t* cblk = this->cblk();
4426 uint32_t framesReady;
4427 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004429 // Check if last stepServer failed, try to step now
4430 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004431 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4432 // Since the fast mixer is higher priority than client callback thread,
4433 // it does not result in priority inversion for client.
4434 // But a non-blocking solution would be preferable to avoid
4435 // fast mixer being unable to tryLock(), and
4436 // to avoid the extra context switches if the client wakes up,
4437 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004438 if (!step()) goto getNextBuffer_exit;
4439 ALOGV("stepServer recovered");
4440 mStepServerFailed = false;
4441 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442
Glenn Kasten288ed212012-04-25 17:52:27 -07004443 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004444 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004446 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 uint32_t s = cblk->server;
4448 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4449
4450 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4451 if (framesReq > framesReady) {
4452 framesReq = framesReady;
4453 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004454 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 framesReq = bufferEnd - s;
4456 }
4457
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004458 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004459 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462
4463getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004464 buffer->raw = NULL;
4465 buffer->frameCount = 0;
4466 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4467 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468}
4469
Glenn Kasten288ed212012-04-25 17:52:27 -07004470// Note that framesReady() takes a mutex on the control block using tryLock().
4471// This could result in priority inversion if framesReady() is called by the normal mixer,
4472// as the normal mixer thread runs at lower
4473// priority than the client's callback thread: there is a short window within framesReady()
4474// during which the normal mixer could be preempted, and the client callback would block.
4475// Another problem can occur if framesReady() is called by the fast mixer:
4476// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4477// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4478size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004479 return mCblk->framesReady();
4480}
4481
Glenn Kasten288ed212012-04-25 17:52:27 -07004482// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004484 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485
John Grossman4ff14ba2012-02-08 16:37:41 -08004486 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4488 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004489 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 return true;
4491 }
4492 return false;
4493}
4494
Glenn Kasten3acbd052012-02-28 10:39:56 -08004495status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004496 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497{
4498 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004499 ALOGV("start(%d), calling pid %d session %d",
4500 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004501
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 sp<ThreadBase> thread = mThread.promote();
4503 if (thread != 0) {
4504 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004505 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 // here the track could be either new, or restarted
4507 // in both cases "unstop" the track
4508 if (mState == PAUSED) {
4509 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004510 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 } else {
4512 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004513 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 }
4515
4516 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4517 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004518 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004520
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004521#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004522 // to track the speaker usage
4523 if (status == NO_ERROR) {
4524 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4525 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004526#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 }
4528 if (status == NO_ERROR) {
4529 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4530 playbackThread->addTrack_l(this);
4531 } else {
4532 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004533 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534 }
4535 } else {
4536 status = BAD_VALUE;
4537 }
4538 return status;
4539}
4540
4541void AudioFlinger::PlaybackThread::Track::stop()
4542{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004543 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 sp<ThreadBase> thread = mThread.promote();
4545 if (thread != 0) {
4546 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004547 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004548 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549 // If the track is not active (PAUSED and buffers full), flush buffers
4550 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4551 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4552 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004553 mState = STOPPED;
4554 } else if (!isFastTrack()) {
4555 mState = STOPPED;
4556 } else {
4557 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4558 // and then to STOPPED and reset() when presentation is complete
4559 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004561 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 }
4563 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4564 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004565 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004567
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004568#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004569 // to track the speaker usage
4570 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004571#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 }
4573 }
4574}
4575
4576void AudioFlinger::PlaybackThread::Track::pause()
4577{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004578 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579 sp<ThreadBase> thread = mThread.promote();
4580 if (thread != 0) {
4581 Mutex::Autolock _l(thread->mLock);
4582 if (mState == ACTIVE || mState == RESUMING) {
4583 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004584 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 if (!isOutputTrack()) {
4586 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004587 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004589
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004590#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004591 // to track the speaker usage
4592 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004593#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 }
4595 }
4596 }
4597}
4598
4599void AudioFlinger::PlaybackThread::Track::flush()
4600{
Steve Block3856b092011-10-20 11:56:00 +01004601 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 sp<ThreadBase> thread = mThread.promote();
4603 if (thread != 0) {
4604 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004605 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4606 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 return;
4608 }
4609 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004610 // FLUSHED state
4611 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004612 // do not reset the track if it is still in the process of being stopped or paused.
4613 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004614 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004615 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004616 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4617 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4618 reset();
4619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621}
4622
4623void AudioFlinger::PlaybackThread::Track::reset()
4624{
4625 // Do not reset twice to avoid discarding data written just after a flush and before
4626 // the audioflinger thread detects the track is stopped.
4627 if (!mResetDone) {
4628 TrackBase::reset();
4629 // Force underrun condition to avoid false underrun callback until first data is
4630 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004631 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4632 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 mFillingUpStatus = FS_FILLING;
4634 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004635 if (mState == FLUSHED) {
4636 mState = IDLE;
4637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 }
4639}
4640
4641void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4642{
4643 mMute = muted;
4644}
4645
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4647{
4648 status_t status = DEAD_OBJECT;
4649 sp<ThreadBase> thread = mThread.promote();
4650 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004651 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004652 sp<AudioFlinger> af = mClient->audioFlinger();
4653
4654 Mutex::Autolock _l(af->mLock);
4655
4656 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004657
Eric Laurent109347d2012-07-02 12:31:03 -07004658 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004659 Mutex::Autolock _dl(playbackThread->mLock);
4660 Mutex::Autolock _sl(srcThread->mLock);
4661 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4662 if (chain == 0) {
4663 return INVALID_OPERATION;
4664 }
4665
4666 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4667 if (effect == 0) {
4668 return INVALID_OPERATION;
4669 }
4670 srcThread->removeEffect_l(effect);
4671 playbackThread->addEffect_l(effect);
4672 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4673 if (effect->state() == EffectModule::ACTIVE ||
4674 effect->state() == EffectModule::STOPPING) {
4675 effect->start();
4676 }
4677
4678 sp<EffectChain> dstChain = effect->chain().promote();
4679 if (dstChain == 0) {
4680 srcThread->addEffect_l(effect);
4681 return INVALID_OPERATION;
4682 }
4683 AudioSystem::unregisterEffect(effect->id());
4684 AudioSystem::registerEffect(&effect->desc(),
4685 srcThread->id(),
4686 dstChain->strategy(),
4687 AUDIO_SESSION_OUTPUT_MIX,
4688 effect->id());
4689 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004690 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 }
4692 return status;
4693}
4694
4695void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4696{
4697 mAuxEffectId = EffectId;
4698 mAuxBuffer = buffer;
4699}
4700
Eric Laurenta011e352012-03-29 15:51:43 -07004701bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4702 size_t audioHalFrames)
4703{
4704 // a track is considered presented when the total number of frames written to audio HAL
4705 // corresponds to the number of frames written when presentationComplete() is called for the
4706 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4707 if (mPresentationCompleteFrames == 0) {
4708 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4709 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4710 mPresentationCompleteFrames, audioHalFrames);
4711 }
4712 if (framesWritten >= mPresentationCompleteFrames) {
4713 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4714 mSessionId, framesWritten);
4715 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004716 return true;
4717 }
4718 return false;
4719}
4720
4721void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4722{
4723 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4724 if (mSyncEvents[i]->type() == type) {
4725 mSyncEvents[i]->trigger();
4726 mSyncEvents.removeAt(i);
4727 i--;
4728 }
4729 }
4730}
4731
Glenn Kasten58912562012-04-03 10:45:00 -07004732// implement VolumeBufferProvider interface
4733
4734uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4735{
4736 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4737 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4738 uint32_t vlr = mCblk->getVolumeLR();
4739 uint32_t vl = vlr & 0xFFFF;
4740 uint32_t vr = vlr >> 16;
4741 // track volumes come from shared memory, so can't be trusted and must be clamped
4742 if (vl > MAX_GAIN_INT) {
4743 vl = MAX_GAIN_INT;
4744 }
4745 if (vr > MAX_GAIN_INT) {
4746 vr = MAX_GAIN_INT;
4747 }
4748 // now apply the cached master volume and stream type volume;
4749 // this is trusted but lacks any synchronization or barrier so may be stale
4750 float v = mCachedVolume;
4751 vl *= v;
4752 vr *= v;
4753 // re-combine into U4.16
4754 vlr = (vr << 16) | (vl & 0xFFFF);
4755 // FIXME look at mute, pause, and stop flags
4756 return vlr;
4757}
Eric Laurenta011e352012-03-29 15:51:43 -07004758
Eric Laurent29864602012-05-08 18:57:51 -07004759status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4760{
4761 if (mState == TERMINATED || mState == PAUSED ||
4762 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4763 (mState == STOPPED)))) {
4764 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4765 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4766 event->cancel();
4767 return INVALID_OPERATION;
4768 }
4769 TrackBase::setSyncEvent(event);
4770 return NO_ERROR;
4771}
4772
John Grossman4ff14ba2012-02-08 16:37:41 -08004773// timed audio tracks
4774
4775sp<AudioFlinger::PlaybackThread::TimedTrack>
4776AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004777 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004778 const sp<Client>& client,
4779 audio_stream_type_t streamType,
4780 uint32_t sampleRate,
4781 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004782 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004783 int frameCount,
4784 const sp<IMemory>& sharedBuffer,
4785 int sessionId) {
4786 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004787 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004788
Glenn Kastena0356762012-03-19 10:38:51 -07004789 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004790 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4791 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004792}
4793
4794AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004795 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004796 const sp<Client>& client,
4797 audio_stream_type_t streamType,
4798 uint32_t sampleRate,
4799 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004800 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004801 int frameCount,
4802 const sp<IMemory>& sharedBuffer,
4803 int sessionId)
4804 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004805 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004806 mQueueHeadInFlight(false),
4807 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004808 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004809 mTimedSilenceBuffer(NULL),
4810 mTimedSilenceBufferSize(0),
4811 mTimedAudioOutputOnTime(false),
4812 mMediaTimeTransformValid(false)
4813{
4814 LocalClock lc;
4815 mLocalTimeFreq = lc.getLocalFreq();
4816
4817 mLocalTimeToSampleTransform.a_zero = 0;
4818 mLocalTimeToSampleTransform.b_zero = 0;
4819 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4820 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4821 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4822 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004823
4824 mMediaTimeToSampleTransform.a_zero = 0;
4825 mMediaTimeToSampleTransform.b_zero = 0;
4826 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4827 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4828 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4829 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004830}
4831
4832AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4833 mClient->releaseTimedTrack();
4834 delete [] mTimedSilenceBuffer;
4835}
4836
4837status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4838 size_t size, sp<IMemory>* buffer) {
4839
4840 Mutex::Autolock _l(mTimedBufferQueueLock);
4841
4842 trimTimedBufferQueue_l();
4843
4844 // lazily initialize the shared memory heap for timed buffers
4845 if (mTimedMemoryDealer == NULL) {
4846 const int kTimedBufferHeapSize = 512 << 10;
4847
4848 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4849 "AudioFlingerTimed");
4850 if (mTimedMemoryDealer == NULL)
4851 return NO_MEMORY;
4852 }
4853
4854 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4855 if (newBuffer == NULL) {
4856 newBuffer = mTimedMemoryDealer->allocate(size);
4857 if (newBuffer == NULL)
4858 return NO_MEMORY;
4859 }
4860
4861 *buffer = newBuffer;
4862 return NO_ERROR;
4863}
4864
4865// caller must hold mTimedBufferQueueLock
4866void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4867 int64_t mediaTimeNow;
4868 {
4869 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4870 if (!mMediaTimeTransformValid)
4871 return;
4872
4873 int64_t targetTimeNow;
4874 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4875 ? mCCHelper.getCommonTime(&targetTimeNow)
4876 : mCCHelper.getLocalTime(&targetTimeNow);
4877
4878 if (OK != res)
4879 return;
4880
4881 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4882 &mediaTimeNow)) {
4883 return;
4884 }
4885 }
4886
John Grossman1c345192012-03-27 14:00:17 -07004887 size_t trimEnd;
4888 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004889 int64_t bufEnd;
4890
John Grossmanc95cfbb2012-04-12 11:53:11 -07004891 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4892 // We have a next buffer. Just use its PTS as the PTS of the frame
4893 // following the last frame in this buffer. If the stream is sparse
4894 // (ie, there are deliberate gaps left in the stream which should be
4895 // filled with silence by the TimedAudioTrack), then this can result
4896 // in one extra buffer being left un-trimmed when it could have
4897 // been. In general, this is not typical, and we would rather
4898 // optimized away the TS calculation below for the more common case
4899 // where PTSes are contiguous.
4900 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4901 } else {
4902 // We have no next buffer. Compute the PTS of the frame following
4903 // the last frame in this buffer by computing the duration of of
4904 // this frame in media time units and adding it to the PTS of the
4905 // buffer.
4906 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4907 / mCblk->frameSize;
4908
4909 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4910 &bufEnd)) {
4911 ALOGE("Failed to convert frame count of %lld to media time"
4912 " duration" " (scale factor %d/%u) in %s",
4913 frameCount,
4914 mMediaTimeToSampleTransform.a_to_b_numer,
4915 mMediaTimeToSampleTransform.a_to_b_denom,
4916 __PRETTY_FUNCTION__);
4917 break;
4918 }
4919 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004920 }
John Grossman9fbdee12012-03-26 17:51:46 -07004921
4922 if (bufEnd > mediaTimeNow)
4923 break;
4924
4925 // Is the buffer we want to use in the middle of a mix operation right
4926 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4927 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004928 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004929 mTrimQueueHeadOnRelease = true;
4930 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004931 }
4932
John Grossman9fbdee12012-03-26 17:51:46 -07004933 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004934 if (trimStart < trimEnd) {
4935 // Update the bookkeeping for framesReady()
4936 for (size_t i = trimStart; i < trimEnd; ++i) {
4937 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4938 }
4939
4940 // Now actually remove the buffers from the queue.
4941 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004942 }
4943}
4944
John Grossman1c345192012-03-27 14:00:17 -07004945void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4946 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004947 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4948 "%s called (reason \"%s\"), but timed buffer queue has no"
4949 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004950
4951 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4952 mTimedBufferQueue.removeAt(0);
4953}
4954
4955void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4956 const TimedBuffer& buf,
4957 const char* logTag) {
4958 uint32_t bufBytes = buf.buffer()->size();
4959 uint32_t consumedAlready = buf.position();
4960
Eric Laurentb388e532012-04-14 13:32:48 -07004961 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004962 "Bad bookkeeping while updating frames pending. Timed buffer is"
4963 " only %u bytes long, but claims to have consumed %u"
4964 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004965 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004966
4967 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004968 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4969 "Bad bookkeeping while updating frames pending. Should have at"
4970 " least %u queued frames, but we think we have only %u. (update"
4971 " reason: \"%s\")",
4972 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004973
4974 mFramesPendingInQueue -= bufFrames;
4975}
4976
John Grossman4ff14ba2012-02-08 16:37:41 -08004977status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4978 const sp<IMemory>& buffer, int64_t pts) {
4979
4980 {
4981 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4982 if (!mMediaTimeTransformValid)
4983 return INVALID_OPERATION;
4984 }
4985
4986 Mutex::Autolock _l(mTimedBufferQueueLock);
4987
John Grossman1c345192012-03-27 14:00:17 -07004988 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4989 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004990 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4991
4992 return NO_ERROR;
4993}
4994
4995status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4996 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4997
John Grossman1c345192012-03-27 14:00:17 -07004998 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4999 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5000 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005001
5002 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5003 target == TimedAudioTrack::COMMON_TIME)) {
5004 return BAD_VALUE;
5005 }
5006
5007 Mutex::Autolock lock(mMediaTimeTransformLock);
5008 mMediaTimeTransform = xform;
5009 mMediaTimeTransformTarget = target;
5010 mMediaTimeTransformValid = true;
5011
5012 return NO_ERROR;
5013}
5014
5015#define min(a, b) ((a) < (b) ? (a) : (b))
5016
5017// implementation of getNextBuffer for tracks whose buffers have timestamps
5018status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5019 AudioBufferProvider::Buffer* buffer, int64_t pts)
5020{
5021 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005022 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005024 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005025 return INVALID_OPERATION;
5026 }
5027
John Grossman4ff14ba2012-02-08 16:37:41 -08005028 Mutex::Autolock _l(mTimedBufferQueueLock);
5029
John Grossman9fbdee12012-03-26 17:51:46 -07005030 ALOG_ASSERT(!mQueueHeadInFlight,
5031 "getNextBuffer called without releaseBuffer!");
5032
John Grossman4ff14ba2012-02-08 16:37:41 -08005033 while (true) {
5034
5035 // if we have no timed buffers, then fail
5036 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005037 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005038 buffer->frameCount = 0;
5039 return NOT_ENOUGH_DATA;
5040 }
5041
5042 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5043
5044 // calculate the PTS of the head of the timed buffer queue expressed in
5045 // local time
5046 int64_t headLocalPTS;
5047 {
5048 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5049
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005050 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005051
5052 if (mMediaTimeTransform.a_to_b_denom == 0) {
5053 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005054 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005055 return NO_ERROR;
5056 }
5057
5058 int64_t transformedPTS;
5059 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5060 &transformedPTS)) {
5061 // the transform failed. this shouldn't happen, but if it does
5062 // then just drop this buffer
5063 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005064 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005065 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005066 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 return NO_ERROR;
5068 }
5069
5070 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5071 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5072 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005073 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005074 buffer->frameCount = 0;
5075 return INVALID_OPERATION;
5076 }
5077 } else {
5078 headLocalPTS = transformedPTS;
5079 }
5080 }
5081
5082 // adjust the head buffer's PTS to reflect the portion of the head buffer
5083 // that has already been consumed
5084 int64_t effectivePTS = headLocalPTS +
5085 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5086
5087 // Calculate the delta in samples between the head of the input buffer
5088 // queue and the start of the next output buffer that will be written.
5089 // If the transformation fails because of over or underflow, it means
5090 // that the sample's position in the output stream is so far out of
5091 // whack that it should just be dropped.
5092 int64_t sampleDelta;
5093 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5094 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005095 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5096 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005097 continue;
5098 }
5099 if (!mLocalTimeToSampleTransform.doForwardTransform(
5100 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005101 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005102 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 continue;
5104 }
5105
John Grossman1c345192012-03-27 14:00:17 -07005106 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5107 " sampleDelta=[%d.%08x]",
5108 head.pts(), head.position(), pts,
5109 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5110 + (sampleDelta >> 32)),
5111 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005112
5113 // if the delta between the ideal placement for the next input sample and
5114 // the current output position is within this threshold, then we will
5115 // concatenate the next input samples to the previous output
5116 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005117 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005118
5119 // if this is the first buffer of audio that we're emitting from this track
5120 // then it should be almost exactly on time.
5121 const int64_t kSampleStartupThreshold = 1LL << 32;
5122
5123 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005124 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005125 // the next input is close enough to being on time, so concatenate it
5126 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005127 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005128
John Grossman1c345192012-03-27 14:00:17 -07005129 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5130 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005131 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005132 }
5133
5134 // Looks like our output is not on time. Reset our on timed status.
5135 // Next time we mix samples from our input queue, then should be within
5136 // the StartupThreshold.
5137 mTimedAudioOutputOnTime = false;
5138 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005139 // the gap between the current output position and the proper start of
5140 // the next input sample is too big, so fill it with silence
5141 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5142
John Grossman9fbdee12012-03-26 17:51:46 -07005143 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005144 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5145 return NO_ERROR;
5146 } else {
5147 // the next input sample is late
5148 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5149 size_t onTimeSamplePosition =
5150 head.position() + lateFrames * mCblk->frameSize;
5151
5152 if (onTimeSamplePosition > head.buffer()->size()) {
5153 // all the remaining samples in the head are too late, so
5154 // drop it and move on
5155 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005156 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005157 continue;
5158 } else {
5159 // skip over the late samples
5160 head.setPosition(onTimeSamplePosition);
5161
5162 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005163 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005164
5165 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5166 return NO_ERROR;
5167 }
5168 }
5169 }
5170}
5171
5172// Yield samples from the timed buffer queue head up to the given output
5173// buffer's capacity.
5174//
5175// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005176void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005177 AudioBufferProvider::Buffer* buffer) {
5178
5179 const TimedBuffer& head = mTimedBufferQueue[0];
5180
5181 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5182 head.position());
5183
5184 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5185 mCblk->frameSize);
5186 size_t framesRequested = buffer->frameCount;
5187 buffer->frameCount = min(framesLeftInHead, framesRequested);
5188
John Grossman9fbdee12012-03-26 17:51:46 -07005189 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005190 mTimedAudioOutputOnTime = true;
5191}
5192
5193// Yield samples of silence up to the given output buffer's capacity
5194//
5195// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005196void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005197 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5198
5199 // lazily allocate a buffer filled with silence
5200 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5201 delete [] mTimedSilenceBuffer;
5202 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5203 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5204 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5205 }
5206
5207 buffer->raw = mTimedSilenceBuffer;
5208 size_t framesRequested = buffer->frameCount;
5209 buffer->frameCount = min(numFrames, framesRequested);
5210
5211 mTimedAudioOutputOnTime = false;
5212}
5213
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005214// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005215void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5216 AudioBufferProvider::Buffer* buffer) {
5217
5218 Mutex::Autolock _l(mTimedBufferQueueLock);
5219
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005220 // If the buffer which was just released is part of the buffer at the head
5221 // of the queue, be sure to update the amt of the buffer which has been
5222 // consumed. If the buffer being returned is not part of the head of the
5223 // queue, its either because the buffer is part of the silence buffer, or
5224 // because the head of the timed queue was trimmed after the mixer called
5225 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005226 if (buffer->raw == mTimedSilenceBuffer) {
5227 ALOG_ASSERT(!mQueueHeadInFlight,
5228 "Queue head in flight during release of silence buffer!");
5229 goto done;
5230 }
5231
5232 ALOG_ASSERT(mQueueHeadInFlight,
5233 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5234 " head in flight.");
5235
5236 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005237 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005238
5239 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005240 void* end = reinterpret_cast<void*>(
5241 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5242 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005243
John Grossman9fbdee12012-03-26 17:51:46 -07005244 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5245 "released buffer not within the head of the timed buffer"
5246 " queue; qHead = [%p, %p], released buffer = %p",
5247 start, end, buffer->raw);
5248
5249 head.setPosition(head.position() +
5250 (buffer->frameCount * mCblk->frameSize));
5251 mQueueHeadInFlight = false;
5252
John Grossman1c345192012-03-27 14:00:17 -07005253 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5254 "Bad bookkeeping during releaseBuffer! Should have at"
5255 " least %u queued frames, but we think we have only %u",
5256 buffer->frameCount, mFramesPendingInQueue);
5257
5258 mFramesPendingInQueue -= buffer->frameCount;
5259
John Grossman9fbdee12012-03-26 17:51:46 -07005260 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5261 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005262 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005263 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005264 }
John Grossman9fbdee12012-03-26 17:51:46 -07005265 } else {
5266 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5267 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 }
5269
John Grossman9fbdee12012-03-26 17:51:46 -07005270done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005271 buffer->raw = 0;
5272 buffer->frameCount = 0;
5273}
5274
Glenn Kasten288ed212012-04-25 17:52:27 -07005275size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005276 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005277 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005278}
5279
5280AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5281 : mPTS(0), mPosition(0) {}
5282
5283AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5284 const sp<IMemory>& buffer, int64_t pts)
5285 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5286
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287// ----------------------------------------------------------------------------
5288
5289// RecordTrack constructor must be called with AudioFlinger::mLock held
5290AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005291 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005292 const sp<Client>& client,
5293 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005294 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005295 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297 int sessionId)
5298 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005299 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005300 mOverflow(false)
5301{
5302 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005303 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5304 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5305 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5306 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5307 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5308 } else {
5309 mCblk->frameSize = sizeof(int8_t);
5310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311 }
5312}
5313
5314AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5315{
5316 sp<ThreadBase> thread = mThread.promote();
5317 if (thread != 0) {
5318 AudioSystem::releaseInput(thread->id());
5319 }
5320}
5321
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005322// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005323status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005324{
5325 audio_track_cblk_t* cblk = this->cblk();
5326 uint32_t framesAvail;
5327 uint32_t framesReq = buffer->frameCount;
5328
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005329 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005330 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005332 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005333 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 }
5335
5336 framesAvail = cblk->framesAvailable_l();
5337
Glenn Kastenf6b16782011-12-15 09:51:17 -08005338 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339 uint32_t s = cblk->server;
5340 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5341
5342 if (framesReq > framesAvail) {
5343 framesReq = framesAvail;
5344 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005345 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 framesReq = bufferEnd - s;
5347 }
5348
5349 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350 buffer->frameCount = framesReq;
5351 return NO_ERROR;
5352 }
5353
5354getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005355 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 buffer->frameCount = 0;
5357 return NOT_ENOUGH_DATA;
5358}
5359
Glenn Kasten3acbd052012-02-28 10:39:56 -08005360status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005361 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005362{
5363 sp<ThreadBase> thread = mThread.promote();
5364 if (thread != 0) {
5365 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005366 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 } else {
5368 return BAD_VALUE;
5369 }
5370}
5371
5372void AudioFlinger::RecordThread::RecordTrack::stop()
5373{
5374 sp<ThreadBase> thread = mThread.promote();
5375 if (thread != 0) {
5376 RecordThread *recordThread = (RecordThread *)thread.get();
5377 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005378 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005379 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005380 // read from buffer
5381 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 }
5383}
5384
5385void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5386{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005387 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005388 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005390 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 mSessionId,
5392 mFrameCount,
5393 mState,
5394 mCblk->sampleRate,
5395 mCblk->server,
5396 mCblk->user);
5397}
5398
5399
5400// ----------------------------------------------------------------------------
5401
5402AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005403 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 DuplicatingThread *sourceThread,
5405 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005406 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005407 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005409 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5410 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 mActive(false), mSourceThread(sourceThread)
5412{
5413
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 if (mCblk != NULL) {
5415 mCblk->flags |= CBLK_DIRECTION_OUT;
5416 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 mOutBuffer.frameCount = 0;
5418 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005419 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005420 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5421 mCblk, mBuffer, mCblk->buffers,
5422 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005424 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 }
5426}
5427
5428AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5429{
5430 clearBufferQueue();
5431}
5432
Glenn Kasten3acbd052012-02-28 10:39:56 -08005433status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005434 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005436 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437 if (status != NO_ERROR) {
5438 return status;
5439 }
5440
5441 mActive = true;
5442 mRetryCount = 127;
5443 return status;
5444}
5445
5446void AudioFlinger::PlaybackThread::OutputTrack::stop()
5447{
5448 Track::stop();
5449 clearBufferQueue();
5450 mOutBuffer.frameCount = 0;
5451 mActive = false;
5452}
5453
5454bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5455{
5456 Buffer *pInBuffer;
5457 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005458 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 bool outputBufferFull = false;
5460 inBuffer.frameCount = frames;
5461 inBuffer.i16 = data;
5462
5463 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5464
5465 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005466 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 sp<ThreadBase> thread = mThread.promote();
5468 if (thread != 0) {
5469 MixerThread *mixerThread = (MixerThread *)thread.get();
5470 if (mCblk->frameCount > frames){
5471 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5472 uint32_t startFrames = (mCblk->frameCount - frames);
5473 pInBuffer = new Buffer;
5474 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5475 pInBuffer->frameCount = startFrames;
5476 pInBuffer->i16 = pInBuffer->mBuffer;
5477 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5478 mBufferQueue.add(pInBuffer);
5479 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005480 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 }
5482 }
5483 }
5484 }
5485
5486 while (waitTimeLeftMs) {
5487 // First write pending buffers, then new data
5488 if (mBufferQueue.size()) {
5489 pInBuffer = mBufferQueue.itemAt(0);
5490 } else {
5491 pInBuffer = &inBuffer;
5492 }
5493
5494 if (pInBuffer->frameCount == 0) {
5495 break;
5496 }
5497
5498 if (mOutBuffer.frameCount == 0) {
5499 mOutBuffer.frameCount = pInBuffer->frameCount;
5500 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005501 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005502 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 outputBufferFull = true;
5504 break;
5505 }
5506 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5507 if (waitTimeLeftMs >= waitTimeMs) {
5508 waitTimeLeftMs -= waitTimeMs;
5509 } else {
5510 waitTimeLeftMs = 0;
5511 }
5512 }
5513
5514 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5515 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5516 mCblk->stepUser(outFrames);
5517 pInBuffer->frameCount -= outFrames;
5518 pInBuffer->i16 += outFrames * channelCount;
5519 mOutBuffer.frameCount -= outFrames;
5520 mOutBuffer.i16 += outFrames * channelCount;
5521
5522 if (pInBuffer->frameCount == 0) {
5523 if (mBufferQueue.size()) {
5524 mBufferQueue.removeAt(0);
5525 delete [] pInBuffer->mBuffer;
5526 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005527 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 } else {
5529 break;
5530 }
5531 }
5532 }
5533
5534 // If we could not write all frames, allocate a buffer and queue it for next time.
5535 if (inBuffer.frameCount) {
5536 sp<ThreadBase> thread = mThread.promote();
5537 if (thread != 0 && !thread->standby()) {
5538 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5539 pInBuffer = new Buffer;
5540 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5541 pInBuffer->frameCount = inBuffer.frameCount;
5542 pInBuffer->i16 = pInBuffer->mBuffer;
5543 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5544 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005545 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005547 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 }
5549 }
5550 }
5551
5552 // Calling write() with a 0 length buffer, means that no more data will be written:
5553 // If no more buffers are pending, fill output track buffer to make sure it is started
5554 // by output mixer.
5555 if (frames == 0 && mBufferQueue.size() == 0) {
5556 if (mCblk->user < mCblk->frameCount) {
5557 frames = mCblk->frameCount - mCblk->user;
5558 pInBuffer = new Buffer;
5559 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5560 pInBuffer->frameCount = frames;
5561 pInBuffer->i16 = pInBuffer->mBuffer;
5562 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5563 mBufferQueue.add(pInBuffer);
5564 } else if (mActive) {
5565 stop();
5566 }
5567 }
5568
5569 return outputBufferFull;
5570}
5571
5572status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5573{
5574 int active;
5575 status_t result;
5576 audio_track_cblk_t* cblk = mCblk;
5577 uint32_t framesReq = buffer->frameCount;
5578
Steve Block3856b092011-10-20 11:56:00 +01005579// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580 buffer->frameCount = 0;
5581
5582 uint32_t framesAvail = cblk->framesAvailable();
5583
5584
5585 if (framesAvail == 0) {
5586 Mutex::Autolock _l(cblk->lock);
5587 goto start_loop_here;
5588 while (framesAvail == 0) {
5589 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005590 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005591 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005592 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 }
5594 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5595 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005596 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 }
5598 // read the server count again
5599 start_loop_here:
5600 framesAvail = cblk->framesAvailable_l();
5601 }
5602 }
5603
5604// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005605// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606// }
5607
5608 if (framesReq > framesAvail) {
5609 framesReq = framesAvail;
5610 }
5611
5612 uint32_t u = cblk->user;
5613 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5614
Marco Nelissena1472d92012-03-30 14:36:54 -07005615 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 framesReq = bufferEnd - u;
5617 }
5618
5619 buffer->frameCount = framesReq;
5620 buffer->raw = (void *)cblk->buffer(u);
5621 return NO_ERROR;
5622}
5623
5624
5625void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5626{
5627 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628
5629 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005630 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 delete [] pBuffer->mBuffer;
5632 delete pBuffer;
5633 }
5634 mBufferQueue.clear();
5635}
5636
5637// ----------------------------------------------------------------------------
5638
5639AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5640 : RefBase(),
5641 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005642 // 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 -07005643 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005644 mPid(pid),
5645 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646{
5647 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5648}
5649
5650// Client destructor must be called with AudioFlinger::mLock held
5651AudioFlinger::Client::~Client()
5652{
5653 mAudioFlinger->removeClient_l(mPid);
5654}
5655
Glenn Kasten435dbe62012-01-30 10:15:48 -08005656sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657{
5658 return mMemoryDealer;
5659}
5660
John Grossman4ff14ba2012-02-08 16:37:41 -08005661// Reserve one of the limited slots for a timed audio track associated
5662// with this client
5663bool AudioFlinger::Client::reserveTimedTrack()
5664{
5665 const int kMaxTimedTracksPerClient = 4;
5666
5667 Mutex::Autolock _l(mTimedTrackLock);
5668
5669 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5670 ALOGW("can not create timed track - pid %d has exceeded the limit",
5671 mPid);
5672 return false;
5673 }
5674
5675 mTimedTrackCount++;
5676 return true;
5677}
5678
5679// Release a slot for a timed audio track
5680void AudioFlinger::Client::releaseTimedTrack()
5681{
5682 Mutex::Autolock _l(mTimedTrackLock);
5683 mTimedTrackCount--;
5684}
5685
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686// ----------------------------------------------------------------------------
5687
5688AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5689 const sp<IAudioFlingerClient>& client,
5690 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005691 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692{
5693}
5694
5695AudioFlinger::NotificationClient::~NotificationClient()
5696{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005697}
5698
5699void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5700{
5701 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005702 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703}
5704
5705// ----------------------------------------------------------------------------
5706
5707AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5708 : BnAudioTrack(),
5709 mTrack(track)
5710{
5711}
5712
5713AudioFlinger::TrackHandle::~TrackHandle() {
5714 // just stop the track on deletion, associated resources
5715 // will be freed from the main thread once all pending buffers have
5716 // been played. Unless it's not in the active track list, in which
5717 // case we free everything now...
5718 mTrack->destroy();
5719}
5720
Glenn Kasten90716c52012-01-26 13:40:12 -08005721sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5722 return mTrack->getCblk();
5723}
5724
Glenn Kasten3acbd052012-02-28 10:39:56 -08005725status_t AudioFlinger::TrackHandle::start() {
5726 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727}
5728
5729void AudioFlinger::TrackHandle::stop() {
5730 mTrack->stop();
5731}
5732
5733void AudioFlinger::TrackHandle::flush() {
5734 mTrack->flush();
5735}
5736
5737void AudioFlinger::TrackHandle::mute(bool e) {
5738 mTrack->mute(e);
5739}
5740
5741void AudioFlinger::TrackHandle::pause() {
5742 mTrack->pause();
5743}
5744
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5746{
5747 return mTrack->attachAuxEffect(EffectId);
5748}
5749
John Grossman4ff14ba2012-02-08 16:37:41 -08005750status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5751 sp<IMemory>* buffer) {
5752 if (!mTrack->isTimedTrack())
5753 return INVALID_OPERATION;
5754
5755 PlaybackThread::TimedTrack* tt =
5756 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5757 return tt->allocateTimedBuffer(size, buffer);
5758}
5759
5760status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5761 int64_t pts) {
5762 if (!mTrack->isTimedTrack())
5763 return INVALID_OPERATION;
5764
5765 PlaybackThread::TimedTrack* tt =
5766 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5767 return tt->queueTimedBuffer(buffer, pts);
5768}
5769
5770status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5771 const LinearTransform& xform, int target) {
5772
5773 if (!mTrack->isTimedTrack())
5774 return INVALID_OPERATION;
5775
5776 PlaybackThread::TimedTrack* tt =
5777 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5778 return tt->setMediaTimeTransform(
5779 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5780}
5781
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782status_t AudioFlinger::TrackHandle::onTransact(
5783 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5784{
5785 return BnAudioTrack::onTransact(code, data, reply, flags);
5786}
5787
5788// ----------------------------------------------------------------------------
5789
5790sp<IAudioRecord> AudioFlinger::openRecord(
5791 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005792 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005794 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005795 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005797 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005798 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 int *sessionId,
5800 status_t *status)
5801{
5802 sp<RecordThread::RecordTrack> recordTrack;
5803 sp<RecordHandle> recordHandle;
5804 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 status_t lStatus;
5806 RecordThread *thread;
5807 size_t inFrameCount;
5808 int lSessionId;
5809
5810 // check calling permissions
5811 if (!recordingAllowed()) {
5812 lStatus = PERMISSION_DENIED;
5813 goto Exit;
5814 }
5815
5816 // add client to list
5817 { // scope for mLock
5818 Mutex::Autolock _l(mLock);
5819 thread = checkRecordThread_l(input);
5820 if (thread == NULL) {
5821 lStatus = BAD_VALUE;
5822 goto Exit;
5823 }
5824
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005825 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826
5827 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005828 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 lSessionId = *sessionId;
5830 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005831 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 if (sessionId != NULL) {
5833 *sessionId = lSessionId;
5834 }
5835 }
5836 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005837 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5838 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005840 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5842 // destructor is called by the TrackBase destructor with mLock held
5843 client.clear();
5844 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845 goto Exit;
5846 }
5847
5848 // return to handle to client
5849 recordHandle = new RecordHandle(recordTrack);
5850 lStatus = NO_ERROR;
5851
5852Exit:
5853 if (status) {
5854 *status = lStatus;
5855 }
5856 return recordHandle;
5857}
5858
5859// ----------------------------------------------------------------------------
5860
5861AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5862 : BnAudioRecord(),
5863 mRecordTrack(recordTrack)
5864{
5865}
5866
5867AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005868 stop_nonvirtual();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869}
5870
Glenn Kasten90716c52012-01-26 13:40:12 -08005871sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5872 return mRecordTrack->getCblk();
5873}
5874
Glenn Kasten3acbd052012-02-28 10:39:56 -08005875status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005876 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005877 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878}
5879
5880void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005881 stop_nonvirtual();
5882}
5883
5884void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005885 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886 mRecordTrack->stop();
5887}
5888
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889status_t AudioFlinger::RecordHandle::onTransact(
5890 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5891{
5892 return BnAudioRecord::onTransact(code, data, reply, flags);
5893}
5894
5895// ----------------------------------------------------------------------------
5896
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005897AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5898 AudioStreamIn *input,
5899 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005900 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005901 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005902 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005903 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005904 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5905 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005906 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005907 mReqSampleRate(sampleRate)
5908 // mBytesRead is only meaningful while active, and so is cleared in start()
5909 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910{
Glenn Kasten480b4682012-02-28 12:30:08 -08005911 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005912
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 readInputParameters();
5914}
5915
5916
5917AudioFlinger::RecordThread::~RecordThread()
5918{
5919 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005920 delete mResampler;
5921 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922}
5923
5924void AudioFlinger::RecordThread::onFirstRef()
5925{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005926 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927}
5928
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005929status_t AudioFlinger::RecordThread::readyToRun()
5930{
5931 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005932 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005933 return status;
5934}
5935
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936bool AudioFlinger::RecordThread::threadLoop()
5937{
5938 AudioBufferProvider::Buffer buffer;
5939 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005940 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941
Eric Laurent44d98482010-09-30 16:12:31 -07005942 nsecs_t lastWarning = 0;
5943
Eric Laurentfeb0db62011-07-22 09:04:31 -07005944 acquireWakeLock();
5945
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 // start recording
5947 while (!exitPending()) {
5948
5949 processConfigEvents();
5950
5951 { // scope for mLock
5952 Mutex::Autolock _l(mLock);
5953 checkForNewParameters_l();
5954 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5955 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005956 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 mStandby = true;
5958 }
5959
5960 if (exitPending()) break;
5961
Eric Laurentfeb0db62011-07-22 09:04:31 -07005962 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005963 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 // go to sleep
5965 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005966 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005967 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 continue;
5969 }
5970 if (mActiveTrack != 0) {
5971 if (mActiveTrack->mState == TrackBase::PAUSING) {
5972 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005973 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 mStandby = true;
5975 }
5976 mActiveTrack.clear();
5977 mStartStopCond.broadcast();
5978 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5979 if (mReqChannelCount != mActiveTrack->channelCount()) {
5980 mActiveTrack.clear();
5981 mStartStopCond.broadcast();
5982 } else if (mBytesRead != 0) {
5983 // record start succeeds only if first read from audio input
5984 // succeeds
5985 if (mBytesRead > 0) {
5986 mActiveTrack->mState = TrackBase::ACTIVE;
5987 } else {
5988 mActiveTrack.clear();
5989 }
5990 mStartStopCond.broadcast();
5991 }
5992 mStandby = false;
5993 }
5994 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005995 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
5997
5998 if (mActiveTrack != 0) {
5999 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6000 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006001 unlockEffectChains(effectChains);
6002 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 continue;
6004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006005 for (size_t i = 0; i < effectChains.size(); i ++) {
6006 effectChains[i]->process_l();
6007 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006008
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006010 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006012 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 // no resampling
6014 while (framesOut) {
6015 size_t framesIn = mFrameCount - mRsmpInIndex;
6016 if (framesIn) {
6017 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6018 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6019 if (framesIn > framesOut)
6020 framesIn = framesOut;
6021 mRsmpInIndex += framesIn;
6022 framesOut -= framesIn;
6023 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006024 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025 memcpy(dst, src, framesIn * mFrameSize);
6026 } else {
6027 int16_t *src16 = (int16_t *)src;
6028 int16_t *dst16 = (int16_t *)dst;
6029 if (mChannelCount == 1) {
6030 while (framesIn--) {
6031 *dst16++ = *src16;
6032 *dst16++ = *src16++;
6033 }
6034 } else {
6035 while (framesIn--) {
6036 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6037 src16 += 2;
6038 }
6039 }
6040 }
6041 }
6042 if (framesOut && mFrameCount == mRsmpInIndex) {
6043 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006044 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006045 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 framesOut = 0;
6047 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006048 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 mRsmpInIndex = 0;
6050 }
6051 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006052 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6054 // Force input into standby so that it tries to
6055 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006056 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 }
6059 mRsmpInIndex = mFrameCount;
6060 framesOut = 0;
6061 buffer.frameCount = 0;
6062 }
6063 }
6064 }
6065 } else {
6066 // resampling
6067
6068 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6069 // alter output frame count as if we were expecting stereo samples
6070 if (mChannelCount == 1 && mReqChannelCount == 1) {
6071 framesOut >>= 1;
6072 }
6073 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6074 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6075 // are 32 bit aligned which should be always true.
6076 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006077 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078 // the resampler always outputs stereo samples: do post stereo to mono conversion
6079 int16_t *src = (int16_t *)mRsmpOutBuffer;
6080 int16_t *dst = buffer.i16;
6081 while (framesOut--) {
6082 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6083 src += 2;
6084 }
6085 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006086 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 }
6088
6089 }
Eric Laurenta011e352012-03-29 15:51:43 -07006090 if (mFramestoDrop == 0) {
6091 mActiveTrack->releaseBuffer(&buffer);
6092 } else {
6093 if (mFramestoDrop > 0) {
6094 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006095 if (mFramestoDrop <= 0) {
6096 clearSyncStartEvent();
6097 }
6098 } else {
6099 mFramestoDrop += buffer.frameCount;
6100 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6101 mSyncStartEvent->isCancelled()) {
6102 ALOGW("Synced record %s, session %d, trigger session %d",
6103 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6104 mActiveTrack->sessionId(),
6105 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6106 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006107 }
6108 }
6109 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006110 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 }
6112 // client isn't retrieving buffers fast enough
6113 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006114 if (!mActiveTrack->setOverflow()) {
6115 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006116 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006117 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006118 lastWarning = now;
6119 }
6120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 // Release the processor for a while before asking for a new buffer.
6122 // This will give the application more chance to read from the buffer and
6123 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 }
6126 }
Eric Laurentec437d82011-07-26 20:54:46 -07006127 // enable changes in effect chain
6128 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006129 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 }
6131
6132 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006133 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
6135 mActiveTrack.clear();
6136
6137 mStartStopCond.broadcast();
6138
Eric Laurentfeb0db62011-07-22 09:04:31 -07006139 releaseWakeLock();
6140
Steve Block3856b092011-10-20 11:56:00 +01006141 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 return false;
6143}
6144
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006145
6146sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6147 const sp<AudioFlinger::Client>& client,
6148 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006149 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006150 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006151 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006153 IAudioFlinger::track_flags_t flags,
6154 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006155 status_t *status)
6156{
6157 sp<RecordTrack> track;
6158 status_t lStatus;
6159
6160 lStatus = initCheck();
6161 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006162 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006163 goto Exit;
6164 }
6165
Glenn Kasten1879fff2012-07-11 15:36:59 -07006166 // FIXME use flags and tid similar to createTrack_l()
6167
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006168 { // scope for mLock
6169 Mutex::Autolock _l(mLock);
6170
6171 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006172 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006173
Glenn Kasten7378ca52012-01-20 13:44:40 -08006174 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006175 lStatus = NO_MEMORY;
6176 goto Exit;
6177 }
6178
6179 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006180 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006181 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6182 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006183 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6184 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006185 }
6186 lStatus = NO_ERROR;
6187
6188Exit:
6189 if (status) {
6190 *status = lStatus;
6191 }
6192 return track;
6193}
6194
Eric Laurenta011e352012-03-29 15:51:43 -07006195status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006196 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006197 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198{
Glenn Kasten58912562012-04-03 10:45:00 -07006199 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006200 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006202
6203 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006204 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006205 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6206 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6207 triggerSession,
6208 recordTrack->sessionId(),
6209 syncStartEventCallback,
6210 this);
Eric Laurent29864602012-05-08 18:57:51 -07006211 // Sync event can be cancelled by the trigger session if the track is not in a
6212 // compatible state in which case we start record immediately
6213 if (mSyncStartEvent->isCancelled()) {
6214 clearSyncStartEvent();
6215 } else {
6216 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6217 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6218 }
Eric Laurenta011e352012-03-29 15:51:43 -07006219 }
6220
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006222 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 if (mActiveTrack != 0) {
6224 if (recordTrack != mActiveTrack.get()) {
6225 status = -EBUSY;
6226 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6227 mActiveTrack->mState = TrackBase::ACTIVE;
6228 }
6229 return status;
6230 }
6231
6232 recordTrack->mState = TrackBase::IDLE;
6233 mActiveTrack = recordTrack;
6234 mLock.unlock();
6235 status_t status = AudioSystem::startInput(mId);
6236 mLock.lock();
6237 if (status != NO_ERROR) {
6238 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006239 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 return status;
6241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 mRsmpInIndex = mFrameCount;
6243 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006244 if (mResampler != NULL) {
6245 mResampler->reset();
6246 }
6247 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006249 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 mWaitWorkCV.signal();
6251 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006252 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 mActiveTrack.clear();
6254 status = INVALID_OPERATION;
6255 goto startError;
6256 }
6257 mStartStopCond.wait(mLock);
6258 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006259 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 status = BAD_VALUE;
6261 goto startError;
6262 }
Steve Block3856b092011-10-20 11:56:00 +01006263 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 return status;
6265 }
6266startError:
6267 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006268 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 return status;
6270}
6271
Eric Laurenta011e352012-03-29 15:51:43 -07006272void AudioFlinger::RecordThread::clearSyncStartEvent()
6273{
6274 if (mSyncStartEvent != 0) {
6275 mSyncStartEvent->cancel();
6276 }
6277 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006278 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006279}
6280
6281void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6282{
6283 sp<SyncEvent> strongEvent = event.promote();
6284
6285 if (strongEvent != 0) {
6286 RecordThread *me = (RecordThread *)strongEvent->cookie();
6287 me->handleSyncStartEvent(strongEvent);
6288 }
6289}
6290
6291void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6292{
Eric Laurent29864602012-05-08 18:57:51 -07006293 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006294 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6295 // from audio HAL
6296 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006297 }
6298}
6299
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006301 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006302 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006304 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6306 mActiveTrack->mState = TrackBase::PAUSING;
6307 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006308 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 return;
6310 }
6311 mStartStopCond.wait(mLock);
6312 // if we have been restarted, recordTrack == mActiveTrack.get() here
6313 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6314 mLock.unlock();
6315 AudioSystem::stopInput(mId);
6316 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006317 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 }
6319 }
6320 }
6321}
6322
Eric Laurenta011e352012-03-29 15:51:43 -07006323bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6324{
6325 return false;
6326}
6327
6328status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6329{
6330 if (!isValidSyncEvent(event)) {
6331 return BAD_VALUE;
6332 }
6333
6334 Mutex::Autolock _l(mLock);
6335
6336 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6337 mTrack->setSyncEvent(event);
6338 return NO_ERROR;
6339 }
6340 return NAME_NOT_FOUND;
6341}
6342
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6344{
6345 const size_t SIZE = 256;
6346 char buffer[SIZE];
6347 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348
6349 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6350 result.append(buffer);
6351
6352 if (mActiveTrack != 0) {
6353 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006354 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 mActiveTrack->dump(buffer, SIZE);
6356 result.append(buffer);
6357
6358 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6359 result.append(buffer);
6360 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6361 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006362 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 result.append(buffer);
6364 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6365 result.append(buffer);
6366 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6367 result.append(buffer);
6368
6369
6370 } else {
6371 result.append("No record client\n");
6372 }
6373 write(fd, result.string(), result.size());
6374
6375 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006376 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377
6378 return NO_ERROR;
6379}
6380
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006381// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006382status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383{
6384 size_t framesReq = buffer->frameCount;
6385 size_t framesReady = mFrameCount - mRsmpInIndex;
6386 int channelCount;
6387
6388 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006389 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006391 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6393 // Force input into standby so that it tries to
6394 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006395 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006396 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006398 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 buffer->frameCount = 0;
6400 return NOT_ENOUGH_DATA;
6401 }
6402 mRsmpInIndex = 0;
6403 framesReady = mFrameCount;
6404 }
6405
6406 if (framesReq > framesReady) {
6407 framesReq = framesReady;
6408 }
6409
6410 if (mChannelCount == 1 && mReqChannelCount == 2) {
6411 channelCount = 1;
6412 } else {
6413 channelCount = 2;
6414 }
6415 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6416 buffer->frameCount = framesReq;
6417 return NO_ERROR;
6418}
6419
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006420// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6422{
6423 mRsmpInIndex += buffer->frameCount;
6424 buffer->frameCount = 0;
6425}
6426
6427bool AudioFlinger::RecordThread::checkForNewParameters_l()
6428{
6429 bool reconfig = false;
6430
6431 while (!mNewParameters.isEmpty()) {
6432 status_t status = NO_ERROR;
6433 String8 keyValuePair = mNewParameters[0];
6434 AudioParameter param = AudioParameter(keyValuePair);
6435 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006436 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 int reqSamplingRate = mReqSampleRate;
6438 int reqChannelCount = mReqChannelCount;
6439
6440 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6441 reqSamplingRate = value;
6442 reconfig = true;
6443 }
6444 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006445 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 reconfig = true;
6447 }
6448 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006449 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 reconfig = true;
6451 }
6452 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6453 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006454 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455 // if frame count is changed after track creation
6456 if (mActiveTrack != 0) {
6457 status = INVALID_OPERATION;
6458 } else {
6459 reconfig = true;
6460 }
6461 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006462 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6463 // forward device change to effects that have requested to be
6464 // aware of attached audio device.
6465 for (size_t i = 0; i < mEffectChains.size(); i++) {
6466 mEffectChains[i]->setDevice_l(value);
6467 }
6468 // store input device and output device but do not forward output device to audio HAL.
6469 // Note that status is ignored by the caller for output device
6470 // (see AudioFlinger::setParameters()
Glenn Kasten94479fd2012-07-09 15:39:54 -07006471 uint32_t /*audio_devices_t*/ newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006472 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten01542f22012-07-02 12:46:15 -07006473 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006474 status = BAD_VALUE;
6475 } else {
Glenn Kasten01542f22012-07-02 12:46:15 -07006476 newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006477 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6478 if (mTrack != NULL) {
6479 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006480 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006481 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6482 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6483 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006484 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006485 newDevice |= value;
Glenn Kasten94479fd2012-07-09 15:39:54 -07006486 mDevice = (audio_devices_t) newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006489 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006491 mInput->stream->common.standby(&mInput->stream->common);
6492 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6493 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 }
6495 if (reconfig) {
6496 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006497 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006498 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006499 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006500 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6501 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 status = NO_ERROR;
6503 }
6504 if (status == NO_ERROR) {
6505 readInputParameters();
6506 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6507 }
6508 }
6509 }
6510
6511 mNewParameters.removeAt(0);
6512
6513 mParamStatus = status;
6514 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006515 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6516 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006517 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 }
6519 return reconfig;
6520}
6521
6522String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6523{
Dima Zavinfce7a472011-04-19 22:30:36 -07006524 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006525 String8 out_s8 = String8();
6526
6527 Mutex::Autolock _l(mLock);
6528 if (initCheck() != NO_ERROR) {
6529 return out_s8;
6530 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006531
Dima Zavin799a70e2011-04-18 16:57:27 -07006532 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006533 out_s8 = String8(s);
6534 free(s);
6535 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536}
6537
6538void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6539 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006540 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541
6542 switch (event) {
6543 case AudioSystem::INPUT_OPENED:
6544 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006545 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 desc.samplingRate = mSampleRate;
6547 desc.format = mFormat;
6548 desc.frameCount = mFrameCount;
6549 desc.latency = 0;
6550 param2 = &desc;
6551 break;
6552
6553 case AudioSystem::INPUT_CLOSED:
6554 default:
6555 break;
6556 }
6557 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6558}
6559
6560void AudioFlinger::RecordThread::readInputParameters()
6561{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006562 delete mRsmpInBuffer;
6563 // mRsmpInBuffer is always assigned a new[] below
6564 delete mRsmpOutBuffer;
6565 mRsmpOutBuffer = NULL;
6566 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006567 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568
Dima Zavin799a70e2011-04-18 16:57:27 -07006569 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006570 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6571 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006572 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006573 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006574 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006576 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6578
Glenn Kasten53d76db2012-03-08 12:32:47 -08006579 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 {
6581 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006582 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6583 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 if (mChannelCount == 1 && mReqChannelCount == 2) {
6585 channelCount = 1;
6586 } else {
6587 channelCount = 2;
6588 }
6589 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6590 mResampler->setSampleRate(mSampleRate);
6591 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6592 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6593
6594 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6595 if (mChannelCount == 1 && mReqChannelCount == 1) {
6596 mFrameCount >>= 1;
6597 }
6598
6599 }
6600 mRsmpInIndex = mFrameCount;
6601}
6602
6603unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6604{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006605 Mutex::Autolock _l(mLock);
6606 if (initCheck() != NO_ERROR) {
6607 return 0;
6608 }
6609
Dima Zavin799a70e2011-04-18 16:57:27 -07006610 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611}
6612
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006613uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6614{
6615 Mutex::Autolock _l(mLock);
6616 uint32_t result = 0;
6617 if (getEffectChain_l(sessionId) != 0) {
6618 result = EFFECT_SESSION;
6619 }
6620
6621 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6622 result |= TRACK_SESSION;
6623 }
6624
6625 return result;
6626}
6627
Eric Laurent59bd0da2011-08-01 09:52:20 -07006628AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6629{
6630 Mutex::Autolock _l(mLock);
6631 return mTrack;
6632}
6633
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006634AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6635{
6636 Mutex::Autolock _l(mLock);
6637 AudioStreamIn *input = mInput;
6638 mInput = NULL;
6639 return input;
6640}
6641
6642// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006643audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006644{
6645 if (mInput == NULL) {
6646 return NULL;
6647 }
6648 return &mInput->stream->common;
6649}
6650
6651
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652// ----------------------------------------------------------------------------
6653
Eric Laurenta4c5a552012-03-29 10:12:40 -07006654audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6655{
6656 if (!settingsAllowed()) {
6657 return 0;
6658 }
6659 Mutex::Autolock _l(mLock);
6660 return loadHwModule_l(name);
6661}
6662
6663// loadHwModule_l() must be called with AudioFlinger::mLock held
6664audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6665{
6666 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6667 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6668 ALOGW("loadHwModule() module %s already loaded", name);
6669 return mAudioHwDevs.keyAt(i);
6670 }
6671 }
6672
Eric Laurenta4c5a552012-03-29 10:12:40 -07006673 audio_hw_device_t *dev;
6674
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006675 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006676 if (rc) {
6677 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6678 return 0;
6679 }
6680
6681 mHardwareStatus = AUDIO_HW_INIT;
6682 rc = dev->init_check(dev);
6683 mHardwareStatus = AUDIO_HW_IDLE;
6684 if (rc) {
6685 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6686 return 0;
6687 }
6688
6689 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6690 (NULL != dev->set_master_volume)) {
6691 AutoMutex lock(mHardwareLock);
6692 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6693 dev->set_master_volume(dev, mMasterVolume);
6694 mHardwareStatus = AUDIO_HW_IDLE;
6695 }
6696
6697 audio_module_handle_t handle = nextUniqueId();
6698 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6699
6700 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006701 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006702
6703 return handle;
6704
6705}
6706
6707audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6708 audio_devices_t *pDevices,
6709 uint32_t *pSamplingRate,
6710 audio_format_t *pFormat,
6711 audio_channel_mask_t *pChannelMask,
6712 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006713 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714{
6715 status_t status;
6716 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006717 struct audio_config config = {
6718 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6719 channel_mask: pChannelMask ? *pChannelMask : 0,
6720 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6721 };
6722 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006723 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724
Eric Laurenta4c5a552012-03-29 10:12:40 -07006725 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6726 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006727 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006728 config.sample_rate,
6729 config.format,
6730 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006731 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732
6733 if (pDevices == NULL || *pDevices == 0) {
6734 return 0;
6735 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006736
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737 Mutex::Autolock _l(mLock);
6738
Eric Laurenta4c5a552012-03-29 10:12:40 -07006739 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006740 if (outHwDev == NULL)
6741 return 0;
6742
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006743 audio_io_handle_t id = nextUniqueId();
6744
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006745 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006746
6747 status = outHwDev->open_output_stream(outHwDev,
6748 id,
6749 *pDevices,
6750 (audio_output_flags_t)flags,
6751 &config,
6752 &outStream);
6753
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006754 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006755 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006756 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006757 config.sample_rate,
6758 config.format,
6759 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 status);
6761
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006762 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006763 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006764
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006765 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006766 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6767 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006769 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 } else {
6771 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006772 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 }
6774 mPlaybackThreads.add(id, thread);
6775
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006776 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6777 if (pFormat != NULL) *pFormat = config.format;
6778 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006779 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780
6781 // notify client processes of the new output creation
6782 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006783
6784 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006785 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006786 ALOGI("Using module %d has the primary audio interface", module);
6787 mPrimaryHardwareDev = outHwDev;
6788
6789 AutoMutex lock(mHardwareLock);
6790 mHardwareStatus = AUDIO_HW_SET_MODE;
6791 outHwDev->set_mode(outHwDev, mMode);
6792
6793 // Determine the level of master volume support the primary audio HAL has,
6794 // and set the initial master volume at the same time.
6795 float initialVolume = 1.0;
6796 mMasterVolumeSupportLvl = MVS_NONE;
6797
6798 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6799 if ((NULL != outHwDev->get_master_volume) &&
6800 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6801 mMasterVolumeSupportLvl = MVS_FULL;
6802 } else {
6803 mMasterVolumeSupportLvl = MVS_SETONLY;
6804 initialVolume = 1.0;
6805 }
6806
6807 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6808 if ((NULL == outHwDev->set_master_volume) ||
6809 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6810 mMasterVolumeSupportLvl = MVS_NONE;
6811 }
6812 // now that we have a primary device, initialize master volume on other devices
6813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6814 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6815
6816 if ((dev != mPrimaryHardwareDev) &&
6817 (NULL != dev->set_master_volume)) {
6818 dev->set_master_volume(dev, initialVolume);
6819 }
6820 }
6821 mHardwareStatus = AUDIO_HW_IDLE;
6822 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6823 ? initialVolume
6824 : 1.0;
6825 mMasterVolume = initialVolume;
6826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 return id;
6828 }
6829
6830 return 0;
6831}
6832
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006833audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6834 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835{
6836 Mutex::Autolock _l(mLock);
6837 MixerThread *thread1 = checkMixerThread_l(output1);
6838 MixerThread *thread2 = checkMixerThread_l(output2);
6839
6840 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006841 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 return 0;
6843 }
6844
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006845 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6847 thread->addOutputTrack(thread2);
6848 mPlaybackThreads.add(id, thread);
6849 // notify client processes of the new output creation
6850 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6851 return id;
6852}
6853
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006854status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855{
Glenn Kastend96c5722012-04-25 13:44:49 -07006856 return closeOutput_nonvirtual(output);
6857}
6858
6859status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6860{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 // keep strong reference on the playback thread so that
6862 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006863 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864 {
6865 Mutex::Autolock _l(mLock);
6866 thread = checkPlaybackThread_l(output);
6867 if (thread == NULL) {
6868 return BAD_VALUE;
6869 }
6870
Steve Block3856b092011-10-20 11:56:00 +01006871 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006873 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006875 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6877 dupThread->removeOutputTrack((MixerThread *)thread.get());
6878 }
6879 }
6880 }
Glenn Kastena1117922012-01-26 10:53:32 -08006881 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 mPlaybackThreads.removeItem(output);
6883 }
6884 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006885 // The thread entity (active unit of execution) is no longer running here,
6886 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006888 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006889 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006890 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006891 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006892 out->hwDev->close_output_stream(out->hwDev, out->stream);
6893 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 }
6895 return NO_ERROR;
6896}
6897
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006898status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899{
6900 Mutex::Autolock _l(mLock);
6901 PlaybackThread *thread = checkPlaybackThread_l(output);
6902
6903 if (thread == NULL) {
6904 return BAD_VALUE;
6905 }
6906
Steve Block3856b092011-10-20 11:56:00 +01006907 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 thread->suspend();
6909
6910 return NO_ERROR;
6911}
6912
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006913status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914{
6915 Mutex::Autolock _l(mLock);
6916 PlaybackThread *thread = checkPlaybackThread_l(output);
6917
6918 if (thread == NULL) {
6919 return BAD_VALUE;
6920 }
6921
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923
6924 thread->restore();
6925
6926 return NO_ERROR;
6927}
6928
Eric Laurenta4c5a552012-03-29 10:12:40 -07006929audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6930 audio_devices_t *pDevices,
6931 uint32_t *pSamplingRate,
6932 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006933 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934{
6935 status_t status;
6936 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006937 struct audio_config config = {
6938 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6939 channel_mask: pChannelMask ? *pChannelMask : 0,
6940 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6941 };
6942 uint32_t reqSamplingRate = config.sample_rate;
6943 audio_format_t reqFormat = config.format;
6944 audio_channel_mask_t reqChannels = config.channel_mask;
6945 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006946 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947
6948 if (pDevices == NULL || *pDevices == 0) {
6949 return 0;
6950 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006951
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 Mutex::Autolock _l(mLock);
6953
Eric Laurenta4c5a552012-03-29 10:12:40 -07006954 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006955 if (inHwDev == NULL)
6956 return 0;
6957
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006958 audio_io_handle_t id = nextUniqueId();
6959
6960 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006961 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006962 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006963 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006964 config.sample_rate,
6965 config.format,
6966 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 status);
6968
6969 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6970 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6971 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006972 if (status == BAD_VALUE &&
6973 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6974 (config.sample_rate <= 2 * reqSamplingRate) &&
6975 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07006976 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006977 inStream = NULL;
6978 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 }
6980
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006981 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006982 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6983
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006984 // Start record thread
6985 // RecorThread require both input and output device indication to forward to audio
6986 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006987 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006988 thread = new RecordThread(this,
6989 input,
6990 reqSamplingRate,
6991 reqChannels,
6992 id,
6993 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006995 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006996 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006997 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006998 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999
Dima Zavin799a70e2011-04-18 16:57:27 -07007000 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001
7002 // notify client processes of the new input creation
7003 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7004 return id;
7005 }
7006
7007 return 0;
7008}
7009
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007010status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011{
Glenn Kastend96c5722012-04-25 13:44:49 -07007012 return closeInput_nonvirtual(input);
7013}
7014
7015status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 // keep strong reference on the record thread so that
7018 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007019 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 {
7021 Mutex::Autolock _l(mLock);
7022 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007023 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 return BAD_VALUE;
7025 }
7026
Steve Block3856b092011-10-20 11:56:00 +01007027 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007028 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029 mRecordThreads.removeItem(input);
7030 }
7031 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007032 // The thread entity (active unit of execution) is no longer running here,
7033 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007035 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007036 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007037 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007038 in->hwDev->close_input_stream(in->hwDev, in->stream);
7039 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040
7041 return NO_ERROR;
7042}
7043
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007044status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045{
7046 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007047 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048
7049 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7050 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007051 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053
7054 return NO_ERROR;
7055}
7056
7057
7058int AudioFlinger::newAudioSessionId()
7059{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007060 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061}
7062
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007063void AudioFlinger::acquireAudioSessionId(int audioSession)
7064{
7065 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007066 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007067 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007068 size_t num = mAudioSessionRefs.size();
7069 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007070 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007071 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7072 ref->mCnt++;
7073 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007074 return;
7075 }
7076 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007077 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7078 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007079}
7080
7081void AudioFlinger::releaseAudioSessionId(int audioSession)
7082{
7083 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007084 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007085 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007086 size_t num = mAudioSessionRefs.size();
7087 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007088 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007089 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7090 ref->mCnt--;
7091 ALOGV(" decremented refcount to %d", ref->mCnt);
7092 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007093 mAudioSessionRefs.removeAt(i);
7094 delete ref;
7095 purgeStaleEffects_l();
7096 }
7097 return;
7098 }
7099 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007100 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007101}
7102
7103void AudioFlinger::purgeStaleEffects_l() {
7104
Steve Block3856b092011-10-20 11:56:00 +01007105 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007106
7107 Vector< sp<EffectChain> > chains;
7108
7109 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7110 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7111 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7112 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007113 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7114 chains.push(ec);
7115 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007116 }
7117 }
7118 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7119 sp<RecordThread> t = mRecordThreads.valueAt(i);
7120 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7121 sp<EffectChain> ec = t->mEffectChains[j];
7122 chains.push(ec);
7123 }
7124 }
7125
7126 for (size_t i = 0; i < chains.size(); i++) {
7127 sp<EffectChain> ec = chains[i];
7128 int sessionid = ec->sessionId();
7129 sp<ThreadBase> t = ec->mThread.promote();
7130 if (t == 0) {
7131 continue;
7132 }
7133 size_t numsessionrefs = mAudioSessionRefs.size();
7134 bool found = false;
7135 for (size_t k = 0; k < numsessionrefs; k++) {
7136 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007137 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007138 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007139 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007140 found = true;
7141 break;
7142 }
7143 }
7144 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007145 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007146 // remove all effects from the chain
7147 while (ec->mEffects.size()) {
7148 sp<EffectModule> effect = ec->mEffects[0];
7149 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007150 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007151 if (effect->purgeHandles()) {
7152 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007153 }
7154 AudioSystem::unregisterEffect(effect->id());
7155 }
7156 }
7157 }
7158 return;
7159}
7160
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007162AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
Glenn Kastena1117922012-01-26 10:53:32 -08007164 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165}
7166
7167// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007168AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169{
7170 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007171 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
7174// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007175AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176{
Glenn Kastena1117922012-01-26 10:53:32 -08007177 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178}
7179
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183}
7184
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007185AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007186{
7187 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7188 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007189 AudioStreamOut *output = thread->getOutput();
7190 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007191 return thread;
7192 }
7193 }
7194 return NULL;
7195}
7196
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007197audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007198{
7199 PlaybackThread *thread = primaryPlaybackThread_l();
7200
7201 if (thread == NULL) {
7202 return 0;
7203 }
7204
7205 return thread->device();
7206}
7207
Eric Laurenta011e352012-03-29 15:51:43 -07007208sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7209 int triggerSession,
7210 int listenerSession,
7211 sync_event_callback_t callBack,
7212 void *cookie)
7213{
7214 Mutex::Autolock _l(mLock);
7215
7216 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7217 status_t playStatus = NAME_NOT_FOUND;
7218 status_t recStatus = NAME_NOT_FOUND;
7219 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7220 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7221 if (playStatus == NO_ERROR) {
7222 return event;
7223 }
7224 }
7225 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7226 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7227 if (recStatus == NO_ERROR) {
7228 return event;
7229 }
7230 }
7231 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7232 mPendingSyncEvents.add(event);
7233 } else {
7234 ALOGV("createSyncEvent() invalid event %d", event->type());
7235 event.clear();
7236 }
7237 return event;
7238}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007239
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240// ----------------------------------------------------------------------------
7241// Effect management
7242// ----------------------------------------------------------------------------
7243
7244
Glenn Kastenf587ba52012-01-26 16:25:10 -08007245status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246{
7247 Mutex::Autolock _l(mLock);
7248 return EffectQueryNumberEffects(numEffects);
7249}
7250
Glenn Kastenf587ba52012-01-26 16:25:10 -08007251status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252{
7253 Mutex::Autolock _l(mLock);
7254 return EffectQueryEffect(index, descriptor);
7255}
7256
Glenn Kasten5e92a782012-01-30 07:40:52 -08007257status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007258 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259{
7260 Mutex::Autolock _l(mLock);
7261 return EffectGetDescriptor(pUuid, descriptor);
7262}
7263
7264
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7266 effect_descriptor_t *pDesc,
7267 const sp<IEffectClient>& effectClient,
7268 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007269 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270 int sessionId,
7271 status_t *status,
7272 int *id,
7273 int *enabled)
7274{
7275 status_t lStatus = NO_ERROR;
7276 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007279 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007280 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281
7282 if (pDesc == NULL) {
7283 lStatus = BAD_VALUE;
7284 goto Exit;
7285 }
7286
Eric Laurent84e9a102010-09-23 16:10:16 -07007287 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007288 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007289 lStatus = PERMISSION_DENIED;
7290 goto Exit;
7291 }
7292
Dima Zavinfce7a472011-04-19 22:30:36 -07007293 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007294 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007295 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007296 lStatus = PERMISSION_DENIED;
7297 goto Exit;
7298 }
7299
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007300 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007301 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007302 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007303 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007304 lStatus = BAD_VALUE;
7305 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007306 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007307 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007308 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007309 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007311 }
7312 }
7313
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 {
7315 Mutex::Autolock _l(mLock);
7316
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317
7318 if (!EffectIsNullUuid(&pDesc->uuid)) {
7319 // if uuid is specified, request effect descriptor
7320 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7321 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007322 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323 goto Exit;
7324 }
7325 } else {
7326 // if uuid is not specified, look for an available implementation
7327 // of the required type in effect factory
7328 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007329 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 lStatus = BAD_VALUE;
7331 goto Exit;
7332 }
7333 uint32_t numEffects = 0;
7334 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007335 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 bool found = false;
7337
7338 lStatus = EffectQueryNumberEffects(&numEffects);
7339 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007340 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 goto Exit;
7342 }
7343 for (uint32_t i = 0; i < numEffects; i++) {
7344 lStatus = EffectQueryEffect(i, &desc);
7345 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007346 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 continue;
7348 }
7349 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7350 // If matching type found save effect descriptor. If the session is
7351 // 0 and the effect is not auxiliary, continue enumeration in case
7352 // an auxiliary version of this effect type is available
7353 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007354 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007355 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7357 break;
7358 }
7359 }
7360 }
7361 if (!found) {
7362 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007363 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 goto Exit;
7365 }
7366 // For same effect type, chose auxiliary version over insert version if
7367 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007368 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007370 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371 }
7372 }
7373
7374 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007375 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7377 lStatus = INVALID_OPERATION;
7378 goto Exit;
7379 }
7380
Eric Laurent59255e42011-07-27 19:49:51 -07007381 // check recording permission for visualizer
7382 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7383 !recordingAllowed()) {
7384 lStatus = PERMISSION_DENIED;
7385 goto Exit;
7386 }
7387
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007389 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390
7391 // If output is not specified try to find a matching audio session ID in one of the
7392 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007393 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7394 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395 // Note: io is never 0 when creating an effect on an input
7396 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007397 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7399 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007401 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007404 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7406 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7407 io = mRecordThreads.keyAt(i);
7408 break;
7409 }
7410 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007411 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007412 // If no output thread contains the requested session ID, default to
7413 // first output. The effect chain will be moved to the correct output
7414 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415 if (io == 0 && mPlaybackThreads.size()) {
7416 io = mPlaybackThreads.keyAt(0);
7417 }
Steve Block3856b092011-10-20 11:56:00 +01007418 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 }
7420 ThreadBase *thread = checkRecordThread_l(io);
7421 if (thread == NULL) {
7422 thread = checkPlaybackThread_l(io);
7423 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007424 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007425 lStatus = BAD_VALUE;
7426 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007428 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007429
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007430 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007432 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007433 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7434 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435 if (handle != 0 && id != NULL) {
7436 *id = handle->id();
7437 }
7438 }
7439
7440Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007441 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 *status = lStatus;
7443 }
7444 return handle;
7445}
7446
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007447status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7448 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007449{
Steve Block3856b092011-10-20 11:56:00 +01007450 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007451 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007452 Mutex::Autolock _l(mLock);
7453 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007454 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007455 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 }
Eric Laurentde070132010-07-13 04:45:46 -07007457 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7458 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007459 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007460 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 }
Eric Laurentde070132010-07-13 04:45:46 -07007462 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7463 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007464 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007465 return BAD_VALUE;
7466 }
7467
7468 Mutex::Autolock _dl(dstThread->mLock);
7469 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007470 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007471
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472 return NO_ERROR;
7473}
7474
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007475// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007476status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007477 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007478 AudioFlinger::PlaybackThread *dstThread,
7479 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007480{
Steve Block3856b092011-10-20 11:56:00 +01007481 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007482 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007483
Eric Laurent59255e42011-07-27 19:49:51 -07007484 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007485 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007486 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007487 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007488 return INVALID_OPERATION;
7489 }
7490
Eric Laurent39e94f82010-07-28 01:32:47 -07007491 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007492 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007493 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007494 // removed.
7495 srcThread->removeEffectChain_l(chain);
7496
7497 // transfer all effects one by one so that new effect chain is created on new thread with
7498 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007499 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007500 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007501 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007502 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7503 while (effect != 0) {
7504 srcThread->removeEffect_l(effect);
7505 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007506 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7507 if (effect->state() == EffectModule::ACTIVE ||
7508 effect->state() == EffectModule::STOPPING) {
7509 effect->start();
7510 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007511 // if the move request is not received from audio policy manager, the effect must be
7512 // re-registered with the new strategy and output
7513 if (dstChain == 0) {
7514 dstChain = effect->chain().promote();
7515 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007516 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007517 srcThread->addEffect_l(effect);
7518 return NO_INIT;
7519 }
7520 strategy = dstChain->strategy();
7521 }
7522 if (reRegister) {
7523 AudioSystem::unregisterEffect(effect->id());
7524 AudioSystem::registerEffect(&effect->desc(),
7525 dstOutput,
7526 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007527 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007528 effect->id());
7529 }
Eric Laurentde070132010-07-13 04:45:46 -07007530 effect = chain->getEffectFromId_l(0);
7531 }
7532
7533 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534}
7535
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007538sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 const sp<AudioFlinger::Client>& client,
7540 const sp<IEffectClient>& effectClient,
7541 int32_t priority,
7542 int sessionId,
7543 effect_descriptor_t *desc,
7544 int *enabled,
7545 status_t *status
7546 )
7547{
7548 sp<EffectModule> effect;
7549 sp<EffectHandle> handle;
7550 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007552 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 bool effectCreated = false;
7554 bool effectRegistered = false;
7555
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007556 lStatus = initCheck();
7557 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007558 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559 goto Exit;
7560 }
7561
7562 // Do not allow effects with session ID 0 on direct output or duplicating threads
7563 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007564 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007565 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007566 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 lStatus = BAD_VALUE;
7568 goto Exit;
7569 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007570 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007571 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007572 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007573 desc->name, desc->flags, mType);
7574 lStatus = BAD_VALUE;
7575 goto Exit;
7576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577
Steve Block3856b092011-10-20 11:56:00 +01007578 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007579
7580 { // scope for mLock
7581 Mutex::Autolock _l(mLock);
7582
7583 // check for existing effect chain with the requested audio session
7584 chain = getEffectChain_l(sessionId);
7585 if (chain == 0) {
7586 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007587 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 chain = new EffectChain(this, sessionId);
7589 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007590 chain->setStrategy(getStrategyForSession_l(sessionId));
7591 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007593 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 }
7595
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007596 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597
7598 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007599 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007601 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 if (lStatus != NO_ERROR) {
7603 goto Exit;
7604 }
7605 effectRegistered = true;
7606 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007607 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 lStatus = effect->status();
7609 if (lStatus != NO_ERROR) {
7610 goto Exit;
7611 }
Eric Laurentcab11242010-07-15 12:50:15 -07007612 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 if (lStatus != NO_ERROR) {
7614 goto Exit;
7615 }
7616 effectCreated = true;
7617
7618 effect->setDevice(mDevice);
7619 effect->setMode(mAudioFlinger->getMode());
7620 }
7621 // create effect handle and connect it to effect module
7622 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007623 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007624 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625 *enabled = (int)effect->isEnabled();
7626 }
7627 }
7628
7629Exit:
7630 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007631 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007633 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 }
7635 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007636 AudioSystem::unregisterEffect(effect->id());
7637 }
7638 if (chainCreated) {
7639 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 }
7641 handle.clear();
7642 }
7643
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007644 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 *status = lStatus;
7646 }
7647 return handle;
7648}
7649
Eric Laurent717e1282012-06-29 16:36:52 -07007650sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7651{
7652 Mutex::Autolock _l(mLock);
7653 return getEffect_l(sessionId, effectId);
7654}
7655
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007656sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7657{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007658 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007659 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007660}
7661
Eric Laurentde070132010-07-13 04:45:46 -07007662// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7663// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007664status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007665{
7666 // check for existing effect chain with the requested audio session
7667 int sessionId = effect->sessionId();
7668 sp<EffectChain> chain = getEffectChain_l(sessionId);
7669 bool chainCreated = false;
7670
7671 if (chain == 0) {
7672 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007674 chain = new EffectChain(this, sessionId);
7675 addEffectChain_l(chain);
7676 chain->setStrategy(getStrategyForSession_l(sessionId));
7677 chainCreated = true;
7678 }
Steve Block3856b092011-10-20 11:56:00 +01007679 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007680
7681 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007682 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007683 this, effect->desc().name, chain.get());
7684 return BAD_VALUE;
7685 }
7686
7687 status_t status = chain->addEffect_l(effect);
7688 if (status != NO_ERROR) {
7689 if (chainCreated) {
7690 removeEffectChain_l(chain);
7691 }
7692 return status;
7693 }
7694
7695 effect->setDevice(mDevice);
7696 effect->setMode(mAudioFlinger->getMode());
7697 return NO_ERROR;
7698}
7699
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007700void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007701
Steve Block3856b092011-10-20 11:56:00 +01007702 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007704 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7705 detachAuxEffect_l(effect->id());
7706 }
7707
7708 sp<EffectChain> chain = effect->chain().promote();
7709 if (chain != 0) {
7710 // remove effect chain if removing last effect
7711 if (chain->removeEffect_l(effect) == 0) {
7712 removeEffectChain_l(chain);
7713 }
7714 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007715 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007716 }
7717}
7718
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007720 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007721{
7722 effectChains = mEffectChains;
7723 for (size_t i = 0; i < mEffectChains.size(); i++) {
7724 mEffectChains[i]->lock();
7725 }
7726}
7727
7728void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007729 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007730{
7731 for (size_t i = 0; i < effectChains.size(); i++) {
7732 effectChains[i]->unlock();
7733 }
7734}
7735
7736sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7737{
7738 Mutex::Autolock _l(mLock);
7739 return getEffectChain_l(sessionId);
7740}
7741
7742sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7743{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007744 size_t size = mEffectChains.size();
7745 for (size_t i = 0; i < size; i++) {
7746 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007747 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007748 }
7749 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007750 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007751}
7752
Glenn Kastenf78aee72012-01-04 11:00:47 -08007753void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007754{
7755 Mutex::Autolock _l(mLock);
7756 size_t size = mEffectChains.size();
7757 for (size_t i = 0; i < size; i++) {
7758 mEffectChains[i]->setMode_l(mode);
7759 }
7760}
7761
7762void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007763 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007764 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007765
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007767 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 // delete the effect module if removing last handle on it
7769 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007770 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007771 removeEffect_l(effect);
7772 AudioSystem::unregisterEffect(effect->id());
7773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 }
7775}
7776
7777status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7778{
7779 int session = chain->sessionId();
7780 int16_t *buffer = mMixBuffer;
7781 bool ownsBuffer = false;
7782
Steve Block3856b092011-10-20 11:56:00 +01007783 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 if (session > 0) {
7785 // Only one effect chain can be present in direct output thread and it uses
7786 // the mix buffer as input
7787 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007788 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 buffer = new int16_t[numSamples];
7790 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007791 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 ownsBuffer = true;
7793 }
7794
7795 // Attach all tracks with same session ID to this chain.
7796 for (size_t i = 0; i < mTracks.size(); ++i) {
7797 sp<Track> track = mTracks[i];
7798 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007799 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007801 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 }
7803 }
7804
7805 // indicate all active tracks in the chain
7806 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7807 sp<Track> track = mActiveTracks[i].promote();
7808 if (track == 0) continue;
7809 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007810 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007811 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 }
7813 }
7814 }
7815
7816 chain->setInBuffer(buffer, ownsBuffer);
7817 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007818 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007819 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007820 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7821 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007823 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7824 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007825 // Effect chain for other sessions are inserted at beginning of effect
7826 // chains list to be processed before output mix effects. Relative order between other
7827 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 size_t size = mEffectChains.size();
7829 size_t i = 0;
7830 for (i = 0; i < size; i++) {
7831 if (mEffectChains[i]->sessionId() < session) break;
7832 }
7833 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007834 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007835
7836 return NO_ERROR;
7837}
7838
7839size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7840{
7841 int session = chain->sessionId();
7842
Steve Block3856b092011-10-20 11:56:00 +01007843 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844
7845 for (size_t i = 0; i < mEffectChains.size(); i++) {
7846 if (chain == mEffectChains[i]) {
7847 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007848 // detach all active tracks from the chain
7849 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7850 sp<Track> track = mActiveTracks[i].promote();
7851 if (track == 0) continue;
7852 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007853 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007854 chain.get(), session);
7855 chain->decActiveTrackCnt();
7856 }
7857 }
7858
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859 // detach all tracks with same session ID from this chain
7860 for (size_t i = 0; i < mTracks.size(); ++i) {
7861 sp<Track> track = mTracks[i];
7862 if (session == track->sessionId()) {
7863 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007864 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 }
7866 }
Eric Laurentde070132010-07-13 04:45:46 -07007867 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868 }
7869 }
7870 return mEffectChains.size();
7871}
7872
Eric Laurentde070132010-07-13 04:45:46 -07007873status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7874 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875{
7876 Mutex::Autolock _l(mLock);
7877 return attachAuxEffect_l(track, EffectId);
7878}
7879
Eric Laurentde070132010-07-13 04:45:46 -07007880status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7881 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882{
7883 status_t status = NO_ERROR;
7884
7885 if (EffectId == 0) {
7886 track->setAuxBuffer(0, NULL);
7887 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007888 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7889 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007890 if (effect != 0) {
7891 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7892 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7893 } else {
7894 status = INVALID_OPERATION;
7895 }
7896 } else {
7897 status = BAD_VALUE;
7898 }
7899 }
7900 return status;
7901}
7902
7903void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7904{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007905 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 sp<Track> track = mTracks[i];
7907 if (track->auxEffectId() == effectId) {
7908 attachAuxEffect_l(track, 0);
7909 }
7910 }
7911}
7912
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007913status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7914{
7915 // only one chain per input thread
7916 if (mEffectChains.size() != 0) {
7917 return INVALID_OPERATION;
7918 }
Steve Block3856b092011-10-20 11:56:00 +01007919 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007920
7921 chain->setInBuffer(NULL);
7922 chain->setOutBuffer(NULL);
7923
Eric Laurent59255e42011-07-27 19:49:51 -07007924 checkSuspendOnAddEffectChain_l(chain);
7925
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007926 mEffectChains.add(chain);
7927
7928 return NO_ERROR;
7929}
7930
7931size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7932{
Steve Block3856b092011-10-20 11:56:00 +01007933 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007934 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007935 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7936 chain.get(), mEffectChains.size(), this);
7937 if (mEffectChains.size() == 1) {
7938 mEffectChains.removeAt(0);
7939 }
7940 return 0;
7941}
7942
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943// ----------------------------------------------------------------------------
7944// EffectModule implementation
7945// ----------------------------------------------------------------------------
7946
7947#undef LOG_TAG
7948#define LOG_TAG "AudioFlinger::EffectModule"
7949
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007950AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 const wp<AudioFlinger::EffectChain>& chain,
7952 effect_descriptor_t *desc,
7953 int id,
7954 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007955 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7956 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7957 // mDescriptor is set below
7958 // mConfig is set by configure() and not used before then
7959 mEffectInterface(NULL),
7960 mStatus(NO_INIT), mState(IDLE),
7961 // mMaxDisableWaitCnt is set by configure() and not used before then
7962 // mDisableWaitCnt is set by process() and updateState() and not used before then
7963 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964{
Steve Block3856b092011-10-20 11:56:00 +01007965 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007966 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007967 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968 return;
7969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970
7971 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7972
7973 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007974 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975
7976 if (mStatus != NO_ERROR) {
7977 return;
7978 }
7979 lStatus = init();
7980 if (lStatus < 0) {
7981 mStatus = lStatus;
7982 goto Error;
7983 }
7984
Steve Block3856b092011-10-20 11:56:00 +01007985 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986 return;
7987Error:
7988 EffectRelease(mEffectInterface);
7989 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007990 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991}
7992
7993AudioFlinger::EffectModule::~EffectModule()
7994{
Steve Block3856b092011-10-20 11:56:00 +01007995 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007997 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7998 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7999 sp<ThreadBase> thread = mThread.promote();
8000 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008001 audio_stream_t *stream = thread->stream();
8002 if (stream != NULL) {
8003 stream->remove_audio_effect(stream, mEffectInterface);
8004 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008005 }
8006 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 // release effect engine
8008 EffectRelease(mEffectInterface);
8009 }
8010}
8011
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008012status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013{
8014 status_t status;
8015
8016 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017 int priority = handle->priority();
8018 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008019 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008020 size_t i;
8021 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008022 EffectHandle *h = mHandles[i];
8023 if (h == NULL || h->destroyed_l()) continue;
8024 // first non destroyed handle is considered in control
8025 if (controlHandle == NULL)
8026 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 if (h->priority() <= priority) break;
8028 }
8029 // if inserted in first place, move effect control from previous owner to this handle
8030 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008031 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008032 if (controlHandle != NULL) {
8033 enabled = controlHandle->enabled();
8034 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 }
Eric Laurent59255e42011-07-27 19:49:51 -07008036 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 status = NO_ERROR;
8038 } else {
8039 status = ALREADY_EXISTS;
8040 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008041 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 mHandles.insertAt(handle, i);
8043 return status;
8044}
8045
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008046size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047{
8048 Mutex::Autolock _l(mLock);
8049 size_t size = mHandles.size();
8050 size_t i;
8051 for (i = 0; i < size; i++) {
8052 if (mHandles[i] == handle) break;
8053 }
8054 if (i == size) {
8055 return size;
8056 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008057 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008058
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008061 if (i == 0) {
8062 EffectHandle *h = controlHandle_l();
8063 if (h != NULL) {
8064 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 }
8066 }
8067
Eric Laurentec437d82011-07-26 20:54:46 -07008068 // Prevent calls to process() and other functions on effect interface from now on.
8069 // The effect engine will be released by the destructor when the last strong reference on
8070 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008071 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008072 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008073 }
8074
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 return size;
8076}
8077
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008078// must be called with EffectModule::mLock held
8079AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008080{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008081 // the first valid handle in the list has control over the module
8082 for (size_t i = 0; i < mHandles.size(); i++) {
8083 EffectHandle *h = mHandles[i];
8084 if (h != NULL && !h->destroyed_l()) {
8085 return h;
8086 }
8087 }
8088
8089 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008090}
8091
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008092size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008094 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095 // keep a strong reference on this EffectModule to avoid calling the
8096 // destructor before we exit
8097 sp<EffectModule> keep(this);
8098 {
8099 sp<ThreadBase> thread = mThread.promote();
8100 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008101 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102 }
8103 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008104 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105}
8106
8107void AudioFlinger::EffectModule::updateState() {
8108 Mutex::Autolock _l(mLock);
8109
8110 switch (mState) {
8111 case RESTART:
8112 reset_l();
8113 // FALL THROUGH
8114
8115 case STARTING:
8116 // clear auxiliary effect input buffer for next accumulation
8117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8118 memset(mConfig.inputCfg.buffer.raw,
8119 0,
8120 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8121 }
8122 start_l();
8123 mState = ACTIVE;
8124 break;
8125 case STOPPING:
8126 stop_l();
8127 mDisableWaitCnt = mMaxDisableWaitCnt;
8128 mState = STOPPED;
8129 break;
8130 case STOPPED:
8131 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8132 // turn off sequence.
8133 if (--mDisableWaitCnt == 0) {
8134 reset_l();
8135 mState = IDLE;
8136 }
8137 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008138 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139 break;
8140 }
8141}
8142
8143void AudioFlinger::EffectModule::process()
8144{
8145 Mutex::Autolock _l(mLock);
8146
Eric Laurentec437d82011-07-26 20:54:46 -07008147 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148 mConfig.inputCfg.buffer.raw == NULL ||
8149 mConfig.outputCfg.buffer.raw == NULL) {
8150 return;
8151 }
8152
Eric Laurent8f45bd72010-08-31 13:50:07 -07008153 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8155 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008156 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008157 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008158 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 }
8160
8161 // do the actual processing in the effect engine
8162 int ret = (*mEffectInterface)->process(mEffectInterface,
8163 &mConfig.inputCfg.buffer,
8164 &mConfig.outputCfg.buffer);
8165
8166 // force transition to IDLE state when engine is ready
8167 if (mState == STOPPED && ret == -ENODATA) {
8168 mDisableWaitCnt = 1;
8169 }
8170
8171 // clear auxiliary effect input buffer for next accumulation
8172 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008173 memset(mConfig.inputCfg.buffer.raw, 0,
8174 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008175 }
8176 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008177 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8178 // If an insert effect is idle and input buffer is different from output buffer,
8179 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008181 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008182 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8183 int16_t *in = mConfig.inputCfg.buffer.s16;
8184 int16_t *out = mConfig.outputCfg.buffer.s16;
8185 for (size_t i = 0; i < frameCnt; i++) {
8186 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188 }
8189 }
8190}
8191
8192void AudioFlinger::EffectModule::reset_l()
8193{
8194 if (mEffectInterface == NULL) {
8195 return;
8196 }
8197 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8198}
8199
8200status_t AudioFlinger::EffectModule::configure()
8201{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202 if (mEffectInterface == NULL) {
8203 return NO_INIT;
8204 }
8205
8206 sp<ThreadBase> thread = mThread.promote();
8207 if (thread == 0) {
8208 return DEAD_OBJECT;
8209 }
8210
8211 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008212 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213
8214 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008215 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008216 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008217 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 }
Glenn Kasten254af182012-07-03 14:59:05 -07008219 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008220 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8221 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008222 mConfig.inputCfg.samplingRate = thread->sampleRate();
8223 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8224 mConfig.inputCfg.bufferProvider.cookie = NULL;
8225 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8226 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8227 mConfig.outputCfg.bufferProvider.cookie = NULL;
8228 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8229 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8230 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8231 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008232 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008233 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008234 // - in other sessions:
8235 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8236 // other effect: overwrites output buffer: input buffer == output buffer
8237 // Auxiliary effect:
8238 // accumulates in output buffer: input buffer != output buffer
8239 // Therefore: accumulate <=> input buffer != output buffer
8240 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8241 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8242 } else {
8243 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8244 }
8245 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8246 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8247 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8248 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8249
Steve Block3856b092011-10-20 11:56:00 +01008250 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008251 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8252
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008254 uint32_t size = sizeof(int);
8255 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008256 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008257 sizeof(effect_config_t),
8258 &mConfig,
8259 &size,
8260 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008261 if (status == 0) {
8262 status = cmdStatus;
8263 }
8264
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008265 if (status == 0 &&
8266 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8267 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8268 effect_param_t *p = (effect_param_t *)buf32;
8269
8270 p->psize = sizeof(uint32_t);
8271 p->vsize = sizeof(uint32_t);
8272 size = sizeof(int);
8273 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8274
8275 uint32_t latency = 0;
8276 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8277 if (pbt != NULL) {
8278 latency = pbt->latency_l();
8279 }
8280
8281 *((int32_t *)p->data + 1)= latency;
8282 (*mEffectInterface)->command(mEffectInterface,
8283 EFFECT_CMD_SET_PARAM,
8284 sizeof(effect_param_t) + 8,
8285 &buf32,
8286 &size,
8287 &cmdStatus);
8288 }
8289
Mathias Agopian65ab4712010-07-14 17:59:35 -07008290 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8291 (1000 * mConfig.outputCfg.buffer.frameCount);
8292
8293 return status;
8294}
8295
8296status_t AudioFlinger::EffectModule::init()
8297{
8298 Mutex::Autolock _l(mLock);
8299 if (mEffectInterface == NULL) {
8300 return NO_INIT;
8301 }
8302 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008303 uint32_t size = sizeof(status_t);
8304 status_t status = (*mEffectInterface)->command(mEffectInterface,
8305 EFFECT_CMD_INIT,
8306 0,
8307 NULL,
8308 &size,
8309 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310 if (status == 0) {
8311 status = cmdStatus;
8312 }
8313 return status;
8314}
8315
Eric Laurentec35a142011-10-05 17:42:25 -07008316status_t AudioFlinger::EffectModule::start()
8317{
8318 Mutex::Autolock _l(mLock);
8319 return start_l();
8320}
8321
Mathias Agopian65ab4712010-07-14 17:59:35 -07008322status_t AudioFlinger::EffectModule::start_l()
8323{
8324 if (mEffectInterface == NULL) {
8325 return NO_INIT;
8326 }
8327 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008328 uint32_t size = sizeof(status_t);
8329 status_t status = (*mEffectInterface)->command(mEffectInterface,
8330 EFFECT_CMD_ENABLE,
8331 0,
8332 NULL,
8333 &size,
8334 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335 if (status == 0) {
8336 status = cmdStatus;
8337 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008338 if (status == 0 &&
8339 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8340 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8341 sp<ThreadBase> thread = mThread.promote();
8342 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008343 audio_stream_t *stream = thread->stream();
8344 if (stream != NULL) {
8345 stream->add_audio_effect(stream, mEffectInterface);
8346 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008347 }
8348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008349 return status;
8350}
8351
Eric Laurentec437d82011-07-26 20:54:46 -07008352status_t AudioFlinger::EffectModule::stop()
8353{
8354 Mutex::Autolock _l(mLock);
8355 return stop_l();
8356}
8357
Mathias Agopian65ab4712010-07-14 17:59:35 -07008358status_t AudioFlinger::EffectModule::stop_l()
8359{
8360 if (mEffectInterface == NULL) {
8361 return NO_INIT;
8362 }
8363 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008364 uint32_t size = sizeof(status_t);
8365 status_t status = (*mEffectInterface)->command(mEffectInterface,
8366 EFFECT_CMD_DISABLE,
8367 0,
8368 NULL,
8369 &size,
8370 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371 if (status == 0) {
8372 status = cmdStatus;
8373 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008374 if (status == 0 &&
8375 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8376 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8377 sp<ThreadBase> thread = mThread.promote();
8378 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008379 audio_stream_t *stream = thread->stream();
8380 if (stream != NULL) {
8381 stream->remove_audio_effect(stream, mEffectInterface);
8382 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008383 }
8384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008385 return status;
8386}
8387
Eric Laurent25f43952010-07-28 05:40:18 -07008388status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8389 uint32_t cmdSize,
8390 void *pCmdData,
8391 uint32_t *replySize,
8392 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008393{
8394 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008395// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396
Eric Laurentec437d82011-07-26 20:54:46 -07008397 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008398 return NO_INIT;
8399 }
Eric Laurent25f43952010-07-28 05:40:18 -07008400 status_t status = (*mEffectInterface)->command(mEffectInterface,
8401 cmdCode,
8402 cmdSize,
8403 pCmdData,
8404 replySize,
8405 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008406 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008407 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008408 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008409 EffectHandle *h = mHandles[i];
8410 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8412 }
8413 }
8414 }
8415 return status;
8416}
8417
8418status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8419{
8420 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008421 return setEnabled_l(enabled);
8422}
8423
8424// must be called with EffectModule::mLock held
8425status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8426{
8427
Steve Block3856b092011-10-20 11:56:00 +01008428 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429
8430 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008431 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8432 if (enabled && status != NO_ERROR) {
8433 return status;
8434 }
8435
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 switch (mState) {
8437 // going from disabled to enabled
8438 case IDLE:
8439 mState = STARTING;
8440 break;
8441 case STOPPED:
8442 mState = RESTART;
8443 break;
8444 case STOPPING:
8445 mState = ACTIVE;
8446 break;
8447
8448 // going from enabled to disabled
8449 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008450 mState = STOPPED;
8451 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 case STARTING:
8453 mState = IDLE;
8454 break;
8455 case ACTIVE:
8456 mState = STOPPING;
8457 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008458 case DESTROYED:
8459 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008460 }
8461 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008462 EffectHandle *h = mHandles[i];
8463 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464 h->setEnabled(enabled);
8465 }
8466 }
8467 }
8468 return NO_ERROR;
8469}
8470
Glenn Kastenc59c0042012-02-02 14:06:11 -08008471bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008472{
8473 switch (mState) {
8474 case RESTART:
8475 case STARTING:
8476 case ACTIVE:
8477 return true;
8478 case IDLE:
8479 case STOPPING:
8480 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008481 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008482 default:
8483 return false;
8484 }
8485}
8486
Glenn Kastenc59c0042012-02-02 14:06:11 -08008487bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008488{
8489 switch (mState) {
8490 case RESTART:
8491 case ACTIVE:
8492 case STOPPING:
8493 case STOPPED:
8494 return true;
8495 case IDLE:
8496 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008497 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008498 default:
8499 return false;
8500 }
8501}
8502
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8504{
8505 Mutex::Autolock _l(mLock);
8506 status_t status = NO_ERROR;
8507
8508 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8509 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008510 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008511 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8512 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 status_t cmdStatus;
8514 uint32_t volume[2];
8515 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008516 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008517 volume[0] = *left;
8518 volume[1] = *right;
8519 if (controller) {
8520 pVolume = volume;
8521 }
Eric Laurent25f43952010-07-28 05:40:18 -07008522 status = (*mEffectInterface)->command(mEffectInterface,
8523 EFFECT_CMD_SET_VOLUME,
8524 size,
8525 volume,
8526 &size,
8527 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8529 *left = volume[0];
8530 *right = volume[1];
8531 }
8532 }
8533 return status;
8534}
8535
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008536status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008537{
8538 Mutex::Autolock _l(mLock);
8539 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008540 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8541 // audio pre processing modules on RecordThread can receive both output and
8542 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008543 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008544 if (dev) {
8545 status_t cmdStatus;
8546 uint32_t size = sizeof(status_t);
8547
8548 status = (*mEffectInterface)->command(mEffectInterface,
8549 EFFECT_CMD_SET_DEVICE,
8550 sizeof(uint32_t),
8551 &dev,
8552 &size,
8553 &cmdStatus);
8554 if (status == NO_ERROR) {
8555 status = cmdStatus;
8556 }
8557 }
8558 dev = device & AUDIO_DEVICE_IN_ALL;
8559 if (dev) {
8560 status_t cmdStatus;
8561 uint32_t size = sizeof(status_t);
8562
8563 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8564 EFFECT_CMD_SET_INPUT_DEVICE,
8565 sizeof(uint32_t),
8566 &dev,
8567 &size,
8568 &cmdStatus);
8569 if (status2 == NO_ERROR) {
8570 status2 = cmdStatus;
8571 }
8572 if (status == NO_ERROR) {
8573 status = status2;
8574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 }
8576 }
8577 return status;
8578}
8579
Glenn Kastenf78aee72012-01-04 11:00:47 -08008580status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581{
8582 Mutex::Autolock _l(mLock);
8583 status_t status = NO_ERROR;
8584 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008585 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008586 uint32_t size = sizeof(status_t);
8587 status = (*mEffectInterface)->command(mEffectInterface,
8588 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008589 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008590 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008591 &size,
8592 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593 if (status == NO_ERROR) {
8594 status = cmdStatus;
8595 }
8596 }
8597 return status;
8598}
8599
Eric Laurent59255e42011-07-27 19:49:51 -07008600void AudioFlinger::EffectModule::setSuspended(bool suspended)
8601{
8602 Mutex::Autolock _l(mLock);
8603 mSuspended = suspended;
8604}
Glenn Kastena3a85482012-01-04 11:01:11 -08008605
8606bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008607{
8608 Mutex::Autolock _l(mLock);
8609 return mSuspended;
8610}
8611
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008612bool AudioFlinger::EffectModule::purgeHandles()
8613{
8614 bool enabled = false;
8615 Mutex::Autolock _l(mLock);
8616 for (size_t i = 0; i < mHandles.size(); i++) {
8617 EffectHandle *handle = mHandles[i];
8618 if (handle != NULL && !handle->destroyed_l()) {
8619 handle->effect().clear();
8620 if (handle->hasControl()) {
8621 enabled = handle->enabled();
8622 }
8623 }
8624 }
8625 return enabled;
8626}
8627
Mathias Agopian65ab4712010-07-14 17:59:35 -07008628status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8629{
8630 const size_t SIZE = 256;
8631 char buffer[SIZE];
8632 String8 result;
8633
8634 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8635 result.append(buffer);
8636
8637 bool locked = tryLock(mLock);
8638 // failed to lock - AudioFlinger is probably deadlocked
8639 if (!locked) {
8640 result.append("\t\tCould not lock Fx mutex:\n");
8641 }
8642
8643 result.append("\t\tSession Status State Engine:\n");
8644 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8645 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8646 result.append(buffer);
8647
8648 result.append("\t\tDescriptor:\n");
8649 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8650 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8651 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8652 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8653 result.append(buffer);
8654 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8655 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8656 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8657 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8658 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008659 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008660 mDescriptor.apiVersion,
8661 mDescriptor.flags);
8662 result.append(buffer);
8663 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8664 mDescriptor.name);
8665 result.append(buffer);
8666 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8667 mDescriptor.implementor);
8668 result.append(buffer);
8669
8670 result.append("\t\t- Input configuration:\n");
8671 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8672 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8673 (uint32_t)mConfig.inputCfg.buffer.raw,
8674 mConfig.inputCfg.buffer.frameCount,
8675 mConfig.inputCfg.samplingRate,
8676 mConfig.inputCfg.channels,
8677 mConfig.inputCfg.format);
8678 result.append(buffer);
8679
8680 result.append("\t\t- Output configuration:\n");
8681 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8682 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8683 (uint32_t)mConfig.outputCfg.buffer.raw,
8684 mConfig.outputCfg.buffer.frameCount,
8685 mConfig.outputCfg.samplingRate,
8686 mConfig.outputCfg.channels,
8687 mConfig.outputCfg.format);
8688 result.append(buffer);
8689
8690 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8691 result.append(buffer);
8692 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8693 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008694 EffectHandle *handle = mHandles[i];
8695 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696 handle->dump(buffer, SIZE);
8697 result.append(buffer);
8698 }
8699 }
8700
8701 result.append("\n");
8702
8703 write(fd, result.string(), result.length());
8704
8705 if (locked) {
8706 mLock.unlock();
8707 }
8708
8709 return NO_ERROR;
8710}
8711
8712// ----------------------------------------------------------------------------
8713// EffectHandle implementation
8714// ----------------------------------------------------------------------------
8715
8716#undef LOG_TAG
8717#define LOG_TAG "AudioFlinger::EffectHandle"
8718
8719AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8720 const sp<AudioFlinger::Client>& client,
8721 const sp<IEffectClient>& effectClient,
8722 int32_t priority)
8723 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008724 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008725 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726{
Steve Block3856b092011-10-20 11:56:00 +01008727 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008729 if (client == 0) {
8730 return;
8731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8733 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8734 if (mCblkMemory != 0) {
8735 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8736
Glenn Kastena0d68332012-01-27 16:47:15 -08008737 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008738 new(mCblk) effect_param_cblk_t();
8739 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008742 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743 return;
8744 }
8745}
8746
8747AudioFlinger::EffectHandle::~EffectHandle()
8748{
Steve Block3856b092011-10-20 11:56:00 +01008749 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008750
8751 if (mEffect == 0) {
8752 mDestroyed = true;
8753 return;
8754 }
8755 mEffect->lock();
8756 mDestroyed = true;
8757 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008758 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759}
8760
8761status_t AudioFlinger::EffectHandle::enable()
8762{
Steve Block3856b092011-10-20 11:56:00 +01008763 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008764 if (!mHasControl) return INVALID_OPERATION;
8765 if (mEffect == 0) return DEAD_OBJECT;
8766
Eric Laurentdb7c0792011-08-10 10:37:50 -07008767 if (mEnabled) {
8768 return NO_ERROR;
8769 }
8770
Eric Laurent59255e42011-07-27 19:49:51 -07008771 mEnabled = true;
8772
8773 sp<ThreadBase> thread = mEffect->thread().promote();
8774 if (thread != 0) {
8775 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8776 }
8777
8778 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8779 if (mEffect->suspended()) {
8780 return NO_ERROR;
8781 }
8782
Eric Laurentdb7c0792011-08-10 10:37:50 -07008783 status_t status = mEffect->setEnabled(true);
8784 if (status != NO_ERROR) {
8785 if (thread != 0) {
8786 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8787 }
8788 mEnabled = false;
8789 }
8790 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008791}
8792
8793status_t AudioFlinger::EffectHandle::disable()
8794{
Steve Block3856b092011-10-20 11:56:00 +01008795 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008796 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008797 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798
Eric Laurentdb7c0792011-08-10 10:37:50 -07008799 if (!mEnabled) {
8800 return NO_ERROR;
8801 }
Eric Laurent59255e42011-07-27 19:49:51 -07008802 mEnabled = false;
8803
8804 if (mEffect->suspended()) {
8805 return NO_ERROR;
8806 }
8807
8808 status_t status = mEffect->setEnabled(false);
8809
8810 sp<ThreadBase> thread = mEffect->thread().promote();
8811 if (thread != 0) {
8812 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8813 }
8814
8815 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816}
8817
8818void AudioFlinger::EffectHandle::disconnect()
8819{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008820 disconnect(true);
8821}
8822
Glenn Kasten58123c32012-02-03 10:32:24 -08008823void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008824{
Glenn Kasten58123c32012-02-03 10:32:24 -08008825 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 if (mEffect == 0) {
8827 return;
8828 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008829 // restore suspended effects if the disconnected handle was enabled and the last one.
8830 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008831 sp<ThreadBase> thread = mEffect->thread().promote();
8832 if (thread != 0) {
8833 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8834 }
Eric Laurent59255e42011-07-27 19:49:51 -07008835 }
8836
Mathias Agopian65ab4712010-07-14 17:59:35 -07008837 // release sp on module => module destructor can be called now
8838 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008840 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008841 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008842 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8843 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008844 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008845 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8847 mClient.clear();
8848 }
8849}
8850
Eric Laurent25f43952010-07-28 05:40:18 -07008851status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8852 uint32_t cmdSize,
8853 void *pCmdData,
8854 uint32_t *replySize,
8855 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856{
Steve Block3856b092011-10-20 11:56:00 +01008857// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008858// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859
8860 // only get parameter command is permitted for applications not controlling the effect
8861 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8862 return INVALID_OPERATION;
8863 }
8864 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008865 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008866
8867 // handle commands that are not forwarded transparently to effect engine
8868 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8869 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8870 // no risk to block the whole media server process or mixer threads is we are stuck here
8871 Mutex::Autolock _l(mCblk->lock);
8872 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8873 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8874 mCblk->serverIndex = 0;
8875 mCblk->clientIndex = 0;
8876 return BAD_VALUE;
8877 }
8878 status_t status = NO_ERROR;
8879 while (mCblk->serverIndex < mCblk->clientIndex) {
8880 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008881 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882 int *p = (int *)(mBuffer + mCblk->serverIndex);
8883 int size = *p++;
8884 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008885 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008886 break;
8887 }
8888 effect_param_t *param = (effect_param_t *)p;
8889 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008890 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008891 mCblk->serverIndex += size;
8892 continue;
8893 }
Eric Laurent25f43952010-07-28 05:40:18 -07008894 uint32_t psize = sizeof(effect_param_t) +
8895 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8896 param->vsize;
8897 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8898 psize,
8899 p,
8900 &rsize,
8901 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008902 // stop at first error encountered
8903 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008905 *(int *)pReplyData = reply;
8906 break;
8907 } else if (reply != NO_ERROR) {
8908 *(int *)pReplyData = reply;
8909 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008910 }
8911 mCblk->serverIndex += size;
8912 }
8913 mCblk->serverIndex = 0;
8914 mCblk->clientIndex = 0;
8915 return status;
8916 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008917 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918 return enable();
8919 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008920 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921 return disable();
8922 }
8923
8924 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8925}
8926
Eric Laurent59255e42011-07-27 19:49:51 -07008927void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928{
Steve Block3856b092011-10-20 11:56:00 +01008929 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930
8931 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008932 mEnabled = enabled;
8933
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934 if (signal && mEffectClient != 0) {
8935 mEffectClient->controlStatusChanged(hasControl);
8936 }
8937}
8938
Eric Laurent25f43952010-07-28 05:40:18 -07008939void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8940 uint32_t cmdSize,
8941 void *pCmdData,
8942 uint32_t replySize,
8943 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008944{
8945 if (mEffectClient != 0) {
8946 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8947 }
8948}
8949
8950
8951
8952void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8953{
8954 if (mEffectClient != 0) {
8955 mEffectClient->enableStatusChanged(enabled);
8956 }
8957}
8958
8959status_t AudioFlinger::EffectHandle::onTransact(
8960 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8961{
8962 return BnEffect::onTransact(code, data, reply, flags);
8963}
8964
8965
8966void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8967{
Glenn Kastena0d68332012-01-27 16:47:15 -08008968 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969
8970 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008971 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972 mPriority,
8973 mHasControl,
8974 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008975 mCblk ? mCblk->clientIndex : 0,
8976 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 );
8978
8979 if (locked) {
8980 mCblk->lock.unlock();
8981 }
8982}
8983
8984#undef LOG_TAG
8985#define LOG_TAG "AudioFlinger::EffectChain"
8986
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008987AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008988 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008989 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008990 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8991 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008992{
Dima Zavinfce7a472011-04-19 22:30:36 -07008993 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008994 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008995 return;
8996 }
8997 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8998 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008999}
9000
9001AudioFlinger::EffectChain::~EffectChain()
9002{
9003 if (mOwnInBuffer) {
9004 delete mInBuffer;
9005 }
9006
9007}
9008
Eric Laurent59255e42011-07-27 19:49:51 -07009009// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009010sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009011{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012 size_t size = mEffects.size();
9013
9014 for (size_t i = 0; i < size; i++) {
9015 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009016 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017 }
9018 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009019 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009020}
9021
Eric Laurent59255e42011-07-27 19:49:51 -07009022// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009023sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009024{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009025 size_t size = mEffects.size();
9026
9027 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009028 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9029 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009030 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031 }
9032 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009033 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034}
9035
Eric Laurent59255e42011-07-27 19:49:51 -07009036// getEffectFromType_l() must be called with ThreadBase::mLock held
9037sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9038 const effect_uuid_t *type)
9039{
Eric Laurent59255e42011-07-27 19:49:51 -07009040 size_t size = mEffects.size();
9041
9042 for (size_t i = 0; i < size; i++) {
9043 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009044 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009045 }
9046 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009047 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009048}
9049
Eric Laurent91b14c42012-05-30 12:30:29 -07009050void AudioFlinger::EffectChain::clearInputBuffer()
9051{
9052 Mutex::Autolock _l(mLock);
9053 sp<ThreadBase> thread = mThread.promote();
9054 if (thread == 0) {
9055 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9056 return;
9057 }
9058 clearInputBuffer_l(thread);
9059}
9060
9061// Must be called with EffectChain::mLock locked
9062void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9063{
9064 size_t numSamples = thread->frameCount() * thread->channelCount();
9065 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9066
9067}
9068
Mathias Agopian65ab4712010-07-14 17:59:35 -07009069// Must be called with EffectChain::mLock locked
9070void AudioFlinger::EffectChain::process_l()
9071{
Eric Laurentdac69112010-09-28 14:09:57 -07009072 sp<ThreadBase> thread = mThread.promote();
9073 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009074 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009075 return;
9076 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009077 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9078 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009079 // always process effects unless no more tracks are on the session and the effect tail
9080 // has been rendered
9081 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009082 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009083 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009084
Eric Laurent544fe9b2011-11-11 15:42:52 -08009085 if (!tracksOnSession && mTailBufferCount == 0) {
9086 doProcess = false;
9087 }
9088
9089 if (activeTrackCnt() == 0) {
9090 // if no track is active and the effect tail has not been rendered,
9091 // the input buffer must be cleared here as the mixer process will not do it
9092 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009093 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009094 if (mTailBufferCount > 0) {
9095 mTailBufferCount--;
9096 }
9097 }
9098 }
Eric Laurentdac69112010-09-28 14:09:57 -07009099 }
9100
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009102 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009103 for (size_t i = 0; i < size; i++) {
9104 mEffects[i]->process();
9105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009106 }
9107 for (size_t i = 0; i < size; i++) {
9108 mEffects[i]->updateState();
9109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110}
9111
Eric Laurentcab11242010-07-15 12:50:15 -07009112// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009113status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009114{
9115 effect_descriptor_t desc = effect->desc();
9116 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9117
9118 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009119 effect->setChain(this);
9120 sp<ThreadBase> thread = mThread.promote();
9121 if (thread == 0) {
9122 return NO_INIT;
9123 }
9124 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009125
9126 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9127 // Auxiliary effects are inserted at the beginning of mEffects vector as
9128 // they are processed first and accumulated in chain input buffer
9129 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009130
Mathias Agopian65ab4712010-07-14 17:59:35 -07009131 // the input buffer for auxiliary effect contains mono samples in
9132 // 32 bit format. This is to avoid saturation in AudoMixer
9133 // accumulation stage. Saturation is done in EffectModule::process() before
9134 // calling the process in effect engine
9135 size_t numSamples = thread->frameCount();
9136 int32_t *buffer = new int32_t[numSamples];
9137 memset(buffer, 0, numSamples * sizeof(int32_t));
9138 effect->setInBuffer((int16_t *)buffer);
9139 // auxiliary effects output samples to chain input buffer for further processing
9140 // by insert effects
9141 effect->setOutBuffer(mInBuffer);
9142 } else {
9143 // Insert effects are inserted at the end of mEffects vector as they are processed
9144 // after track and auxiliary effects.
9145 // Insert effect order as a function of indicated preference:
9146 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9147 // another effect is present
9148 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9149 // last effect claiming first position
9150 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9151 // first effect claiming last position
9152 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9153 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9154 // already present
9155
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009156 size_t size = mEffects.size();
9157 size_t idx_insert = size;
9158 ssize_t idx_insert_first = -1;
9159 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009160
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009161 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009162 effect_descriptor_t d = mEffects[i]->desc();
9163 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9164 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9165 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9166 // check invalid effect chaining combinations
9167 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9168 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009169 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009170 return INVALID_OPERATION;
9171 }
9172 // remember position of first insert effect and by default
9173 // select this as insert position for new effect
9174 if (idx_insert == size) {
9175 idx_insert = i;
9176 }
9177 // remember position of last insert effect claiming
9178 // first position
9179 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9180 idx_insert_first = i;
9181 }
9182 // remember position of first insert effect claiming
9183 // last position
9184 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9185 idx_insert_last == -1) {
9186 idx_insert_last = i;
9187 }
9188 }
9189 }
9190
9191 // modify idx_insert from first position if needed
9192 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9193 if (idx_insert_last != -1) {
9194 idx_insert = idx_insert_last;
9195 } else {
9196 idx_insert = size;
9197 }
9198 } else {
9199 if (idx_insert_first != -1) {
9200 idx_insert = idx_insert_first + 1;
9201 }
9202 }
9203
9204 // always read samples from chain input buffer
9205 effect->setInBuffer(mInBuffer);
9206
9207 // if last effect in the chain, output samples to chain
9208 // output buffer, otherwise to chain input buffer
9209 if (idx_insert == size) {
9210 if (idx_insert != 0) {
9211 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9212 mEffects[idx_insert-1]->configure();
9213 }
9214 effect->setOutBuffer(mOutBuffer);
9215 } else {
9216 effect->setOutBuffer(mInBuffer);
9217 }
9218 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009219
Steve Block3856b092011-10-20 11:56:00 +01009220 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009221 }
9222 effect->configure();
9223 return NO_ERROR;
9224}
9225
Eric Laurentcab11242010-07-15 12:50:15 -07009226// removeEffect_l() must be called with PlaybackThread::mLock held
9227size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228{
9229 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009230 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009231 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9232
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009233 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009235 // calling stop here will remove pre-processing effect from the audio HAL.
9236 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9237 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009238 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9239 mEffects[i]->state() == EffectModule::STOPPING) {
9240 mEffects[i]->stop();
9241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9243 delete[] effect->inBuffer();
9244 } else {
9245 if (i == size - 1 && i != 0) {
9246 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9247 mEffects[i - 1]->configure();
9248 }
9249 }
9250 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009251 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 break;
9253 }
9254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255
9256 return mEffects.size();
9257}
9258
Eric Laurentcab11242010-07-15 12:50:15 -07009259// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009260void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009261{
9262 size_t size = mEffects.size();
9263 for (size_t i = 0; i < size; i++) {
9264 mEffects[i]->setDevice(device);
9265 }
9266}
9267
Eric Laurentcab11242010-07-15 12:50:15 -07009268// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009269void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009270{
9271 size_t size = mEffects.size();
9272 for (size_t i = 0; i < size; i++) {
9273 mEffects[i]->setMode(mode);
9274 }
9275}
9276
Eric Laurentcab11242010-07-15 12:50:15 -07009277// setVolume_l() must be called with PlaybackThread::mLock held
9278bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009279{
9280 uint32_t newLeft = *left;
9281 uint32_t newRight = *right;
9282 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009283 int ctrlIdx = -1;
9284 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009285
Eric Laurentcab11242010-07-15 12:50:15 -07009286 // first update volume controller
9287 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009288 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009289 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9290 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009291 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009292 break;
9293 }
9294 }
9295
9296 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009297 if (hasControl) {
9298 *left = mNewLeftVolume;
9299 *right = mNewRightVolume;
9300 }
9301 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009302 }
9303
9304 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009305 mLeftVolume = newLeft;
9306 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009307
9308 // second get volume update from volume controller
9309 if (ctrlIdx >= 0) {
9310 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009311 mNewLeftVolume = newLeft;
9312 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009313 }
9314 // then indicate volume to all other effects in chain.
9315 // Pass altered volume to effects before volume controller
9316 // and requested volume to effects after controller
9317 uint32_t lVol = newLeft;
9318 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009319
Mathias Agopian65ab4712010-07-14 17:59:35 -07009320 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009321 if ((int)i == ctrlIdx) continue;
9322 // this also works for ctrlIdx == -1 when there is no volume controller
9323 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009324 lVol = *left;
9325 rVol = *right;
9326 }
9327 mEffects[i]->setVolume(&lVol, &rVol, false);
9328 }
9329 *left = newLeft;
9330 *right = newRight;
9331
9332 return hasControl;
9333}
9334
Mathias Agopian65ab4712010-07-14 17:59:35 -07009335status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9336{
9337 const size_t SIZE = 256;
9338 char buffer[SIZE];
9339 String8 result;
9340
9341 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9342 result.append(buffer);
9343
9344 bool locked = tryLock(mLock);
9345 // failed to lock - AudioFlinger is probably deadlocked
9346 if (!locked) {
9347 result.append("\tCould not lock mutex:\n");
9348 }
9349
Eric Laurentcab11242010-07-15 12:50:15 -07009350 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9351 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009352 mEffects.size(),
9353 (uint32_t)mInBuffer,
9354 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 mActiveTrackCnt);
9356 result.append(buffer);
9357 write(fd, result.string(), result.size());
9358
9359 for (size_t i = 0; i < mEffects.size(); ++i) {
9360 sp<EffectModule> effect = mEffects[i];
9361 if (effect != 0) {
9362 effect->dump(fd, args);
9363 }
9364 }
9365
9366 if (locked) {
9367 mLock.unlock();
9368 }
9369
9370 return NO_ERROR;
9371}
9372
Eric Laurent59255e42011-07-27 19:49:51 -07009373// must be called with ThreadBase::mLock held
9374void AudioFlinger::EffectChain::setEffectSuspended_l(
9375 const effect_uuid_t *type, bool suspend)
9376{
9377 sp<SuspendedEffectDesc> desc;
9378 // use effect type UUID timelow as key as there is no real risk of identical
9379 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009380 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009381 if (suspend) {
9382 if (index >= 0) {
9383 desc = mSuspendedEffects.valueAt(index);
9384 } else {
9385 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009386 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009387 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009388 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009389 }
9390 if (desc->mRefCount++ == 0) {
9391 sp<EffectModule> effect = getEffectIfEnabled(type);
9392 if (effect != 0) {
9393 desc->mEffect = effect;
9394 effect->setSuspended(true);
9395 effect->setEnabled(false);
9396 }
9397 }
9398 } else {
9399 if (index < 0) {
9400 return;
9401 }
9402 desc = mSuspendedEffects.valueAt(index);
9403 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009404 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009405 desc->mRefCount = 1;
9406 }
9407 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009408 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009409 if (desc->mEffect != 0) {
9410 sp<EffectModule> effect = desc->mEffect.promote();
9411 if (effect != 0) {
9412 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009413 effect->lock();
9414 EffectHandle *handle = effect->controlHandle_l();
9415 if (handle != NULL && !handle->destroyed_l()) {
9416 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009417 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009418 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009419 }
9420 desc->mEffect.clear();
9421 }
9422 mSuspendedEffects.removeItemsAt(index);
9423 }
9424 }
9425}
9426
9427// must be called with ThreadBase::mLock held
9428void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9429{
9430 sp<SuspendedEffectDesc> desc;
9431
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009432 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009433 if (suspend) {
9434 if (index >= 0) {
9435 desc = mSuspendedEffects.valueAt(index);
9436 } else {
9437 desc = new SuspendedEffectDesc();
9438 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009439 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009440 }
9441 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009442 Vector< sp<EffectModule> > effects;
9443 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009444 for (size_t i = 0; i < effects.size(); i++) {
9445 setEffectSuspended_l(&effects[i]->desc().type, true);
9446 }
9447 }
9448 } else {
9449 if (index < 0) {
9450 return;
9451 }
9452 desc = mSuspendedEffects.valueAt(index);
9453 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009454 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009455 desc->mRefCount = 1;
9456 }
9457 if (--desc->mRefCount == 0) {
9458 Vector<const effect_uuid_t *> types;
9459 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9460 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9461 continue;
9462 }
9463 types.add(&mSuspendedEffects.valueAt(i)->mType);
9464 }
9465 for (size_t i = 0; i < types.size(); i++) {
9466 setEffectSuspended_l(types[i], false);
9467 }
Steve Block3856b092011-10-20 11:56:00 +01009468 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009469 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9470 }
9471 }
9472}
9473
Eric Laurent6bffdb82011-09-23 08:40:41 -07009474
9475// The volume effect is used for automated tests only
9476#ifndef OPENSL_ES_H_
9477static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9478 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9479const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9480#endif //OPENSL_ES_H_
9481
Eric Laurentdb7c0792011-08-10 10:37:50 -07009482bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9483{
9484 // auxiliary effects and visualizer are never suspended on output mix
9485 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9486 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009487 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9488 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009489 return false;
9490 }
9491 return true;
9492}
9493
Glenn Kastend0539712012-01-30 12:56:03 -08009494void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009495{
Glenn Kastend0539712012-01-30 12:56:03 -08009496 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009497 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009498 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9499 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009500 }
Eric Laurent59255e42011-07-27 19:49:51 -07009501 }
Eric Laurent59255e42011-07-27 19:49:51 -07009502}
9503
9504sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9505 const effect_uuid_t *type)
9506{
Glenn Kasten090f0192012-01-30 13:00:02 -08009507 sp<EffectModule> effect = getEffectFromType_l(type);
9508 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009509}
9510
9511void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9512 bool enabled)
9513{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009514 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009515 if (enabled) {
9516 if (index < 0) {
9517 // if the effect is not suspend check if all effects are suspended
9518 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9519 if (index < 0) {
9520 return;
9521 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009522 if (!isEffectEligibleForSuspend(effect->desc())) {
9523 return;
9524 }
Eric Laurent59255e42011-07-27 19:49:51 -07009525 setEffectSuspended_l(&effect->desc().type, enabled);
9526 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009527 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009528 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009529 return;
9530 }
Eric Laurent59255e42011-07-27 19:49:51 -07009531 }
Steve Block3856b092011-10-20 11:56:00 +01009532 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009533 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009534 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9535 // if effect is requested to suspended but was not yet enabled, supend it now.
9536 if (desc->mEffect == 0) {
9537 desc->mEffect = effect;
9538 effect->setEnabled(false);
9539 effect->setSuspended(true);
9540 }
9541 } else {
9542 if (index < 0) {
9543 return;
9544 }
Steve Block3856b092011-10-20 11:56:00 +01009545 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009546 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009547 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9548 desc->mEffect.clear();
9549 effect->setSuspended(false);
9550 }
9551}
9552
Mathias Agopian65ab4712010-07-14 17:59:35 -07009553#undef LOG_TAG
9554#define LOG_TAG "AudioFlinger"
9555
9556// ----------------------------------------------------------------------------
9557
9558status_t AudioFlinger::onTransact(
9559 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9560{
9561 return BnAudioFlinger::onTransact(code, data, reply, flags);
9562}
9563
Mathias Agopian65ab4712010-07-14 17:59:35 -07009564}; // namespace android