blob: 1ea788e53bfe5f34262886384bb7415f0afe0010 [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#ifdef HAVE_REQUEST_PRIORITY
87#include "SchedulingPolicyService.h"
88#endif
89
Glenn Kasten58912562012-04-03 10:45:00 -070090#ifdef SOAKER
91#include "Soaker.h"
92#endif
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
John Grossman1c345192012-03-27 14:00:17 -070096// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
Eric Laurentde070132010-07-13 04:45:46 -0700108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800115static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116
117// retry counts for buffer fill timeout
118// 50 * ~20msecs = 1 second
119static const int8_t kMaxTrackRetries = 50;
120static const int8_t kMaxTrackStartupRetries = 50;
121// allow less retry attempts on direct output thread.
122// direct outputs can be a scarce resource in audio hardware and should
123// be released as quickly as possible.
124static const int8_t kMaxTrackRetriesDirect = 2;
125
126static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800127static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// don't warn about blocked writes or record buffer overflows more often than this
130static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700132// RecordThread loop sleep time upon application overrun or audio HAL read error
133static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Glenn Kasten7dede872011-12-13 11:04:14 -0800135// maximum time to wait for setParameters to complete
136static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700137
Eric Laurent7cafbb32011-11-22 18:50:29 -0800138// minimum sleep time for the mixer thread loop when tracks are active but in underrun
139static const uint32_t kMinThreadSleepTimeUs = 5000;
140// maximum divider applied to the active sleep time in the mixer thread loop
141static const uint32_t kMaxThreadSleepTimeShift = 2;
142
Glenn Kasten58912562012-04-03 10:45:00 -0700143// minimum normal mix buffer size, expressed in milliseconds rather than frames
144static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700145// maximum normal mix buffer size
146static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700147
John Grossman4ff14ba2012-02-08 16:37:41 -0800148nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800149
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700150// Whether to use fast mixer
151static const enum {
152 FastMixer_Never, // never initialize or use: for debugging only
153 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
154 // normal mixer multiplier is 1
155 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700156 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700157 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700158 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700159 // FIXME for FastMixer_Dynamic:
160 // Supporting this option will require fixing HALs that can't handle large writes.
161 // For example, one HAL implementation returns an error from a large write,
162 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
163 // We could either fix the HAL implementations, or provide a wrapper that breaks
164 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
165} kUseFastMixer = FastMixer_Static;
166
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700167static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
168 // AudioFlinger::setParameters() updates, other threads read w/o lock
169
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170// ----------------------------------------------------------------------------
171
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700172#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800173// To collect the amplifier usage
174static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800175 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
176 if (service == NULL) {
177 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800178 return;
179 }
180
181 service->addBatteryData(params);
182}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700183#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800184
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700186{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700187 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 int rc;
189
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700190 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
191 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
192 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
193 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700195 }
196 rc = audio_hw_device_open(mod, dev);
197 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
198 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
199 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700201 }
202 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
203 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
204 rc = BAD_VALUE;
205 goto out;
206 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 return 0;
208
209out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 *dev = NULL;
211 return rc;
212}
213
Mathias Agopian65ab4712010-07-14 17:59:35 -0700214// ----------------------------------------------------------------------------
215
216AudioFlinger::AudioFlinger()
217 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mPrimaryHardwareDev(NULL),
219 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
220 mMasterVolume(1.0f),
221 mMasterVolumeSupportLvl(MVS_NONE),
222 mMasterMute(false),
223 mNextUniqueId(1),
224 mMode(AUDIO_MODE_INVALID),
225 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700227}
228
229void AudioFlinger::onFirstRef()
230{
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700232
Eric Laurent93575202011-01-18 18:39:02 -0800233 Mutex::Autolock _l(mLock);
234
Dima Zavin799a70e2011-04-18 16:57:27 -0700235 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800236 char val_str[PROPERTY_VALUE_MAX] = { 0 };
237 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
238 uint32_t int_val;
239 if (1 == sscanf(val_str, "%u", &int_val)) {
240 mStandbyTimeInNsecs = milliseconds(int_val);
241 ALOGI("Using %u mSec as standby time.", int_val);
242 } else {
243 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
244 ALOGI("Using default %u mSec as standby time.",
245 (uint32_t)(mStandbyTimeInNsecs / 1000000));
246 }
247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248
Eric Laurenta4c5a552012-03-29 10:12:40 -0700249 mMode = AUDIO_MODE_NORMAL;
250 mMasterVolumeSW = 1.0;
251 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800252 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253}
254
255AudioFlinger::~AudioFlinger()
256{
Dima Zavin799a70e2011-04-18 16:57:27 -0700257
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258 while (!mRecordThreads.isEmpty()) {
259 // closeInput() will remove first entry from mRecordThreads
260 closeInput(mRecordThreads.keyAt(0));
261 }
262 while (!mPlaybackThreads.isEmpty()) {
263 // closeOutput() will remove first entry from mPlaybackThreads
264 closeOutput(mPlaybackThreads.keyAt(0));
265 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700266
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800267 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
268 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
270 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 }
272}
273
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274static const char * const audio_interfaces[] = {
275 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
276 AUDIO_HARDWARE_MODULE_ID_A2DP,
277 AUDIO_HARDWARE_MODULE_ID_USB,
278};
279#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
280
281audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700282{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700283 // if module is 0, the request comes from an old policy manager and we should load
284 // well known modules
285 if (module == 0) {
286 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
287 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
288 loadHwModule_l(audio_interfaces[i]);
289 }
290 } else {
291 // check a match for the requested module handle
292 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
293 if (audioHwdevice != NULL) {
294 return audioHwdevice->hwDevice();
295 }
296 }
297 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700298 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700300 if ((dev->get_supported_devices(dev) & devices) == devices)
301 return dev;
302 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700303
Dima Zavin799a70e2011-04-18 16:57:27 -0700304 return NULL;
305}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306
307status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
308{
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
312
313 result.append("Clients:\n");
314 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800315 sp<Client> client = mClients.valueAt(i).promote();
316 if (client != 0) {
317 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
318 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 }
320 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321
322 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
325 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800326 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327 result.append(buffer);
328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 write(fd, result.string(), result.size());
330 return NO_ERROR;
331}
332
333
334status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
335{
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800339 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340
John Grossman4ff14ba2012-02-08 16:37:41 -0800341 snprintf(buffer, SIZE, "Hardware status: %d\n"
342 "Standby Time mSec: %u\n",
343 hardwareStatus,
344 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 result.append(buffer);
346 write(fd, result.string(), result.size());
347 return NO_ERROR;
348}
349
350status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
351{
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
355 snprintf(buffer, SIZE, "Permission Denial: "
356 "can't dump AudioFlinger from pid=%d, uid=%d\n",
357 IPCThreadState::self()->getCallingPid(),
358 IPCThreadState::self()->getCallingUid());
359 result.append(buffer);
360 write(fd, result.string(), result.size());
361 return NO_ERROR;
362}
363
364static bool tryLock(Mutex& mutex)
365{
366 bool locked = false;
367 for (int i = 0; i < kDumpLockRetries; ++i) {
368 if (mutex.tryLock() == NO_ERROR) {
369 locked = true;
370 break;
371 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800372 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 return locked;
375}
376
377status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
378{
Glenn Kasten44deb052012-02-05 18:09:08 -0800379 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 dumpPermissionDenial(fd, args);
381 } else {
382 // get state of hardware lock
383 bool hardwareLocked = tryLock(mHardwareLock);
384 if (!hardwareLocked) {
385 String8 result(kHardwareLockedString);
386 write(fd, result.string(), result.size());
387 } else {
388 mHardwareLock.unlock();
389 }
390
391 bool locked = tryLock(mLock);
392
393 // failed to lock - AudioFlinger is probably deadlocked
394 if (!locked) {
395 String8 result(kDeadlockedString);
396 write(fd, result.string(), result.size());
397 }
398
399 dumpClients(fd, args);
400 dumpInternals(fd, args);
401
402 // dump playback threads
403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
404 mPlaybackThreads.valueAt(i)->dump(fd, args);
405 }
406
407 // dump record threads
408 for (size_t i = 0; i < mRecordThreads.size(); i++) {
409 mRecordThreads.valueAt(i)->dump(fd, args);
410 }
411
Dima Zavin799a70e2011-04-18 16:57:27 -0700412 // dump all hardware devs
413 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700414 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700415 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 }
417 if (locked) mLock.unlock();
418 }
419 return NO_ERROR;
420}
421
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800422sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
423{
424 // If pid is already in the mClients wp<> map, then use that entry
425 // (for which promote() is always != 0), otherwise create a new entry and Client.
426 sp<Client> client = mClients.valueFor(pid).promote();
427 if (client == 0) {
428 client = new Client(this, pid);
429 mClients.add(pid, client);
430 }
431
432 return client;
433}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434
435// IAudioFlinger interface
436
437
438sp<IAudioTrack> AudioFlinger::createTrack(
439 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800440 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800442 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700443 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800445 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800447 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800448 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 int *sessionId,
450 status_t *status)
451{
452 sp<PlaybackThread::Track> track;
453 sp<TrackHandle> trackHandle;
454 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 status_t lStatus;
456 int lSessionId;
457
Glenn Kasten263709e2012-01-06 08:40:01 -0800458 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
459 // but if someone uses binder directly they could bypass that and cause us to crash
460 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000461 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 lStatus = BAD_VALUE;
463 goto Exit;
464 }
465
466 {
467 Mutex::Autolock _l(mLock);
468 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700469 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000471 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 lStatus = BAD_VALUE;
473 goto Exit;
474 }
475
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800476 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477
Steve Block3856b092011-10-20 11:56:00 +0100478 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700479 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700480 // check if an effect chain with the same session ID is present on another
481 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700482 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700483 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
484 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700485 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 if (sessions & PlaybackThread::EFFECT_SESSION) {
487 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700488 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700489 }
Eric Laurentde070132010-07-13 04:45:46 -0700490 }
491 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492 lSessionId = *sessionId;
493 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700494 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700495 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 if (sessionId != NULL) {
497 *sessionId = lSessionId;
498 }
499 }
Steve Block3856b092011-10-20 11:56:00 +0100500 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501
502 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800503 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700504
505 // move effect chain to this output thread if an effect on same session was waiting
506 // for a track to be created
507 if (lStatus == NO_ERROR && effectThread != NULL) {
508 Mutex::Autolock _dl(thread->mLock);
509 Mutex::Autolock _sl(effectThread->mLock);
510 moveEffectChain_l(lSessionId, effectThread, thread, true);
511 }
Eric Laurenta011e352012-03-29 15:51:43 -0700512
513 // Look for sync events awaiting for a session to be used.
514 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
515 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
516 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700517 if (lStatus == NO_ERROR) {
518 track->setSyncEvent(mPendingSyncEvents[i]);
519 } else {
520 mPendingSyncEvents[i]->cancel();
521 }
Eric Laurenta011e352012-03-29 15:51:43 -0700522 mPendingSyncEvents.removeAt(i);
523 i--;
524 }
525 }
526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 }
528 if (lStatus == NO_ERROR) {
529 trackHandle = new TrackHandle(track);
530 } else {
531 // remove local strong reference to Client before deleting the Track so that the Client
532 // destructor is called by the TrackBase destructor with mLock held
533 client.clear();
534 track.clear();
535 }
536
537Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700538 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 *status = lStatus;
540 }
541 return trackHandle;
542}
543
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800544uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545{
546 Mutex::Autolock _l(mLock);
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000549 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 return 0;
551 }
552 return thread->sampleRate();
553}
554
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800555int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556{
557 Mutex::Autolock _l(mLock);
558 PlaybackThread *thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000560 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 return 0;
562 }
563 return thread->channelCount();
564}
565
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800566audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567{
568 Mutex::Autolock _l(mLock);
569 PlaybackThread *thread = checkPlaybackThread_l(output);
570 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000571 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800572 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 }
574 return thread->format();
575}
576
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800577size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578{
579 Mutex::Autolock _l(mLock);
580 PlaybackThread *thread = checkPlaybackThread_l(output);
581 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000582 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 return 0;
584 }
Glenn Kasten58912562012-04-03 10:45:00 -0700585 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
586 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587 return thread->frameCount();
588}
589
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800590uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591{
592 Mutex::Autolock _l(mLock);
593 PlaybackThread *thread = checkPlaybackThread_l(output);
594 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000595 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 return 0;
597 }
598 return thread->latency();
599}
600
601status_t AudioFlinger::setMasterVolume(float value)
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 float swmv = value;
614
Eric Laurenta4c5a552012-03-29 10:12:40 -0700615 Mutex::Autolock _l(mLock);
616
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800618 if (MVS_NONE != mMasterVolumeSupportLvl) {
619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
620 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700621 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800622
623 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
624 if (NULL != dev->set_master_volume) {
625 dev->set_master_volume(dev, value);
626 }
627 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800628 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800629
630 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632
John Grossman4ff14ba2012-02-08 16:37:41 -0800633 mMasterVolume = value;
634 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800635 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700636 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637
638 return NO_ERROR;
639}
640
Glenn Kastenf78aee72012-01-04 11:00:47 -0800641status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642{
Eric Laurenta1884f92011-08-23 08:25:03 -0700643 status_t ret = initCheck();
644 if (ret != NO_ERROR) {
645 return ret;
646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800652 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000653 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
657 { // scope for the lock
658 AutoMutex lock(mHardwareLock);
659 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700660 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 mHardwareStatus = AUDIO_HW_IDLE;
662 }
663
664 if (NO_ERROR == ret) {
665 Mutex::Autolock _l(mLock);
666 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800667 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700668 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669 }
670
671 return ret;
672}
673
674status_t AudioFlinger::setMicMute(bool state)
675{
Eric Laurenta1884f92011-08-23 08:25:03 -0700676 status_t ret = initCheck();
677 if (ret != NO_ERROR) {
678 return ret;
679 }
680
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
686 AutoMutex lock(mHardwareLock);
687 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700688 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 mHardwareStatus = AUDIO_HW_IDLE;
690 return ret;
691}
692
693bool AudioFlinger::getMicMute() const
694{
Eric Laurenta1884f92011-08-23 08:25:03 -0700695 status_t ret = initCheck();
696 if (ret != NO_ERROR) {
697 return false;
698 }
699
Dima Zavinfce7a472011-04-19 22:30:36 -0700700 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800701 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700703 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 mHardwareStatus = AUDIO_HW_IDLE;
705 return state;
706}
707
708status_t AudioFlinger::setMasterMute(bool muted)
709{
710 // check calling permissions
711 if (!settingsAllowed()) {
712 return PERMISSION_DENIED;
713 }
714
Eric Laurent93575202011-01-18 18:39:02 -0800715 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800716 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800718 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700719 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720
721 return NO_ERROR;
722}
723
724float AudioFlinger::masterVolume() const
725{
Glenn Kasten98067102011-12-13 11:47:54 -0800726 Mutex::Autolock _l(mLock);
727 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728}
729
John Grossman4ff14ba2012-02-08 16:37:41 -0800730float AudioFlinger::masterVolumeSW() const
731{
732 Mutex::Autolock _l(mLock);
733 return masterVolumeSW_l();
734}
735
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736bool AudioFlinger::masterMute() const
737{
Glenn Kasten98067102011-12-13 11:47:54 -0800738 Mutex::Autolock _l(mLock);
739 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740}
741
John Grossman4ff14ba2012-02-08 16:37:41 -0800742float AudioFlinger::masterVolume_l() const
743{
744 if (MVS_FULL == mMasterVolumeSupportLvl) {
745 float ret_val;
746 AutoMutex lock(mHardwareLock);
747
748 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800749 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
750 (NULL != mPrimaryHardwareDev->get_master_volume),
751 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800752
753 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
754 mHardwareStatus = AUDIO_HW_IDLE;
755 return ret_val;
756 }
757
758 return mMasterVolume;
759}
760
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800761status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
762 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763{
764 // check calling permissions
765 if (!settingsAllowed()) {
766 return PERMISSION_DENIED;
767 }
768
Glenn Kasten263709e2012-01-06 08:40:01 -0800769 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000770 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771 return BAD_VALUE;
772 }
773
774 AutoMutex lock(mLock);
775 PlaybackThread *thread = NULL;
776 if (output) {
777 thread = checkPlaybackThread_l(output);
778 if (thread == NULL) {
779 return BAD_VALUE;
780 }
781 }
782
783 mStreamTypes[stream].volume = value;
784
785 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700787 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788 }
789 } else {
790 thread->setStreamVolume(stream, value);
791 }
792
793 return NO_ERROR;
794}
795
Glenn Kastenfff6d712012-01-12 16:38:12 -0800796status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797{
798 // check calling permissions
799 if (!settingsAllowed()) {
800 return PERMISSION_DENIED;
801 }
802
Glenn Kasten263709e2012-01-06 08:40:01 -0800803 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700804 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000805 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 return BAD_VALUE;
807 }
808
Eric Laurent93575202011-01-18 18:39:02 -0800809 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 mStreamTypes[stream].mute = muted;
811 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700812 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813
814 return NO_ERROR;
815}
816
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800817float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818{
Glenn Kasten263709e2012-01-06 08:40:01 -0800819 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 return 0.0f;
821 }
822
823 AutoMutex lock(mLock);
824 float volume;
825 if (output) {
826 PlaybackThread *thread = checkPlaybackThread_l(output);
827 if (thread == NULL) {
828 return 0.0f;
829 }
830 volume = thread->streamVolume(stream);
831 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800832 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 }
834
835 return volume;
836}
837
Glenn Kastenfff6d712012-01-12 16:38:12 -0800838bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839{
Glenn Kasten263709e2012-01-06 08:40:01 -0800840 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 return true;
842 }
843
Glenn Kasten6637baa2012-01-09 09:40:36 -0800844 AutoMutex lock(mLock);
845 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846}
847
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800848status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800850 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
852 // check calling permissions
853 if (!settingsAllowed()) {
854 return PERMISSION_DENIED;
855 }
856
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 // ioHandle == 0 means the parameters are global to the audio hardware interface
858 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700859 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700860 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800861 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700862 AutoMutex lock(mHardwareLock);
863 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
864 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
865 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
866 status_t result = dev->set_parameters(dev, keyValuePairs.string());
867 final_result = result ?: final_result;
868 }
869 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800870 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700871 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
872 AudioParameter param = AudioParameter(keyValuePairs);
873 String8 value;
874 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700875 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
876 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700877 for (size_t i = 0; i < mRecordThreads.size(); i++) {
878 sp<RecordThread> thread = mRecordThreads.valueAt(i);
879 RecordThread::RecordTrack *track = thread->track();
880 if (track != NULL) {
881 audio_devices_t device = (audio_devices_t)(
882 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700883 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700884 thread->setEffectSuspended(FX_IID_AEC,
885 suspend,
886 track->sessionId());
887 thread->setEffectSuspended(FX_IID_NS,
888 suspend,
889 track->sessionId());
890 }
891 }
Eric Laurentbee53372011-08-29 12:42:48 -0700892 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700893 }
894 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700895 String8 screenState;
896 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
897 bool isOff = screenState == "off";
898 if (isOff != (gScreenState & 1)) {
899 gScreenState = ((gScreenState & ~1) + 2) | isOff;
900 }
901 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700902 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 }
904
905 // hold a strong ref on thread in case closeOutput() or closeInput() is called
906 // and the thread is exited once the lock is released
907 sp<ThreadBase> thread;
908 {
909 Mutex::Autolock _l(mLock);
910 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700911 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800913 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700914 // indicate output device change to all input threads for pre processing
915 AudioParameter param = AudioParameter(keyValuePairs);
916 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700917 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
918 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700919 for (size_t i = 0; i < mRecordThreads.size(); i++) {
920 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
921 }
922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923 }
924 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800925 if (thread != 0) {
926 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 }
928 return BAD_VALUE;
929}
930
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800931String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800933// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
935
Eric Laurenta4c5a552012-03-29 10:12:40 -0700936 Mutex::Autolock _l(mLock);
937
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700939 String8 out_s8;
940
Dima Zavin799a70e2011-04-18 16:57:27 -0700941 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800942 char *s;
943 {
944 AutoMutex lock(mHardwareLock);
945 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700946 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800947 s = dev->get_parameters(dev, keys.string());
948 mHardwareStatus = AUDIO_HW_IDLE;
949 }
John Grossmanef7740b2012-02-09 11:28:36 -0800950 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700951 free(s);
952 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700953 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 }
955
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
957 if (playbackThread != NULL) {
958 return playbackThread->getParameters(keys);
959 }
960 RecordThread *recordThread = checkRecordThread_l(ioHandle);
961 if (recordThread != NULL) {
962 return recordThread->getParameters(keys);
963 }
964 return String8("");
965}
966
Glenn Kastenf587ba52012-01-26 16:25:10 -0800967size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700968{
Eric Laurenta1884f92011-08-23 08:25:03 -0700969 status_t ret = initCheck();
970 if (ret != NO_ERROR) {
971 return 0;
972 }
973
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800974 AutoMutex lock(mHardwareLock);
975 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700976 struct audio_config config = {
977 sample_rate: sampleRate,
978 channel_mask: audio_channel_in_mask_from_count(channelCount),
979 format: format,
980 };
981 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800982 mHardwareStatus = AUDIO_HW_IDLE;
983 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984}
985
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800986unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
988 if (ioHandle == 0) {
989 return 0;
990 }
991
992 Mutex::Autolock _l(mLock);
993
994 RecordThread *recordThread = checkRecordThread_l(ioHandle);
995 if (recordThread != NULL) {
996 return recordThread->getInputFramesLost();
997 }
998 return 0;
999}
1000
1001status_t AudioFlinger::setVoiceVolume(float value)
1002{
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 status_t ret = initCheck();
1004 if (ret != NO_ERROR) {
1005 return ret;
1006 }
1007
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 // check calling permissions
1009 if (!settingsAllowed()) {
1010 return PERMISSION_DENIED;
1011 }
1012
1013 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001014 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001015 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 mHardwareStatus = AUDIO_HW_IDLE;
1017
1018 return ret;
1019}
1020
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001021status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1022 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023{
1024 status_t status;
1025
1026 Mutex::Autolock _l(mLock);
1027
1028 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1029 if (playbackThread != NULL) {
1030 return playbackThread->getRenderPosition(halFrames, dspFrames);
1031 }
1032
1033 return BAD_VALUE;
1034}
1035
1036void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1037{
1038
1039 Mutex::Autolock _l(mLock);
1040
Glenn Kastenbb001922012-02-03 11:10:26 -08001041 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 if (mNotificationClients.indexOfKey(pid) < 0) {
1043 sp<NotificationClient> notificationClient = new NotificationClient(this,
1044 client,
1045 pid);
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
1048 mNotificationClients.add(pid, notificationClient);
1049
1050 sp<IBinder> binder = client->asBinder();
1051 binder->linkToDeath(notificationClient);
1052
1053 // the config change is always sent from playback or record threads to avoid deadlock
1054 // with AudioSystem::gLock
1055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1056 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1057 }
1058
1059 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1060 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1061 }
1062 }
1063}
1064
1065void AudioFlinger::removeNotificationClient(pid_t pid)
1066{
1067 Mutex::Autolock _l(mLock);
1068
Glenn Kastena3b09252012-01-20 09:19:01 -08001069 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001072 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001074 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001076 ALOGV(" pid %d @ %d", ref->mPid, i);
1077 if (ref->mPid == pid) {
1078 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079 mAudioSessionRefs.removeAt(i);
1080 delete ref;
1081 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 } else {
1084 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001085 }
1086 }
1087 if (removed) {
1088 purgeStaleEffects_l();
1089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090}
1091
1092// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001093void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
1095 size_t size = mNotificationClients.size();
1096 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001097 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1098 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 }
1100}
1101
1102// removeClient_l() must be called with AudioFlinger::mLock held
1103void AudioFlinger::removeClient_l(pid_t pid)
1104{
Steve Block3856b092011-10-20 11:56:00 +01001105 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 mClients.removeItem(pid);
1107}
1108
Eric Laurent717e1282012-06-29 16:36:52 -07001109// getEffectThread_l() must be called with AudioFlinger::mLock held
1110sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1111{
1112 sp<PlaybackThread> thread;
1113
1114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1115 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1116 ALOG_ASSERT(thread == 0);
1117 thread = mPlaybackThreads.valueAt(i);
1118 }
1119 }
1120
1121 return thread;
1122}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123
1124// ----------------------------------------------------------------------------
1125
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001126AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1127 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001129 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001130 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001131 // mChannelMask
1132 mChannelCount(0),
1133 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1134 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001135 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001136 mDevice(device),
1137 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138{
1139}
1140
1141AudioFlinger::ThreadBase::~ThreadBase()
1142{
1143 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001144 // do not lock the mutex in destructor
1145 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001146 if (mPowerManager != 0) {
1147 sp<IBinder> binder = mPowerManager->asBinder();
1148 binder->unlinkToDeath(mDeathRecipient);
1149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150}
1151
1152void AudioFlinger::ThreadBase::exit()
1153{
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001156 // This lock prevents the following race in thread (uniprocessor for illustration):
1157 // if (!exitPending()) {
1158 // // context switch from here to exit()
1159 // // exit() calls requestExit(), what exitPending() observes
1160 // // exit() calls signal(), which is dropped since no waiters
1161 // // context switch back from exit() to here
1162 // mWaitWorkCV.wait(...);
1163 // // now thread is hung
1164 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001165 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 requestExit();
1167 mWaitWorkCV.signal();
1168 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001169 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1170 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 requestExitAndWait();
1172}
1173
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1175{
1176 status_t status;
1177
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 Mutex::Autolock _l(mLock);
1180
1181 mNewParameters.add(keyValuePairs);
1182 mWaitWorkCV.signal();
1183 // wait condition with timeout in case the thread loop has exited
1184 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001185 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 status = mParamStatus;
1187 mWaitWorkCV.signal();
1188 } else {
1189 status = TIMED_OUT;
1190 }
1191 return status;
1192}
1193
1194void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1195{
1196 Mutex::Autolock _l(mLock);
1197 sendConfigEvent_l(event, param);
1198}
1199
1200// sendConfigEvent_l() must be called with ThreadBase::mLock held
1201void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1202{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001203 ConfigEvent configEvent;
1204 configEvent.mEvent = event;
1205 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 mWaitWorkCV.signal();
1209}
1210
1211void AudioFlinger::ThreadBase::processConfigEvents()
1212{
1213 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001214 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001215 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001216 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mConfigEvents.removeAt(0);
1218 // release mLock before locking AudioFlinger mLock: lock order is always
1219 // AudioFlinger then ThreadBase to avoid cross deadlock
1220 mLock.unlock();
1221 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001222 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mLock.lock();
1225 }
1226 mLock.unlock();
1227}
1228
1229status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1230{
1231 const size_t SIZE = 256;
1232 char buffer[SIZE];
1233 String8 result;
1234
1235 bool locked = tryLock(mLock);
1236 if (!locked) {
1237 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1238 write(fd, buffer, strlen(buffer));
1239 }
1240
Eric Laurent612bbb52012-03-14 15:03:26 -07001241 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1244 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1248 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001249 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1250 result.append(buffer);
1251 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 result.append(buffer);
1253 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1254 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001255 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1256 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1258 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001259 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 result.append(buffer);
1261
1262 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1263 result.append(buffer);
1264 result.append(" Index Command");
1265 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1266 snprintf(buffer, SIZE, "\n %02d ", i);
1267 result.append(buffer);
1268 result.append(mNewParameters[i]);
1269 }
1270
1271 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1272 result.append(buffer);
1273 snprintf(buffer, SIZE, " Index event param\n");
1274 result.append(buffer);
1275 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001276 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277 result.append(buffer);
1278 }
1279 result.append("\n");
1280
1281 write(fd, result.string(), result.size());
1282
1283 if (locked) {
1284 mLock.unlock();
1285 }
1286 return NO_ERROR;
1287}
1288
Eric Laurent1d2bff02011-07-24 17:49:51 -07001289status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1290{
1291 const size_t SIZE = 256;
1292 char buffer[SIZE];
1293 String8 result;
1294
1295 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1296 write(fd, buffer, strlen(buffer));
1297
1298 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1299 sp<EffectChain> chain = mEffectChains[i];
1300 if (chain != 0) {
1301 chain->dump(fd, args);
1302 }
1303 }
1304 return NO_ERROR;
1305}
1306
Eric Laurentfeb0db62011-07-22 09:04:31 -07001307void AudioFlinger::ThreadBase::acquireWakeLock()
1308{
1309 Mutex::Autolock _l(mLock);
1310 acquireWakeLock_l();
1311}
1312
1313void AudioFlinger::ThreadBase::acquireWakeLock_l()
1314{
1315 if (mPowerManager == 0) {
1316 // use checkService() to avoid blocking if power service is not up yet
1317 sp<IBinder> binder =
1318 defaultServiceManager()->checkService(String16("power"));
1319 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001320 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001321 } else {
1322 mPowerManager = interface_cast<IPowerManager>(binder);
1323 binder->linkToDeath(mDeathRecipient);
1324 }
1325 }
1326 if (mPowerManager != 0) {
1327 sp<IBinder> binder = new BBinder();
1328 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1329 binder,
1330 String16(mName));
1331 if (status == NO_ERROR) {
1332 mWakeLockToken = binder;
1333 }
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001335 }
1336}
1337
1338void AudioFlinger::ThreadBase::releaseWakeLock()
1339{
1340 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001341 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001342}
1343
1344void AudioFlinger::ThreadBase::releaseWakeLock_l()
1345{
1346 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001347 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001348 if (mPowerManager != 0) {
1349 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1350 }
1351 mWakeLockToken.clear();
1352 }
1353}
1354
1355void AudioFlinger::ThreadBase::clearPowerManager()
1356{
1357 Mutex::Autolock _l(mLock);
1358 releaseWakeLock_l();
1359 mPowerManager.clear();
1360}
1361
1362void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1363{
1364 sp<ThreadBase> thread = mThread.promote();
1365 if (thread != 0) {
1366 thread->clearPowerManager();
1367 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001368 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001369}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001370
Eric Laurent59255e42011-07-27 19:49:51 -07001371void AudioFlinger::ThreadBase::setEffectSuspended(
1372 const effect_uuid_t *type, bool suspend, int sessionId)
1373{
1374 Mutex::Autolock _l(mLock);
1375 setEffectSuspended_l(type, suspend, sessionId);
1376}
1377
1378void AudioFlinger::ThreadBase::setEffectSuspended_l(
1379 const effect_uuid_t *type, bool suspend, int sessionId)
1380{
Glenn Kasten090f0192012-01-30 13:00:02 -08001381 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001382 if (chain != 0) {
1383 if (type != NULL) {
1384 chain->setEffectSuspended_l(type, suspend);
1385 } else {
1386 chain->setEffectSuspendedAll_l(suspend);
1387 }
1388 }
1389
1390 updateSuspendedSessions_l(type, suspend, sessionId);
1391}
1392
1393void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1394{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001395 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001396 if (index < 0) {
1397 return;
1398 }
1399
1400 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1401 mSuspendedSessions.editValueAt(index);
1402
1403 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001404 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001405 for (int j = 0; j < desc->mRefCount; j++) {
1406 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1407 chain->setEffectSuspendedAll_l(true);
1408 } else {
Steve Block3856b092011-10-20 11:56:00 +01001409 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001410 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001411 chain->setEffectSuspended_l(&desc->mType, true);
1412 }
1413 }
1414 }
1415}
1416
Eric Laurent59255e42011-07-27 19:49:51 -07001417void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1418 bool suspend,
1419 int sessionId)
1420{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001421 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001422
1423 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1424
1425 if (suspend) {
1426 if (index >= 0) {
1427 sessionEffects = mSuspendedSessions.editValueAt(index);
1428 } else {
1429 mSuspendedSessions.add(sessionId, sessionEffects);
1430 }
1431 } else {
1432 if (index < 0) {
1433 return;
1434 }
1435 sessionEffects = mSuspendedSessions.editValueAt(index);
1436 }
1437
1438
1439 int key = EffectChain::kKeyForSuspendAll;
1440 if (type != NULL) {
1441 key = type->timeLow;
1442 }
1443 index = sessionEffects.indexOfKey(key);
1444
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001445 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001446 if (suspend) {
1447 if (index >= 0) {
1448 desc = sessionEffects.valueAt(index);
1449 } else {
1450 desc = new SuspendedSessionDesc();
1451 if (type != NULL) {
1452 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1453 }
1454 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001455 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001456 }
1457 desc->mRefCount++;
1458 } else {
1459 if (index < 0) {
1460 return;
1461 }
1462 desc = sessionEffects.valueAt(index);
1463 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001464 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001465 sessionEffects.removeItemsAt(index);
1466 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001467 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001468 sessionId);
1469 mSuspendedSessions.removeItem(sessionId);
1470 }
1471 }
1472 }
1473 if (!sessionEffects.isEmpty()) {
1474 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1475 }
1476}
1477
1478void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1479 bool enabled,
1480 int sessionId)
1481{
1482 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001483 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1484}
Eric Laurent59255e42011-07-27 19:49:51 -07001485
Eric Laurenta85a74a2011-10-19 11:44:54 -07001486void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1487 bool enabled,
1488 int sessionId)
1489{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001490 if (mType != RECORD) {
1491 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1492 // another session. This gives the priority to well behaved effect control panels
1493 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001494 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1495 // global effects
1496 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001497 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1498 }
1499 }
Eric Laurent59255e42011-07-27 19:49:51 -07001500
1501 sp<EffectChain> chain = getEffectChain_l(sessionId);
1502 if (chain != 0) {
1503 chain->checkSuspendOnEffectEnabled(effect, enabled);
1504 }
1505}
1506
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507// ----------------------------------------------------------------------------
1508
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001509AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1510 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001511 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001512 uint32_t device,
1513 type_t type)
1514 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001515 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1516 // Assumes constructor is called by AudioFlinger with it's mLock held,
1517 // but it would be safer to explicitly pass initial masterMute as parameter
1518 mMasterMute(audioFlinger->masterMute_l()),
1519 // mStreamTypes[] initialized in constructor body
1520 mOutput(output),
1521 // Assumes constructor is called by AudioFlinger with it's mLock held,
1522 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001523 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001524 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001525 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001526 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001527 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001528 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001529 // index 0 is reserved for normal mixer's submix
1530 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531{
Glenn Kasten480b4682012-02-28 12:30:08 -08001532 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001533
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 readOutputParameters();
1535
Glenn Kasten263709e2012-01-06 08:40:01 -08001536 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001537 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1538 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1539 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001540 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1541 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001543 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1544 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545}
1546
1547AudioFlinger::PlaybackThread::~PlaybackThread()
1548{
1549 delete [] mMixBuffer;
1550}
1551
1552status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1553{
1554 dumpInternals(fd, args);
1555 dumpTracks(fd, args);
1556 dumpEffectChains(fd, args);
1557 return NO_ERROR;
1558}
1559
1560status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1561{
1562 const size_t SIZE = 256;
1563 char buffer[SIZE];
1564 String8 result;
1565
Glenn Kasten58912562012-04-03 10:45:00 -07001566 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1567 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1568 const stream_type_t *st = &mStreamTypes[i];
1569 if (i > 0) {
1570 result.appendFormat(", ");
1571 }
1572 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1573 if (st->mute) {
1574 result.append("M");
1575 }
1576 }
1577 result.append("\n");
1578 write(fd, result.string(), result.length());
1579 result.clear();
1580
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1582 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001583 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 for (size_t i = 0; i < mTracks.size(); ++i) {
1585 sp<Track> track = mTracks[i];
1586 if (track != 0) {
1587 track->dump(buffer, SIZE);
1588 result.append(buffer);
1589 }
1590 }
1591
1592 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1593 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001594 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001596 sp<Track> track = mActiveTracks[i].promote();
1597 if (track != 0) {
1598 track->dump(buffer, SIZE);
1599 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 }
1601 }
1602 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001603
1604 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1605 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1606 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1607 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1608
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 return NO_ERROR;
1610}
1611
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1613{
1614 const size_t SIZE = 256;
1615 char buffer[SIZE];
1616 String8 result;
1617
1618 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1623 result.append(buffer);
1624 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1625 result.append(buffer);
1626 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1627 result.append(buffer);
1628 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1629 result.append(buffer);
1630 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1631 result.append(buffer);
1632 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001633 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634
1635 dumpBase(fd, args);
1636
1637 return NO_ERROR;
1638}
1639
1640// Thread virtuals
1641status_t AudioFlinger::PlaybackThread::readyToRun()
1642{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001643 status_t status = initCheck();
1644 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001645 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001646 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001647 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001649 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650}
1651
1652void AudioFlinger::PlaybackThread::onFirstRef()
1653{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001654 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655}
1656
1657// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001658sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001660 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001662 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001663 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 int frameCount,
1665 const sp<IMemory>& sharedBuffer,
1666 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001668 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 status_t *status)
1670{
1671 sp<Track> track;
1672 status_t lStatus;
1673
Glenn Kasten73d22752012-03-19 13:38:30 -07001674 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1675
1676 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 if (flags & IAudioFlinger::TRACK_FAST) {
1678 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 // not timed
1680 (!isTimed) &&
1681 // either of these use cases:
1682 (
1683 // use case 1: shared buffer with any frame count
1684 (
1685 (sharedBuffer != 0)
1686 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001687 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001688 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001689 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001691 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001692 )
1693 ) &&
1694 // PCM data
1695 audio_is_linear_pcm(format) &&
1696 // mono or stereo
1697 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1698 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001699#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001700 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001701 (sampleRate == mSampleRate) &&
1702#endif
1703 // normal mixer has an associated fast mixer
1704 hasFastMixer() &&
1705 // there are sufficient fast track slots available
1706 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001707 // FIXME test that MixerThread for this fast track has a capable output HAL
1708 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001709 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1711 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001712 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001713 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001714 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001715 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001716 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001717 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001718 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1719 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1720 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1721 audio_is_linear_pcm(format),
1722 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001723 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001724 // For compatibility with AudioTrack calculation, buffer depth is forced
1725 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1726 // This is probably too conservative, but legacy application code may depend on it.
1727 // If you change this calculation, also review the start threshold which is related.
1728 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1729 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1730 if (minBufCount < 2) {
1731 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001732 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001733 int minFrameCount = mNormalFrameCount * minBufCount;
1734 if (frameCount < minFrameCount) {
1735 frameCount = minFrameCount;
1736 }
1737 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001738 }
1739
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001741 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1742 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001743 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001744 "for output %p with format %d",
1745 sampleRate, format, channelMask, mOutput, mFormat);
1746 lStatus = BAD_VALUE;
1747 goto Exit;
1748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 }
1750 } else {
1751 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1752 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001753 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 lStatus = BAD_VALUE;
1755 goto Exit;
1756 }
1757 }
1758
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001759 lStatus = initCheck();
1760 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001761 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 goto Exit;
1763 }
1764
1765 { // scope for mLock
1766 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001767
1768 // all tracks in same audio session must share the same routing strategy otherwise
1769 // conflicts will happen when tracks are moved from one output to another by audio policy
1770 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001771 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001772 for (size_t i = 0; i < mTracks.size(); ++i) {
1773 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001774 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001775 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001776 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001777 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001778 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001779 lStatus = BAD_VALUE;
1780 goto Exit;
1781 }
1782 }
1783 }
1784
John Grossman4ff14ba2012-02-08 16:37:41 -08001785 if (!isTimed) {
1786 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001787 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001788 } else {
1789 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1790 channelMask, frameCount, sharedBuffer, sessionId);
1791 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001792 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 lStatus = NO_MEMORY;
1794 goto Exit;
1795 }
1796 mTracks.add(track);
1797
1798 sp<EffectChain> chain = getEffectChain_l(sessionId);
1799 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001802 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001803 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 }
1805 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001806
1807#ifdef HAVE_REQUEST_PRIORITY
1808 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1809 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1810 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1811 // so ask activity manager to do this on our behalf
1812 int err = requestPriority(callingPid, tid, 1);
1813 if (err != 0) {
1814 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1815 1, callingPid, tid, err);
1816 }
1817 }
1818#endif
1819
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 lStatus = NO_ERROR;
1821
1822Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001823 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 *status = lStatus;
1825 }
1826 return track;
1827}
1828
Eric Laurente737cda2012-05-22 18:55:44 -07001829uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1830{
1831 if (mFastMixer != NULL) {
1832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1833 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1834 }
1835 return latency;
1836}
1837
1838uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1839{
1840 return latency;
1841}
1842
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843uint32_t AudioFlinger::PlaybackThread::latency() const
1844{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001845 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001846 return latency_l();
1847}
1848uint32_t AudioFlinger::PlaybackThread::latency_l() const
1849{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001850 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001851 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001852 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 return 0;
1854 }
1855}
1856
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857void AudioFlinger::PlaybackThread::setMasterVolume(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 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001865 Mutex::Autolock _l(mLock);
1866 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
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 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873}
1874
Glenn Kasten6637baa2012-01-09 09:40:36 -08001875void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001877 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879}
1880
Glenn Kastenfff6d712012-01-12 16:38:12 -08001881float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001883 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 return mStreamTypes[stream].volume;
1885}
1886
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887// addTrack_l() must be called with ThreadBase::mLock held
1888status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1889{
1890 status_t status = ALREADY_EXISTS;
1891
1892 // set retry count for buffer fill
1893 track->mRetryCount = kMaxTrackStartupRetries;
1894 if (mActiveTracks.indexOf(track) < 0) {
1895 // the track is newly added, make sure it fills up all its
1896 // buffers before playing. This is to ensure the client will
1897 // effectively get the latency it requested.
1898 track->mFillingUpStatus = Track::FS_FILLING;
1899 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001900 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 mActiveTracks.add(track);
1902 if (track->mainBuffer() != mMixBuffer) {
1903 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1904 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001905 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001906 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 }
1908 }
1909
1910 status = NO_ERROR;
1911 }
1912
Steve Block3856b092011-10-20 11:56:00 +01001913 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 mWaitWorkCV.broadcast();
1915
1916 return status;
1917}
1918
1919// destroyTrack_l() must be called with ThreadBase::mLock held
1920void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1921{
1922 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001923 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001925 removeTrack_l(track);
1926 }
1927}
1928
1929void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1930{
Eric Laurent29864602012-05-08 18:57:51 -07001931 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001932 mTracks.remove(track);
1933 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001934 // redundant as track is about to be destroyed, for dumpsys only
1935 track->mName = -1;
1936 if (track->isFastTrack()) {
1937 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001938 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1940 mFastTrackAvailMask |= 1 << index;
1941 // redundant as track is about to be destroyed, for dumpsys only
1942 track->mFastIndex = -1;
1943 }
Eric Laurentb469b942011-05-09 12:09:06 -07001944 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1945 if (chain != 0) {
1946 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 }
1948}
1949
1950String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1951{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001952 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001953 char *s;
1954
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001955 Mutex::Autolock _l(mLock);
1956 if (initCheck() != NO_ERROR) {
1957 return out_s8;
1958 }
1959
Dima Zavin799a70e2011-04-18 16:57:27 -07001960 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001961 out_s8 = String8(s);
1962 free(s);
1963 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964}
1965
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001966// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1968 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001969 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970
Steve Block3856b092011-10-20 11:56:00 +01001971 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972
1973 switch (event) {
1974 case AudioSystem::OUTPUT_OPENED:
1975 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001976 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 desc.samplingRate = mSampleRate;
1978 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001979 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 desc.latency = latency();
1981 param2 = &desc;
1982 break;
1983
1984 case AudioSystem::STREAM_CONFIG_CHANGED:
1985 param2 = &param;
1986 case AudioSystem::OUTPUT_CLOSED:
1987 default:
1988 break;
1989 }
1990 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1991}
1992
1993void AudioFlinger::PlaybackThread::readOutputParameters()
1994{
Dima Zavin799a70e2011-04-18 16:57:27 -07001995 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001996 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1997 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001998 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001999 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002000 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002001 if (mFrameCount & 15) {
2002 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2003 mFrameCount);
2004 }
2005
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002006 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002007 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002008 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002009 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002010 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2011 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2012 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2013 maxNormalFrameCount = maxNormalFrameCount & ~15;
2014 if (maxNormalFrameCount < minNormalFrameCount) {
2015 maxNormalFrameCount = minNormalFrameCount;
2016 }
2017 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2018 if (multiplier <= 1.0) {
2019 multiplier = 1.0;
2020 } else if (multiplier <= 2.0) {
2021 if (2 * mFrameCount <= maxNormalFrameCount) {
2022 multiplier = 2.0;
2023 } else {
2024 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2025 }
2026 } else {
2027 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2028 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2029 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2030 // FIXME this rounding up should not be done if no HAL SRC
2031 uint32_t truncMult = (uint32_t) multiplier;
2032 if ((truncMult & 1)) {
2033 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2034 ++truncMult;
2035 }
2036 }
2037 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002038 }
Glenn Kasten58912562012-04-03 10:45:00 -07002039 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002040 mNormalFrameCount = multiplier * mFrameCount;
2041 // round up to nearest 16 frames to satisfy AudioMixer
2042 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002043 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044
Glenn Kastene9dd0172012-01-27 18:08:45 -08002045 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002046 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2047 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048
Eric Laurentde070132010-07-13 04:45:46 -07002049 // force reconfiguration of effect chains and engines to take new buffer size and audio
2050 // parameters into account
2051 // Note that mLock is not held when readOutputParameters() is called from the constructor
2052 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2053 // matter.
2054 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2055 Vector< sp<EffectChain> > effectChains = mEffectChains;
2056 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002057 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059}
2060
Eric Laurente737cda2012-05-22 18:55:44 -07002061
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2063{
Glenn Kastena0d68332012-01-27 16:47:15 -08002064 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 return BAD_VALUE;
2066 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002067 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002068 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 return INVALID_OPERATION;
2070 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002071 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072
Dima Zavin799a70e2011-04-18 16:57:27 -07002073 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074}
2075
Eric Laurent39e94f82010-07-28 01:32:47 -07002076uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077{
2078 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002079 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002081 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 }
2083
2084 for (size_t i = 0; i < mTracks.size(); ++i) {
2085 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002086 if (sessionId == track->sessionId() &&
2087 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002088 result |= TRACK_SESSION;
2089 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 }
2091 }
2092
Eric Laurent39e94f82010-07-28 01:32:47 -07002093 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094}
2095
Eric Laurentde070132010-07-13 04:45:46 -07002096uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2097{
Dima Zavinfce7a472011-04-19 22:30:36 -07002098 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002099 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002100 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2101 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002102 }
2103 for (size_t i = 0; i < mTracks.size(); i++) {
2104 sp<Track> track = mTracks[i];
2105 if (sessionId == track->sessionId() &&
2106 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002107 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002108 }
2109 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002110 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002111}
2112
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113
Glenn Kastenaed850d2012-01-26 09:46:34 -08002114AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002115{
2116 Mutex::Autolock _l(mLock);
2117 return mOutput;
2118}
2119
2120AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2121{
2122 Mutex::Autolock _l(mLock);
2123 AudioStreamOut *output = mOutput;
2124 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002125 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2126 // must push a NULL and wait for ack
2127 mOutputSink.clear();
2128 mPipeSink.clear();
2129 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002130 return output;
2131}
2132
2133// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002134audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002135{
2136 if (mOutput == NULL) {
2137 return NULL;
2138 }
2139 return &mOutput->stream->common;
2140}
2141
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002142uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002143{
Eric Laurentab9071b2012-06-04 13:45:29 -07002144 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002145}
2146
Eric Laurenta011e352012-03-29 15:51:43 -07002147status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2148{
2149 if (!isValidSyncEvent(event)) {
2150 return BAD_VALUE;
2151 }
2152
2153 Mutex::Autolock _l(mLock);
2154
2155 for (size_t i = 0; i < mTracks.size(); ++i) {
2156 sp<Track> track = mTracks[i];
2157 if (event->triggerSession() == track->sessionId()) {
2158 track->setSyncEvent(event);
2159 return NO_ERROR;
2160 }
2161 }
2162
2163 return NAME_NOT_FOUND;
2164}
2165
2166bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2167{
2168 switch (event->type()) {
2169 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2170 return true;
2171 default:
2172 break;
2173 }
2174 return false;
2175}
2176
Eric Laurent44a957f2012-05-15 15:26:05 -07002177void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2178{
2179 size_t count = tracksToRemove.size();
2180 if (CC_UNLIKELY(count)) {
2181 for (size_t i = 0 ; i < count ; i++) {
2182 const sp<Track>& track = tracksToRemove.itemAt(i);
2183 if ((track->sharedBuffer() != 0) &&
2184 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2185 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2186 }
2187 }
2188 }
2189
2190}
2191
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192// ----------------------------------------------------------------------------
2193
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002194AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002195 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002196 : PlaybackThread(audioFlinger, output, id, device, type),
2197 // mAudioMixer below
2198#ifdef SOAKER
2199 mSoaker(NULL),
2200#endif
2201 // mFastMixer below
2202 mFastMixerFutex(0)
2203 // mOutputSink below
2204 // mPipeSink below
2205 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206{
Glenn Kasten58912562012-04-03 10:45:00 -07002207 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2208 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2209 "mFrameCount=%d, mNormalFrameCount=%d",
2210 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2211 mNormalFrameCount);
2212 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2213
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 // FIXME - Current mixer implementation only supports stereo output
2215 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002216 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 }
Glenn Kasten58912562012-04-03 10:45:00 -07002218
2219 // create an NBAIO sink for the HAL output stream, and negotiate
2220 mOutputSink = new AudioStreamOutSink(output->stream);
2221 size_t numCounterOffers = 0;
2222 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2223 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2224 ALOG_ASSERT(index == 0);
2225
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002226 // initialize fast mixer depending on configuration
2227 bool initFastMixer;
2228 switch (kUseFastMixer) {
2229 case FastMixer_Never:
2230 initFastMixer = false;
2231 break;
2232 case FastMixer_Always:
2233 initFastMixer = true;
2234 break;
2235 case FastMixer_Static:
2236 case FastMixer_Dynamic:
2237 initFastMixer = mFrameCount < mNormalFrameCount;
2238 break;
2239 }
2240 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002241
2242 // create a MonoPipe to connect our submix to FastMixer
2243 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002244 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2245 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2246 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2247 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002248 const NBAIO_Format offers[1] = {format};
2249 size_t numCounterOffers = 0;
2250 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2251 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002252 monoPipe->setAvgFrames((mScreenState & 1) ?
2253 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002254 mPipeSink = monoPipe;
2255
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002256#ifdef TEE_SINK_FRAMES
2257 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2258 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2259 numCounterOffers = 0;
2260 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2261 ALOG_ASSERT(index == 0);
2262 mTeeSink = teeSink;
2263 PipeReader *teeSource = new PipeReader(*teeSink);
2264 numCounterOffers = 0;
2265 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2266 ALOG_ASSERT(index == 0);
2267 mTeeSource = teeSource;
2268#endif
2269
Glenn Kasten58912562012-04-03 10:45:00 -07002270#ifdef SOAKER
2271 // create a soaker as workaround for governor issues
2272 mSoaker = new Soaker();
2273 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2274 mSoaker->run("Soaker", PRIORITY_LOWEST);
2275#endif
2276
2277 // create fast mixer and configure it initially with just one fast track for our submix
2278 mFastMixer = new FastMixer();
2279 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002280#ifdef STATE_QUEUE_DUMP
2281 sq->setObserverDump(&mStateQueueObserverDump);
2282 sq->setMutatorDump(&mStateQueueMutatorDump);
2283#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002284 FastMixerState *state = sq->begin();
2285 FastTrack *fastTrack = &state->mFastTracks[0];
2286 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2287 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2288 fastTrack->mVolumeProvider = NULL;
2289 fastTrack->mGeneration++;
2290 state->mFastTracksGen++;
2291 state->mTrackMask = 1;
2292 // fast mixer will use the HAL output sink
2293 state->mOutputSink = mOutputSink.get();
2294 state->mOutputSinkGen++;
2295 state->mFrameCount = mFrameCount;
2296 state->mCommand = FastMixerState::COLD_IDLE;
2297 // already done in constructor initialization list
2298 //mFastMixerFutex = 0;
2299 state->mColdFutexAddr = &mFastMixerFutex;
2300 state->mColdGen++;
2301 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002302 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002303 sq->end();
2304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2305
2306 // start the fast mixer
2307 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2308#ifdef HAVE_REQUEST_PRIORITY
2309 pid_t tid = mFastMixer->getTid();
2310 int err = requestPriority(getpid_cached, tid, 2);
2311 if (err != 0) {
2312 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2313 2, getpid_cached, tid, err);
2314 }
2315#endif
2316
Glenn Kastenc15d6652012-05-30 14:52:57 -07002317#ifdef AUDIO_WATCHDOG
2318 // create and start the watchdog
2319 mAudioWatchdog = new AudioWatchdog();
2320 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2321 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2322 tid = mAudioWatchdog->getTid();
2323 err = requestPriority(getpid_cached, tid, 1);
2324 if (err != 0) {
2325 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2326 1, getpid_cached, tid, err);
2327 }
2328#endif
2329
Glenn Kasten58912562012-04-03 10:45:00 -07002330 } else {
2331 mFastMixer = NULL;
2332 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002333
2334 switch (kUseFastMixer) {
2335 case FastMixer_Never:
2336 case FastMixer_Dynamic:
2337 mNormalSink = mOutputSink;
2338 break;
2339 case FastMixer_Always:
2340 mNormalSink = mPipeSink;
2341 break;
2342 case FastMixer_Static:
2343 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2344 break;
2345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346}
2347
2348AudioFlinger::MixerThread::~MixerThread()
2349{
Glenn Kasten58912562012-04-03 10:45:00 -07002350 if (mFastMixer != NULL) {
2351 FastMixerStateQueue *sq = mFastMixer->sq();
2352 FastMixerState *state = sq->begin();
2353 if (state->mCommand == FastMixerState::COLD_IDLE) {
2354 int32_t old = android_atomic_inc(&mFastMixerFutex);
2355 if (old == -1) {
2356 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2357 }
2358 }
2359 state->mCommand = FastMixerState::EXIT;
2360 sq->end();
2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2362 mFastMixer->join();
2363 // Though the fast mixer thread has exited, it's state queue is still valid.
2364 // We'll use that extract the final state which contains one remaining fast track
2365 // corresponding to our sub-mix.
2366 state = sq->begin();
2367 ALOG_ASSERT(state->mTrackMask == 1);
2368 FastTrack *fastTrack = &state->mFastTracks[0];
2369 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2370 delete fastTrack->mBufferProvider;
2371 sq->end(false /*didModify*/);
2372 delete mFastMixer;
2373#ifdef SOAKER
2374 if (mSoaker != NULL) {
2375 mSoaker->requestExitAndWait();
2376 }
2377 delete mSoaker;
2378#endif
Glenn Kastenc15d6652012-05-30 14:52:57 -07002379 if (mAudioWatchdog != 0) {
2380 mAudioWatchdog->requestExit();
2381 mAudioWatchdog->requestExitAndWait();
2382 mAudioWatchdog.clear();
2383 }
Glenn Kasten58912562012-04-03 10:45:00 -07002384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 delete mAudioMixer;
2386}
2387
Glenn Kasten83efdd02012-02-24 07:21:32 -08002388class CpuStats {
2389public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390 CpuStats();
2391 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002392#ifdef DEBUG_CPU_USAGE
2393private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2395 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2396
2397 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2398
2399 int mCpuNum; // thread's current CPU number
2400 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401#endif
2402};
2403
Glenn Kasten190a46f2012-03-06 11:27:10 -08002404CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002405#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002406 : mCpuNum(-1), mCpukHz(-1)
2407#endif
2408{
2409}
2410
2411void CpuStats::sample(const String8 &title) {
2412#ifdef DEBUG_CPU_USAGE
2413 // get current thread's delta CPU time in wall clock ns
2414 double wcNs;
2415 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2416
2417 // record sample for wall clock statistics
2418 if (valid) {
2419 mWcStats.sample(wcNs);
2420 }
2421
2422 // get the current CPU number
2423 int cpuNum = sched_getcpu();
2424
2425 // get the current CPU frequency in kHz
2426 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2427
2428 // check if either CPU number or frequency changed
2429 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2430 mCpuNum = cpuNum;
2431 mCpukHz = cpukHz;
2432 // ignore sample for purposes of cycles
2433 valid = false;
2434 }
2435
2436 // if no change in CPU number or frequency, then record sample for cycle statistics
2437 if (valid && mCpukHz > 0) {
2438 double cycles = wcNs * cpukHz * 0.000001;
2439 mHzStats.sample(cycles);
2440 }
2441
2442 unsigned n = mWcStats.n();
2443 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002444 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002446 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2447 double perLoop = elapsed / (double) n;
2448 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002449 double perLoop1k = perLoop * 0.001;
2450 double mean = mWcStats.mean();
2451 double stddev = mWcStats.stddev();
2452 double minimum = mWcStats.minimum();
2453 double maximum = mWcStats.maximum();
2454 double meanCycles = mHzStats.mean();
2455 double stddevCycles = mHzStats.stddev();
2456 double minCycles = mHzStats.minimum();
2457 double maxCycles = mHzStats.maximum();
2458 mCpuUsage.resetElapsed();
2459 mWcStats.reset();
2460 mHzStats.reset();
2461 ALOGD("CPU usage for %s over past %.1f secs\n"
2462 " (%u mixer loops at %.1f mean ms per loop):\n"
2463 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2464 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2465 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2466 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002467 elapsed * .000000001, n, perLoop * .000001,
2468 mean * .001,
2469 stddev * .001,
2470 minimum * .001,
2471 maximum * .001,
2472 mean / perLoop100,
2473 stddev / perLoop100,
2474 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002475 maximum / perLoop100,
2476 meanCycles / perLoop1k,
2477 stddevCycles / perLoop1k,
2478 minCycles / perLoop1k,
2479 maxCycles / perLoop1k);
2480
Glenn Kasten83efdd02012-02-24 07:21:32 -08002481 }
2482 }
2483#endif
2484};
2485
Glenn Kasten37d825e2012-02-24 07:21:48 -08002486void AudioFlinger::PlaybackThread::checkSilentMode_l()
2487{
2488 if (!mMasterMute) {
2489 char value[PROPERTY_VALUE_MAX];
2490 if (property_get("ro.audio.silent", value, "0") > 0) {
2491 char *endptr;
2492 unsigned long ul = strtoul(value, &endptr, 0);
2493 if (*endptr == '\0' && ul != 0) {
2494 ALOGD("Silence is golden");
2495 // The setprop command will not allow a property to be changed after
2496 // the first time it is set, so we don't have to worry about un-muting.
2497 setMasterMute_l(true);
2498 }
2499 }
2500 }
2501}
2502
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504{
2505 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002506
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
2509 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002511
Glenn Kasten000f0e32012-03-01 17:10:56 -08002512 // DUPLICATING
2513 // FIXME could this be made local to while loop?
2514 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002515
Glenn Kasten66fcab92012-02-24 14:59:21 -08002516 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002517 sleepTime = idleSleepTime;
2518
2519if (mType == MIXER) {
2520 sleepTimeShift = 0;
2521}
2522
Glenn Kasten83efdd02012-02-24 07:21:32 -08002523 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002524 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525
Eric Laurentfeb0db62011-07-22 09:04:31 -07002526 acquireWakeLock();
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 while (!exitPending())
2529 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002530 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002531
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002532 Vector< sp<EffectChain> > effectChains;
2533
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 processConfigEvents();
2535
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 { // scope for mLock
2537
2538 Mutex::Autolock _l(mLock);
2539
2540 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002541 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 }
2543
Glenn Kastenfa26a852012-03-06 11:28:04 -08002544 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002545
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002547 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002548 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002550
2551 threadLoop_standby();
2552
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 mStandby = true;
2554 mBytesWritten = 0;
2555 }
2556
Glenn Kasten3e074702012-02-28 18:40:35 -08002557 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 // we're about to wait, flush the binder command buffer
2559 IPCThreadState::self()->flushCommands();
2560
Glenn Kastenfa26a852012-03-06 11:28:04 -08002561 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002562
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 if (exitPending()) break;
2564
Eric Laurentfeb0db62011-07-22 09:04:31 -07002565 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002567 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002569 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002570 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571
Eric Laurentda747442012-04-25 18:53:13 -07002572 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002573 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002574
Glenn Kasten37d825e2012-02-24 07:21:48 -08002575 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002579 if (mType == MIXER) {
2580 sleepTimeShift = 0;
2581 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583 continue;
2584 }
2585 }
2586
Glenn Kasten81028042012-04-30 18:15:12 -07002587 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002588 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589
2590 // prevent any changes in effect chain list and in each effect chain
2591 // during mixing and effect process as the audio buffers could be deleted
2592 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002593 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002594 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595
Glenn Kastenfec279f2012-03-08 07:47:15 -08002596 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002597 threadLoop_mix();
2598 } else {
2599 threadLoop_sleepTime();
2600 }
2601
2602 if (mSuspended > 0) {
2603 sleepTime = suspendSleepTimeUs();
2604 }
2605
2606 // only process effects if we're going to write
2607 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002608 for (size_t i = 0; i < effectChains.size(); i ++) {
2609 effectChains[i]->process_l();
2610 }
2611 }
2612
2613 // enable changes in effect chain
2614 unlockEffectChains(effectChains);
2615
2616 // sleepTime == 0 means we must write to audio hardware
2617 if (sleepTime == 0) {
2618
2619 threadLoop_write();
2620
2621if (mType == MIXER) {
2622 // write blocked detection
2623 nsecs_t now = systemTime();
2624 nsecs_t delta = now - mLastWriteTime;
2625 if (!mStandby && delta > maxPeriod) {
2626 mNumDelayedWrites++;
2627 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002628#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002629 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002630#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002631 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2632 ns2ms(delta), mNumDelayedWrites, this);
2633 lastWarning = now;
2634 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635 }
2636}
2637
2638 mStandby = false;
2639 } else {
2640 usleep(sleepTime);
2641 }
2642
Glenn Kasten58912562012-04-03 10:45:00 -07002643 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002644 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002645 // same lock. This will also mutate and push a new fast mixer state.
2646 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002647 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648
Glenn Kastenfa26a852012-03-06 11:28:04 -08002649 // FIXME I don't understand the need for this here;
2650 // it was in the original code but maybe the
2651 // assignment in saveOutputTracks() makes this unnecessary?
2652 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002653
2654 // Effect chains will be actually deleted here if they were removed from
2655 // mEffectChains list during mixing or effects processing
2656 effectChains.clear();
2657
2658 // FIXME Note that the above .clear() is no longer necessary since effectChains
2659 // is now local to this block, but will keep it for now (at least until merge done).
2660 }
2661
2662if (mType == MIXER || mType == DIRECT) {
2663 // put output stream into standby mode
2664 if (!mStandby) {
2665 mOutput->stream->common.standby(&mOutput->stream->common);
2666 }
2667}
2668if (mType == DUPLICATING) {
2669 // for DuplicatingThread, standby mode is handled by the outputTracks
2670}
2671
2672 releaseWakeLock();
2673
2674 ALOGV("Thread %p type %d exiting", this, mType);
2675 return false;
2676}
2677
Glenn Kasten58912562012-04-03 10:45:00 -07002678void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2679{
Glenn Kasten58912562012-04-03 10:45:00 -07002680 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2681}
2682
2683void AudioFlinger::MixerThread::threadLoop_write()
2684{
2685 // FIXME we should only do one push per cycle; confirm this is true
2686 // Start the fast mixer if it's not already running
2687 if (mFastMixer != NULL) {
2688 FastMixerStateQueue *sq = mFastMixer->sq();
2689 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002690 if (state->mCommand != FastMixerState::MIX_WRITE &&
2691 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002692 if (state->mCommand == FastMixerState::COLD_IDLE) {
2693 int32_t old = android_atomic_inc(&mFastMixerFutex);
2694 if (old == -1) {
2695 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2696 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002697 if (mAudioWatchdog != 0) {
2698 mAudioWatchdog->resume();
2699 }
Glenn Kasten58912562012-04-03 10:45:00 -07002700 }
2701 state->mCommand = FastMixerState::MIX_WRITE;
2702 sq->end();
2703 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002704 if (kUseFastMixer == FastMixer_Dynamic) {
2705 mNormalSink = mPipeSink;
2706 }
Glenn Kasten58912562012-04-03 10:45:00 -07002707 } else {
2708 sq->end(false /*didModify*/);
2709 }
2710 }
2711 PlaybackThread::threadLoop_write();
2712}
2713
Glenn Kasten000f0e32012-03-01 17:10:56 -08002714// shared by MIXER and DIRECT, overridden by DUPLICATING
2715void AudioFlinger::PlaybackThread::threadLoop_write()
2716{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002717 // FIXME rewrite to reduce number of system calls
2718 mLastWriteTime = systemTime();
2719 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002720 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002721
Eric Laurent67c0a582012-05-01 19:31:12 -07002722 // If an NBAIO sink is present, use it to write the normal mixer's submix
2723 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002724#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002725 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002726#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002727 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002728#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002729 // update the setpoint when gScreenState changes
2730 uint32_t screenState = gScreenState;
2731 if (screenState != mScreenState) {
2732 mScreenState = screenState;
2733 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2734 if (pipe != NULL) {
2735 pipe->setAvgFrames((mScreenState & 1) ?
2736 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2737 }
2738 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002739 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002740#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002741 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002742#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002743 if (framesWritten > 0) {
2744 bytesWritten = framesWritten << mBitShift;
2745 } else {
2746 bytesWritten = framesWritten;
2747 }
2748 // otherwise use the HAL / AudioStreamOut directly
2749 } else {
2750 // Direct output thread.
2751 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002752 }
2753
Eric Laurent67c0a582012-05-01 19:31:12 -07002754 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002755 mNumWrites++;
2756 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002757}
2758
Glenn Kasten58912562012-04-03 10:45:00 -07002759void AudioFlinger::MixerThread::threadLoop_standby()
2760{
2761 // Idle the fast mixer if it's currently running
2762 if (mFastMixer != NULL) {
2763 FastMixerStateQueue *sq = mFastMixer->sq();
2764 FastMixerState *state = sq->begin();
2765 if (!(state->mCommand & FastMixerState::IDLE)) {
2766 state->mCommand = FastMixerState::COLD_IDLE;
2767 state->mColdFutexAddr = &mFastMixerFutex;
2768 state->mColdGen++;
2769 mFastMixerFutex = 0;
2770 sq->end();
2771 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2772 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002773 if (kUseFastMixer == FastMixer_Dynamic) {
2774 mNormalSink = mOutputSink;
2775 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002776 if (mAudioWatchdog != 0) {
2777 mAudioWatchdog->pause();
2778 }
Glenn Kasten58912562012-04-03 10:45:00 -07002779 } else {
2780 sq->end(false /*didModify*/);
2781 }
2782 }
2783 PlaybackThread::threadLoop_standby();
2784}
2785
Glenn Kasten000f0e32012-03-01 17:10:56 -08002786// shared by MIXER and DIRECT, overridden by DUPLICATING
2787void AudioFlinger::PlaybackThread::threadLoop_standby()
2788{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2790 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002791}
2792
2793void AudioFlinger::MixerThread::threadLoop_mix()
2794{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002795 // obtain the presentation timestamp of the next output buffer
2796 int64_t pts;
2797 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002798
Glenn Kasten952eeb22012-03-06 11:30:57 -08002799 if (NULL != mOutput->stream->get_next_write_timestamp) {
2800 status = mOutput->stream->get_next_write_timestamp(
2801 mOutput->stream, &pts);
2802 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002803
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 if (status != NO_ERROR) {
2805 pts = AudioBufferProvider::kInvalidPTS;
2806 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002807
Glenn Kasten952eeb22012-03-06 11:30:57 -08002808 // mix buffers...
2809 mAudioMixer->process(pts);
2810 // increase sleep time progressively when application underrun condition clears.
2811 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2812 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2813 // such that we would underrun the audio HAL.
2814 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2815 sleepTimeShift--;
2816 }
2817 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002818 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002819 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002820}
2821
2822void AudioFlinger::MixerThread::threadLoop_sleepTime()
2823{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002824 // If no tracks are ready, sleep once for the duration of an output
2825 // buffer size, then write 0s to the output
2826 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002827 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002828 sleepTime = activeSleepTime >> sleepTimeShift;
2829 if (sleepTime < kMinThreadSleepTimeUs) {
2830 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 // reduce sleep time in case of consecutive application underruns to avoid
2833 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2834 // duration we would end up writing less data than needed by the audio HAL if
2835 // the condition persists.
2836 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2837 sleepTimeShift++;
2838 }
2839 } else {
2840 sleepTime = idleSleepTime;
2841 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002842 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002843 memset (mMixBuffer, 0, mixBufferSize);
2844 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002845 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002846 }
2847 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848}
2849
2850// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002851AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002852 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853{
2854
Glenn Kasten29c23c32012-01-26 13:37:52 -08002855 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002857 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 size_t mixedTracks = 0;
2859 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002860 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002861 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002862 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863
2864 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002865 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866
Eric Laurent571d49c2010-08-11 05:20:11 -07002867 if (masterMute) {
2868 masterVolume = 0;
2869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002871 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002873 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002874 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 masterVolume = (float)((v + (1 << 23)) >> 24);
2876 chain.clear();
2877 }
2878
Glenn Kasten288ed212012-04-25 17:52:27 -07002879 // prepare a new state to push
2880 FastMixerStateQueue *sq = NULL;
2881 FastMixerState *state = NULL;
2882 bool didModify = false;
2883 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2884 if (mFastMixer != NULL) {
2885 sq = mFastMixer->sq();
2886 state = sq->begin();
2887 }
2888
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002890 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 if (t == 0) continue;
2892
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002893 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002895
Glenn Kasten288ed212012-04-25 17:52:27 -07002896 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002897 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002898
2899 // It's theoretically possible (though unlikely) for a fast track to be created
2900 // and then removed within the same normal mix cycle. This is not a problem, as
2901 // the track never becomes active so it's fast mixer slot is never touched.
2902 // The converse, of removing an (active) track and then creating a new track
2903 // at the identical fast mixer slot within the same normal mix cycle,
2904 // is impossible because the slot isn't marked available until the end of each cycle.
2905 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002906 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2907 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002908 FastTrack *fastTrack = &state->mFastTracks[j];
2909
2910 // Determine whether the track is currently in underrun condition,
2911 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002912 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2913 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002914 uint32_t recentFull = (underruns.mBitFields.mFull -
2915 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2916 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2917 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2918 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2919 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2920 uint32_t recentUnderruns = recentPartial + recentEmpty;
2921 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002922 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002923 // or stopped which can occur when flush() is called while active
2924 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002925 track->mUnderrunCount += recentUnderruns;
2926 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002927
Glenn Kastend08f48c2012-05-01 18:14:02 -07002928 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002929 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002930 bool isActive = true;
2931 switch (track->mState) {
2932 case TrackBase::STOPPING_1:
2933 // track stays active in STOPPING_1 state until first underrun
2934 if (recentUnderruns > 0) {
2935 track->mState = TrackBase::STOPPING_2;
2936 }
2937 break;
2938 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002940 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002941 break;
2942 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002943 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002944 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002945 break;
2946 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002947 if (recentFull > 0 || recentPartial > 0) {
2948 // track has provided at least some frames recently: reset retry count
2949 track->mRetryCount = kMaxTrackRetries;
2950 }
2951 if (recentUnderruns == 0) {
2952 // no recent underruns: stay active
2953 break;
2954 }
2955 // there has recently been an underrun of some kind
2956 if (track->sharedBuffer() == 0) {
2957 // were any of the recent underruns "empty" (no frames available)?
2958 if (recentEmpty == 0) {
2959 // no, then ignore the partial underruns as they are allowed indefinitely
2960 break;
2961 }
2962 // there has recently been an "empty" underrun: decrement the retry counter
2963 if (--(track->mRetryCount) > 0) {
2964 break;
2965 }
2966 // indicate to client process that the track was disabled because of underrun;
2967 // it will then automatically call start() when data is available
2968 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2969 // remove from active list, but state remains ACTIVE [confusing but true]
2970 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002971 break;
2972 }
2973 // fall through
2974 case TrackBase::STOPPING_2:
2975 case TrackBase::PAUSED:
2976 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002977 case TrackBase::STOPPED:
2978 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002979 // Check for presentation complete if track is inactive
2980 // We have consumed all the buffers of this track.
2981 // This would be incomplete if we auto-paused on underrun
2982 {
2983 size_t audioHALFrames =
2984 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2985 size_t framesWritten =
2986 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2987 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2988 // track stays in active list until presentation is complete
2989 break;
2990 }
2991 }
2992 if (track->isStopping_2()) {
2993 track->mState = TrackBase::STOPPED;
2994 }
2995 if (track->isStopped()) {
2996 // Can't reset directly, as fast mixer is still polling this track
2997 // track->reset();
2998 // So instead mark this track as needing to be reset after push with ack
2999 resetMask |= 1 << i;
3000 }
3001 isActive = false;
3002 break;
3003 case TrackBase::IDLE:
3004 default:
3005 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003006 }
3007
3008 if (isActive) {
3009 // was it previously inactive?
3010 if (!(state->mTrackMask & (1 << j))) {
3011 ExtendedAudioBufferProvider *eabp = track;
3012 VolumeProvider *vp = track;
3013 fastTrack->mBufferProvider = eabp;
3014 fastTrack->mVolumeProvider = vp;
3015 fastTrack->mSampleRate = track->mSampleRate;
3016 fastTrack->mChannelMask = track->mChannelMask;
3017 fastTrack->mGeneration++;
3018 state->mTrackMask |= 1 << j;
3019 didModify = true;
3020 // no acknowledgement required for newly active tracks
3021 }
3022 // cache the combined master volume and stream type volume for fast mixer; this
3023 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3024 track->mCachedVolume = track->isMuted() ?
3025 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3026 ++fastTracks;
3027 } else {
3028 // was it previously active?
3029 if (state->mTrackMask & (1 << j)) {
3030 fastTrack->mBufferProvider = NULL;
3031 fastTrack->mGeneration++;
3032 state->mTrackMask &= ~(1 << j);
3033 didModify = true;
3034 // If any fast tracks were removed, we must wait for acknowledgement
3035 // because we're about to decrement the last sp<> on those tracks.
3036 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003037 } else {
3038 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003039 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003040 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003041 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003042 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003043 }
3044 continue;
3045 }
3046
3047 { // local variable scope to avoid goto warning
3048
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 audio_track_cblk_t* cblk = track->cblk();
3050
3051 // The first time a track is added we wait
3052 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003053 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003054 // make sure that we have enough frames to mix one full buffer.
3055 // enforce this condition only once to enable draining the buffer in case the client
3056 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003057 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003058 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003059 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003060 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003061 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003062 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003063 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003064 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003065 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003066 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003067 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003068 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003069 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3070 // the minimum track buffer size is normally twice the number of frames necessary
3071 // to fill one buffer and the resampler should not leave more than one buffer worth
3072 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003073 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003074 }
3075 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003076 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 !track->isPaused() && !track->isTerminated())
3078 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003079 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080
3081 mixedTracks++;
3082
3083 // track->mainBuffer() != mMixBuffer means there is an effect chain
3084 // connected to the track
3085 chain.clear();
3086 if (track->mainBuffer() != mMixBuffer) {
3087 chain = getEffectChain_l(track->sessionId());
3088 // Delegate volume control to effect in track effect chain if needed
3089 if (chain != 0) {
3090 tracksWithEffect++;
3091 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003092 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003093 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
3095 }
3096
3097
3098 int param = AudioMixer::VOLUME;
3099 if (track->mFillingUpStatus == Track::FS_FILLED) {
3100 // no ramp for the first volume setting
3101 track->mFillingUpStatus = Track::FS_ACTIVE;
3102 if (track->mState == TrackBase::RESUMING) {
3103 track->mState = TrackBase::ACTIVE;
3104 param = AudioMixer::RAMP_VOLUME;
3105 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003106 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 } else if (cblk->server != 0) {
3108 // If the track is stopped before the first frame was mixed,
3109 // do not apply ramp
3110 param = AudioMixer::RAMP_VOLUME;
3111 }
3112
3113 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003114 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003115 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003116 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003117 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 if (track->isPausing()) {
3119 track->setPaused();
3120 }
3121 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003122
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003124 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003126 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003127 vl = vlr & 0xFFFF;
3128 vr = vlr >> 16;
3129 // track volumes come from shared memory, so can't be trusted and must be clamped
3130 if (vl > MAX_GAIN_INT) {
3131 ALOGV("Track left volume out of range: %04X", vl);
3132 vl = MAX_GAIN_INT;
3133 }
3134 if (vr > MAX_GAIN_INT) {
3135 ALOGV("Track right volume out of range: %04X", vr);
3136 vr = MAX_GAIN_INT;
3137 }
3138 // now apply the master volume and stream type volume
3139 vl = (uint32_t)(v * vl) << 12;
3140 vr = (uint32_t)(v * vr) << 12;
3141 // assuming master volume and stream type volume each go up to 1.0,
3142 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143
Glenn Kasten05632a52012-01-03 14:22:33 -08003144 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3145 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003146 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003147 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003148 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003149 }
3150 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003152 // Delegate volume control to effect in track effect chain if needed
3153 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3154 // Do not ramp volume if volume is controlled by effect
3155 param = AudioMixer::VOLUME;
3156 track->mHasVolumeController = true;
3157 } else {
3158 // force no volume ramp when volume controller was just disabled or removed
3159 // from effect chain to avoid volume spike
3160 if (track->mHasVolumeController) {
3161 param = AudioMixer::VOLUME;
3162 }
3163 track->mHasVolumeController = false;
3164 }
3165
3166 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003167 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003168 vl = (vl + (1 << 11)) >> 12;
3169 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3170 vr = (vr + (1 << 11)) >> 12;
3171 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003172
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003173 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003176 mAudioMixer->setBufferProvider(name, track);
3177 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003179 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3180 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3181 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003183 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 AudioMixer::TRACK,
3185 AudioMixer::FORMAT, (void *)track->format());
3186 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003187 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003189 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 AudioMixer::RESAMPLE,
3193 AudioMixer::SAMPLE_RATE,
3194 (void *)(cblk->sampleRate));
3195 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003196 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 AudioMixer::TRACK,
3198 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3199 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003200 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 AudioMixer::TRACK,
3202 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3203
3204 // reset retry count
3205 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003206
Eric Laurent27741442012-01-17 19:20:12 -08003207 // If one track is ready, set the mixer ready if:
3208 // - the mixer was not ready during previous round OR
3209 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003210 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003211 mixerStatus != MIXER_TRACKS_ENABLED) {
3212 mixerStatus = MIXER_TRACKS_READY;
3213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003215 // clear effect chain input buffer if an active track underruns to avoid sending
3216 // previous audio buffer again to effects
3217 chain = getEffectChain_l(track->sessionId());
3218 if (chain != 0) {
3219 chain->clearInputBuffer();
3220 }
3221
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003222 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003223 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3224 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 // We have consumed all the buffers of this track.
3226 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003227 // TODO: use actual buffer filling status instead of latency when available from
3228 // audio HAL
3229 size_t audioHALFrames =
3230 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3231 size_t framesWritten =
3232 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3233 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003234 if (track->isStopped()) {
3235 track->reset();
3236 }
Eric Laurenta011e352012-03-29 15:51:43 -07003237 tracksToRemove->add(track);
3238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003240 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 // No buffers for this track. Give it a few chances to
3242 // fill a buffer, then remove it from active list.
3243 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003244 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003246 // indicate to client process that the track was disabled because of underrun;
3247 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003248 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003249 // If one track is not ready, mark the mixer also not ready if:
3250 // - the mixer was ready during previous round OR
3251 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003252 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003253 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 mixerStatus = MIXER_TRACKS_ENABLED;
3255 }
3256 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003257 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 }
Glenn Kasten58912562012-04-03 10:45:00 -07003259
3260 } // local variable scope to avoid goto warning
3261track_is_ready: ;
3262
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 }
3264
Glenn Kasten288ed212012-04-25 17:52:27 -07003265 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003266 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003267 if (didModify) {
3268 state->mFastTracksGen++;
3269 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3270 if (kUseFastMixer == FastMixer_Dynamic &&
3271 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3272 state->mCommand = FastMixerState::COLD_IDLE;
3273 state->mColdFutexAddr = &mFastMixerFutex;
3274 state->mColdGen++;
3275 mFastMixerFutex = 0;
3276 if (kUseFastMixer == FastMixer_Dynamic) {
3277 mNormalSink = mOutputSink;
3278 }
3279 // If we go into cold idle, need to wait for acknowledgement
3280 // so that fast mixer stops doing I/O.
3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003282 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003283 }
3284 sq->end();
3285 }
3286 if (sq != NULL) {
3287 sq->end(didModify);
3288 sq->push(block);
3289 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003290 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3291 mAudioWatchdog->pause();
3292 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003293
3294 // Now perform the deferred reset on fast tracks that have stopped
3295 while (resetMask != 0) {
3296 size_t i = __builtin_ctz(resetMask);
3297 ALOG_ASSERT(i < count);
3298 resetMask &= ~(1 << i);
3299 sp<Track> t = mActiveTracks[i].promote();
3300 if (t == 0) continue;
3301 Track* track = t.get();
3302 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3303 track->reset();
3304 }
Glenn Kasten58912562012-04-03 10:45:00 -07003305
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 // remove all the tracks that need to be...
3307 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003308 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 for (size_t i=0 ; i<count ; i++) {
3310 const sp<Track>& track = tracksToRemove->itemAt(i);
3311 mActiveTracks.remove(track);
3312 if (track->mainBuffer() != mMixBuffer) {
3313 chain = getEffectChain_l(track->sessionId());
3314 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003315 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003316 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318 }
3319 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003320 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 }
3322 }
3323 }
3324
3325 // mix buffer must be cleared if all tracks are connected to an
3326 // effect chain as in this case the mixer will not write to
3327 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003328 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3329 // FIXME as a performance optimization, should remember previous zero status
3330 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 }
3332
Glenn Kasten58912562012-04-03 10:45:00 -07003333 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003334 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003335 if (fastTracks > 0) {
3336 mixerStatus = MIXER_TRACKS_READY;
3337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 return mixerStatus;
3339}
3340
Glenn Kasten66fcab92012-02-24 14:59:21 -08003341/*
3342The derived values that are cached:
3343 - mixBufferSize from frame count * frame size
3344 - activeSleepTime from activeSleepTimeUs()
3345 - idleSleepTime from idleSleepTimeUs()
3346 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3347 - maxPeriod from frame count and sample rate (MIXER only)
3348
3349The parameters that affect these derived values are:
3350 - frame count
3351 - frame size
3352 - sample rate
3353 - device type: A2DP or not
3354 - device latency
3355 - format: PCM or not
3356 - active sleep time
3357 - idle sleep time
3358*/
3359
3360void AudioFlinger::PlaybackThread::cacheParameters_l()
3361{
Glenn Kasten58912562012-04-03 10:45:00 -07003362 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003363 activeSleepTime = activeSleepTimeUs();
3364 idleSleepTime = idleSleepTimeUs();
3365}
3366
Eric Laurent22167852012-06-20 12:26:32 -07003367void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368{
Steve Block3856b092011-10-20 11:56:00 +01003369 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003370 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003372
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 size_t size = mTracks.size();
3374 for (size_t i = 0; i < size; i++) {
3375 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003376 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003377 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 }
3380 }
3381}
3382
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003384int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003386 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387}
3388
3389// deleteTrackName_l() must be called with ThreadBase::mLock held
3390void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3391{
Steve Block3856b092011-10-20 11:56:00 +01003392 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 mAudioMixer->deleteTrackName(name);
3394}
3395
3396// checkForNewParameters_l() must be called with ThreadBase::mLock held
3397bool AudioFlinger::MixerThread::checkForNewParameters_l()
3398{
Glenn Kasten58912562012-04-03 10:45:00 -07003399 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3400 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 bool reconfig = false;
3402
3403 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003404
3405 if (mFastMixer != NULL) {
3406 FastMixerStateQueue *sq = mFastMixer->sq();
3407 FastMixerState *state = sq->begin();
3408 if (!(state->mCommand & FastMixerState::IDLE)) {
3409 previousCommand = state->mCommand;
3410 state->mCommand = FastMixerState::HOT_IDLE;
3411 sq->end();
3412 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3413 } else {
3414 sq->end(false /*didModify*/);
3415 }
3416 }
3417
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 status_t status = NO_ERROR;
3419 String8 keyValuePair = mNewParameters[0];
3420 AudioParameter param = AudioParameter(keyValuePair);
3421 int value;
3422
3423 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3424 reconfig = true;
3425 }
3426 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003427 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 status = BAD_VALUE;
3429 } else {
3430 reconfig = true;
3431 }
3432 }
3433 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003434 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 status = BAD_VALUE;
3436 } else {
3437 reconfig = true;
3438 }
3439 }
3440 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3441 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003442 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 // if frame count is changed after track creation
3444 if (!mTracks.isEmpty()) {
3445 status = INVALID_OPERATION;
3446 } else {
3447 reconfig = true;
3448 }
3449 }
3450 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003451#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003452 // when changing the audio output device, call addBatteryData to notify
3453 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003454 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003455 uint32_t params = 0;
3456 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003457 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003458 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3459 }
3460
3461 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003462 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003463 // check if any other device (except speaker) is on
3464 if (value & deviceWithoutSpeaker ) {
3465 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3466 }
3467
3468 if (params != 0) {
3469 addBatteryData(params);
3470 }
3471 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003472#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003473
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 // forward device change to effects that have requested to be
3475 // aware of attached audio device.
3476 mDevice = (uint32_t)value;
3477 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003478 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 }
3480 }
3481
3482 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003483 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003484 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003486 mOutput->stream->common.standby(&mOutput->stream->common);
3487 mStandby = true;
3488 mBytesWritten = 0;
3489 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003490 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 }
3492 if (status == NO_ERROR && reconfig) {
3493 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003494 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3495 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003497 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003499 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 if (name < 0) break;
3501 mTracks[i]->mName = name;
3502 // limit track sample rate to 2 x new output sample rate
3503 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3504 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3505 }
3506 }
3507 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3508 }
3509 }
3510
3511 mNewParameters.removeAt(0);
3512
3513 mParamStatus = status;
3514 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003515 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3516 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003517 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 }
Glenn Kasten58912562012-04-03 10:45:00 -07003519
3520 if (!(previousCommand & FastMixerState::IDLE)) {
3521 ALOG_ASSERT(mFastMixer != NULL);
3522 FastMixerStateQueue *sq = mFastMixer->sq();
3523 FastMixerState *state = sq->begin();
3524 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3525 state->mCommand = previousCommand;
3526 sq->end();
3527 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3528 }
3529
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 return reconfig;
3531}
3532
3533status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3534{
3535 const size_t SIZE = 256;
3536 char buffer[SIZE];
3537 String8 result;
3538
3539 PlaybackThread::dumpInternals(fd, args);
3540
3541 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3542 result.append(buffer);
3543 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003544
3545 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3546 FastMixerDumpState copy = mFastMixerDumpState;
3547 copy.dump(fd);
3548
Glenn Kasten39993082012-05-31 13:40:27 -07003549#ifdef STATE_QUEUE_DUMP
3550 // Similar for state queue
3551 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3552 observerCopy.dump(fd);
3553 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3554 mutatorCopy.dump(fd);
3555#endif
3556
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003557 // Write the tee output to a .wav file
3558 NBAIO_Source *teeSource = mTeeSource.get();
3559 if (teeSource != NULL) {
3560 char teePath[64];
3561 struct timeval tv;
3562 gettimeofday(&tv, NULL);
3563 struct tm tm;
3564 localtime_r(&tv.tv_sec, &tm);
3565 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3566 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3567 if (teeFd >= 0) {
3568 char wavHeader[44];
3569 memcpy(wavHeader,
3570 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3571 sizeof(wavHeader));
3572 NBAIO_Format format = teeSource->format();
3573 unsigned channelCount = Format_channelCount(format);
3574 ALOG_ASSERT(channelCount <= FCC_2);
3575 unsigned sampleRate = Format_sampleRate(format);
3576 wavHeader[22] = channelCount; // number of channels
3577 wavHeader[24] = sampleRate; // sample rate
3578 wavHeader[25] = sampleRate >> 8;
3579 wavHeader[32] = channelCount * 2; // block alignment
3580 write(teeFd, wavHeader, sizeof(wavHeader));
3581 size_t total = 0;
3582 bool firstRead = true;
3583 for (;;) {
3584#define TEE_SINK_READ 1024
3585 short buffer[TEE_SINK_READ * FCC_2];
3586 size_t count = TEE_SINK_READ;
3587 ssize_t actual = teeSource->read(buffer, count);
3588 bool wasFirstRead = firstRead;
3589 firstRead = false;
3590 if (actual <= 0) {
3591 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3592 continue;
3593 }
3594 break;
3595 }
3596 ALOG_ASSERT(actual <= count);
3597 write(teeFd, buffer, actual * channelCount * sizeof(short));
3598 total += actual;
3599 }
3600 lseek(teeFd, (off_t) 4, SEEK_SET);
3601 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3602 write(teeFd, &temp, sizeof(temp));
3603 lseek(teeFd, (off_t) 40, SEEK_SET);
3604 temp = total * channelCount * sizeof(short);
3605 write(teeFd, &temp, sizeof(temp));
3606 close(teeFd);
3607 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3608 } else {
3609 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3610 }
3611 }
3612
Glenn Kastenc15d6652012-05-30 14:52:57 -07003613 if (mAudioWatchdog != 0) {
3614 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3615 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3616 wdCopy.dump(fd);
3617 }
3618
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 return NO_ERROR;
3620}
3621
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003622uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623{
Glenn Kasten58912562012-04-03 10:45:00 -07003624 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625}
3626
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003627uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003628{
Glenn Kasten58912562012-04-03 10:45:00 -07003629 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003630}
3631
Glenn Kasten66fcab92012-02-24 14:59:21 -08003632void AudioFlinger::MixerThread::cacheParameters_l()
3633{
3634 PlaybackThread::cacheParameters_l();
3635
3636 // FIXME: Relaxed timing because of a certain device that can't meet latency
3637 // Should be reduced to 2x after the vendor fixes the driver issue
3638 // increase threshold again due to low power audio mode. The way this warning
3639 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003640 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003641}
3642
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003644AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3645 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003646 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003647 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649}
3650
3651AudioFlinger::DirectOutputThread::~DirectOutputThread()
3652{
3653}
3654
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003655AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3656 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003657)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003659 sp<Track> trackToRemove;
3660
Glenn Kastenfec279f2012-03-08 07:47:15 -08003661 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003662
Glenn Kasten952eeb22012-03-06 11:30:57 -08003663 // find out which tracks need to be processed
3664 if (mActiveTracks.size() != 0) {
3665 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003666 // The track died recently
3667 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668
Glenn Kasten952eeb22012-03-06 11:30:57 -08003669 Track* const track = t.get();
3670 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671
Glenn Kasten952eeb22012-03-06 11:30:57 -08003672 // The first time a track is added we wait
3673 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003674 uint32_t minFrames;
3675 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3676 minFrames = mNormalFrameCount;
3677 } else {
3678 minFrames = 1;
3679 }
3680 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 !track->isPaused() && !track->isTerminated())
3682 {
3683 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684
Glenn Kasten952eeb22012-03-06 11:30:57 -08003685 if (track->mFillingUpStatus == Track::FS_FILLED) {
3686 track->mFillingUpStatus = Track::FS_ACTIVE;
3687 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003688 if (track->mState == TrackBase::RESUMING) {
3689 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003690 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003692
Glenn Kasten952eeb22012-03-06 11:30:57 -08003693 // compute volume for this track
3694 float left, right;
3695 if (track->isMuted() || mMasterMute || track->isPausing() ||
3696 mStreamTypes[track->streamType()].mute) {
3697 left = right = 0;
3698 if (track->isPausing()) {
3699 track->setPaused();
3700 }
3701 } else {
3702 float typeVolume = mStreamTypes[track->streamType()].volume;
3703 float v = mMasterVolume * typeVolume;
3704 uint32_t vlr = cblk->getVolumeLR();
3705 float v_clamped = v * (vlr & 0xFFFF);
3706 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3707 left = v_clamped/MAX_GAIN;
3708 v_clamped = v * (vlr >> 16);
3709 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3710 right = v_clamped/MAX_GAIN;
3711 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712
Glenn Kasten952eeb22012-03-06 11:30:57 -08003713 if (left != mLeftVolFloat || right != mRightVolFloat) {
3714 mLeftVolFloat = left;
3715 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716
Glenn Kasten952eeb22012-03-06 11:30:57 -08003717 // Convert volumes from float to 8.24
3718 uint32_t vl = (uint32_t)(left * (1 << 24));
3719 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720
Glenn Kasten952eeb22012-03-06 11:30:57 -08003721 // Delegate volume control to effect in track effect chain if needed
3722 // only one effect chain can be present on DirectOutputThread, so if
3723 // there is one, the track is connected to it
3724 if (!mEffectChains.isEmpty()) {
3725 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003726 mEffectChains[0]->setVolume_l(&vl, &vr);
3727 left = (float)vl / (1 << 24);
3728 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003729 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003730 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003731 }
3732
3733 // reset retry count
3734 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003735 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003736 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003737 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003738 // clear effect chain input buffer if an active track underruns to avoid sending
3739 // previous audio buffer again to effects
3740 if (!mEffectChains.isEmpty()) {
3741 mEffectChains[0]->clearInputBuffer();
3742 }
3743
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003745 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3746 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003747 // We have consumed all the buffers of this track.
3748 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003749 // TODO: implement behavior for compressed audio
3750 size_t audioHALFrames =
3751 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3752 size_t framesWritten =
3753 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3754 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003755 if (track->isStopped()) {
3756 track->reset();
3757 }
Eric Laurenta011e352012-03-29 15:51:43 -07003758 trackToRemove = track;
3759 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003760 } else {
3761 // No buffers for this track. Give it a few chances to
3762 // fill a buffer, then remove it from active list.
3763 if (--(track->mRetryCount) <= 0) {
3764 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3765 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003767 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
3769 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 }
3771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003773 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 // remove all the tracks that need to be...
3775 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003776 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003777 mActiveTracks.remove(trackToRemove);
3778 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003779 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003780 trackToRemove->sessionId());
3781 mEffectChains[0]->decActiveTrackCnt();
3782 }
3783 if (trackToRemove->isTerminated()) {
3784 removeTrack_l(trackToRemove);
3785 }
3786 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787
Glenn Kastenfec279f2012-03-08 07:47:15 -08003788 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003789}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790
Glenn Kasten000f0e32012-03-01 17:10:56 -08003791void AudioFlinger::DirectOutputThread::threadLoop_mix()
3792{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 AudioBufferProvider::Buffer buffer;
3794 size_t frameCount = mFrameCount;
3795 int8_t *curBuf = (int8_t *)mMixBuffer;
3796 // output audio to hardware
3797 while (frameCount) {
3798 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003799 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003800 if (CC_UNLIKELY(buffer.raw == NULL)) {
3801 memset(curBuf, 0, frameCount * mFrameSize);
3802 break;
3803 }
3804 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3805 frameCount -= buffer.frameCount;
3806 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003807 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003808 }
3809 sleepTime = 0;
3810 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003811 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003812
Glenn Kasten000f0e32012-03-01 17:10:56 -08003813}
3814
3815void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3816{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003817 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003818 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003819 sleepTime = activeSleepTime;
3820 } else {
3821 sleepTime = idleSleepTime;
3822 }
3823 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003824 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003825 sleepTime = 0;
3826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827}
3828
3829// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003830int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831{
3832 return 0;
3833}
3834
3835// deleteTrackName_l() must be called with ThreadBase::mLock held
3836void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3837{
3838}
3839
3840// checkForNewParameters_l() must be called with ThreadBase::mLock held
3841bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3842{
3843 bool reconfig = false;
3844
3845 while (!mNewParameters.isEmpty()) {
3846 status_t status = NO_ERROR;
3847 String8 keyValuePair = mNewParameters[0];
3848 AudioParameter param = AudioParameter(keyValuePair);
3849 int value;
3850
3851 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3852 // do not accept frame count changes if tracks are open as the track buffer
3853 // size depends on frame count and correct behavior would not be garantied
3854 // if frame count is changed after track creation
3855 if (!mTracks.isEmpty()) {
3856 status = INVALID_OPERATION;
3857 } else {
3858 reconfig = true;
3859 }
3860 }
3861 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003862 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003863 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003865 mOutput->stream->common.standby(&mOutput->stream->common);
3866 mStandby = true;
3867 mBytesWritten = 0;
3868 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003869 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 }
3871 if (status == NO_ERROR && reconfig) {
3872 readOutputParameters();
3873 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3874 }
3875 }
3876
3877 mNewParameters.removeAt(0);
3878
3879 mParamStatus = status;
3880 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003881 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3882 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003883 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884 }
3885 return reconfig;
3886}
3887
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003888uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889{
3890 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003891 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003892 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 } else {
3894 time = 10000;
3895 }
3896 return time;
3897}
3898
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003899uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900{
3901 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003902 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003903 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904 } else {
3905 time = 10000;
3906 }
3907 return time;
3908}
3909
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003910uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003911{
3912 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003913 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003914 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3915 } else {
3916 time = 10000;
3917 }
3918 return time;
3919}
3920
Glenn Kasten66fcab92012-02-24 14:59:21 -08003921void AudioFlinger::DirectOutputThread::cacheParameters_l()
3922{
3923 PlaybackThread::cacheParameters_l();
3924
3925 // use shorter standby delay as on normal output to release
3926 // hardware resources as soon as possible
3927 standbyDelay = microseconds(activeSleepTime*2);
3928}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003929
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930// ----------------------------------------------------------------------------
3931
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003932AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003933 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003934 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3935 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 addOutputTrack(mainThread);
3938}
3939
3940AudioFlinger::DuplicatingThread::~DuplicatingThread()
3941{
3942 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3943 mOutputTracks[i]->destroy();
3944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945}
3946
Glenn Kasten000f0e32012-03-01 17:10:56 -08003947void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003949 // mix buffers...
3950 if (outputsReady(outputTracks)) {
3951 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3952 } else {
3953 memset(mMixBuffer, 0, mixBufferSize);
3954 }
3955 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003956 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003957 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003958}
3959
3960void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3961{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003962 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003963 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003964 sleepTime = activeSleepTime;
3965 } else {
3966 sleepTime = idleSleepTime;
3967 }
3968 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003969 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3970 writeFrames = mNormalFrameCount;
3971 memset(mMixBuffer, 0, mixBufferSize);
3972 } else {
3973 // flush remaining overflow buffers in output tracks
3974 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003975 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003976 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003977 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003978}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979
Glenn Kasten000f0e32012-03-01 17:10:56 -08003980void AudioFlinger::DuplicatingThread::threadLoop_write()
3981{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003982 for (size_t i = 0; i < outputTracks.size(); i++) {
3983 outputTracks[i]->write(mMixBuffer, writeFrames);
3984 }
3985 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003986}
Glenn Kasten688a6402012-02-29 07:57:06 -08003987
Glenn Kasten000f0e32012-03-01 17:10:56 -08003988void AudioFlinger::DuplicatingThread::threadLoop_standby()
3989{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003990 // DuplicatingThread implements standby by stopping all tracks
3991 for (size_t i = 0; i < outputTracks.size(); i++) {
3992 outputTracks[i]->stop();
3993 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994}
3995
Glenn Kastenfa26a852012-03-06 11:28:04 -08003996void AudioFlinger::DuplicatingThread::saveOutputTracks()
3997{
3998 outputTracks = mOutputTracks;
3999}
4000
4001void AudioFlinger::DuplicatingThread::clearOutputTracks()
4002{
4003 outputTracks.clear();
4004}
4005
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4007{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004008 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004009 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004010 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004011 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 this,
4013 mSampleRate,
4014 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004015 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016 frameCount);
4017 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004018 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004020 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004021 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022 }
4023}
4024
4025void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4026{
4027 Mutex::Autolock _l(mLock);
4028 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004029 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 mOutputTracks[i]->destroy();
4031 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004032 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 return;
4034 }
4035 }
Steve Block3856b092011-10-20 11:56:00 +01004036 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037}
4038
Glenn Kasten438b0362012-03-06 11:24:48 -08004039// caller must hold mLock
4040void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041{
4042 mWaitTimeMs = UINT_MAX;
4043 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4044 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004045 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4047 if (waitTimeMs < mWaitTimeMs) {
4048 mWaitTimeMs = waitTimeMs;
4049 }
4050 }
4051 }
4052}
4053
4054
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004055bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056{
4057 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004058 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004060 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 return false;
4062 }
4063 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4064 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004065 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 return false;
4067 }
4068 }
4069 return true;
4070}
4071
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004072uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073{
4074 return (mWaitTimeMs * 1000) / 2;
4075}
4076
Glenn Kasten66fcab92012-02-24 14:59:21 -08004077void AudioFlinger::DuplicatingThread::cacheParameters_l()
4078{
4079 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4080 updateWaitTime_l();
4081
4082 MixerThread::cacheParameters_l();
4083}
4084
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085// ----------------------------------------------------------------------------
4086
4087// TrackBase constructor must be called with AudioFlinger::mLock held
4088AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004089 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 const sp<Client>& client,
4091 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004092 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004093 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 const sp<IMemory>& sharedBuffer,
4096 int sessionId)
4097 : RefBase(),
4098 mThread(thread),
4099 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004100 mCblk(NULL),
4101 // mBuffer
4102 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 mFrameCount(0),
4104 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004105 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004107 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004109 // mChannelCount
4110 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111{
Steve Block3856b092011-10-20 11:56:00 +01004112 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113
Steve Blockb8a80522011-12-20 16:23:08 +00004114 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004115 size_t size = sizeof(audio_track_cblk_t);
4116 uint8_t channelCount = popcount(channelMask);
4117 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4118 if (sharedBuffer == 0) {
4119 size += bufferSize;
4120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004122 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 mCblkMemory = client->heap()->allocate(size);
4124 if (mCblkMemory != 0) {
4125 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004126 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 new(mCblk) audio_track_cblk_t();
4128 // clear all buffers
4129 mCblk->frameCount = frameCount;
4130 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004131// uncomment the following lines to quickly test 32-bit wraparound
4132// mCblk->user = 0xffff0000;
4133// mCblk->server = 0xffff0000;
4134// mCblk->userBase = 0xffff0000;
4135// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004136 mChannelCount = channelCount;
4137 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 if (sharedBuffer == 0) {
4139 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4140 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4141 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004142 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 mCblk->flags = CBLK_UNDERRUN_ON;
4144 } else {
4145 mBuffer = sharedBuffer->pointer();
4146 }
4147 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4148 }
4149 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004150 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 client->heap()->dump("AudioTrack");
4152 return;
4153 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004154 } else {
4155 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004156 // construct the shared structure in-place.
4157 new(mCblk) audio_track_cblk_t();
4158 // clear all buffers
4159 mCblk->frameCount = frameCount;
4160 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004161// uncomment the following lines to quickly test 32-bit wraparound
4162// mCblk->user = 0xffff0000;
4163// mCblk->server = 0xffff0000;
4164// mCblk->userBase = 0xffff0000;
4165// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004166 mChannelCount = channelCount;
4167 mChannelMask = channelMask;
4168 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4169 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4170 // Force underrun condition to avoid false underrun callback until first data is
4171 // written to buffer (other flags are cleared)
4172 mCblk->flags = CBLK_UNDERRUN_ON;
4173 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175}
4176
4177AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4178{
Glenn Kastena0d68332012-01-27 16:47:15 -08004179 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004180 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004182 } else {
4183 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 }
4185 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004186 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004187 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004188 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004190 // If the client's reference count drops to zero, the associated destructor
4191 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4192 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 mClient.clear();
4194 }
4195}
4196
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004197// AudioBufferProvider interface
4198// getNextBuffer() = 0;
4199// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4201{
Glenn Kastene0feee32011-12-13 11:53:26 -08004202 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004204 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004205 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 buffer->frameCount = 0;
4207}
4208
4209bool AudioFlinger::ThreadBase::TrackBase::step() {
4210 bool result;
4211 audio_track_cblk_t* cblk = this->cblk();
4212
4213 result = cblk->stepServer(mFrameCount);
4214 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004216 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 }
4218 return result;
4219}
4220
4221void AudioFlinger::ThreadBase::TrackBase::reset() {
4222 audio_track_cblk_t* cblk = this->cblk();
4223
4224 cblk->user = 0;
4225 cblk->server = 0;
4226 cblk->userBase = 0;
4227 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004228 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004229 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230}
4231
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4233 return (int)mCblk->sampleRate;
4234}
4235
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4237 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004238 size_t frameSize = cblk->frameSize;
4239 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4240 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
4242 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004243 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4244 "TrackBase::getBuffer buffer out of range:\n"
4245 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4246 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004248 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249
4250 return bufferStart;
4251}
4252
Eric Laurenta011e352012-03-29 15:51:43 -07004253status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4254{
4255 mSyncEvents.add(event);
4256 return NO_ERROR;
4257}
4258
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259// ----------------------------------------------------------------------------
4260
4261// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4262AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004263 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004265 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004267 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004268 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 int frameCount,
4270 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004271 int sessionId,
4272 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004273 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004274 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004275 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004276 // mRetryCount initialized later when needed
4277 mSharedBuffer(sharedBuffer),
4278 mStreamType(streamType),
4279 mName(-1), // see note below
4280 mMainBuffer(thread->mixBuffer()),
4281 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004282 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004283 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004284 mFlags(flags),
4285 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004286 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004287 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288{
4289 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4291 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004292 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004293 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4294 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004295 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004296 if (mName < 0) {
4297 ALOGE("no more track names available");
4298 return;
4299 }
4300 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004301 if (flags & IAudioFlinger::TRACK_FAST) {
4302 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4303 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4304 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004305 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004306 // FIXME This is too eager. We allocate a fast track index before the
4307 // fast track becomes active. Since fast tracks are a scarce resource,
4308 // this means we are potentially denying other more important fast tracks from
4309 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004310 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004311 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004312 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004313 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004314 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004317 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318}
4319
4320AudioFlinger::PlaybackThread::Track::~Track()
4321{
Steve Block3856b092011-10-20 11:56:00 +01004322 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 sp<ThreadBase> thread = mThread.promote();
4324 if (thread != 0) {
4325 Mutex::Autolock _l(thread->mLock);
4326 mState = TERMINATED;
4327 }
4328}
4329
4330void AudioFlinger::PlaybackThread::Track::destroy()
4331{
4332 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4333 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004334 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 // we must acquire a strong reference on this Track before locking mLock
4336 // here so that the destructor is called only when exiting this function.
4337 // On the other hand, as long as Track::destroy() is only called by
4338 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4339 // this Track with its member mTrack.
4340 sp<Track> keep(this);
4341 { // scope for mLock
4342 sp<ThreadBase> thread = mThread.promote();
4343 if (thread != 0) {
4344 if (!isOutputTrack()) {
4345 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004346 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004347
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004348#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004349 // to track the speaker usage
4350 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004351#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 }
4353 AudioSystem::releaseOutput(thread->id());
4354 }
4355 Mutex::Autolock _l(thread->mLock);
4356 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4357 playbackThread->destroyTrack_l(this);
4358 }
4359 }
4360}
4361
Glenn Kasten288ed212012-04-25 17:52:27 -07004362/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4363{
Glenn Kastene213c862012-04-25 13:46:15 -07004364 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 -07004365 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004366}
4367
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4369{
Glenn Kasten83d86532012-01-17 14:39:34 -08004370 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004371 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004372 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004373 } else {
4374 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4375 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004376 track_state state = mState;
4377 char stateChar;
4378 switch (state) {
4379 case IDLE:
4380 stateChar = 'I';
4381 break;
4382 case TERMINATED:
4383 stateChar = 'T';
4384 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004385 case STOPPING_1:
4386 stateChar = 's';
4387 break;
4388 case STOPPING_2:
4389 stateChar = '5';
4390 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004391 case STOPPED:
4392 stateChar = 'S';
4393 break;
4394 case RESUMING:
4395 stateChar = 'R';
4396 break;
4397 case ACTIVE:
4398 stateChar = 'A';
4399 break;
4400 case PAUSING:
4401 stateChar = 'p';
4402 break;
4403 case PAUSED:
4404 stateChar = 'P';
4405 break;
Eric Laurent29864602012-05-08 18:57:51 -07004406 case FLUSHED:
4407 stateChar = 'F';
4408 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004409 default:
4410 stateChar = '?';
4411 break;
4412 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004413 char nowInUnderrun;
4414 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4415 case UNDERRUN_FULL:
4416 nowInUnderrun = ' ';
4417 break;
4418 case UNDERRUN_PARTIAL:
4419 nowInUnderrun = '<';
4420 break;
4421 case UNDERRUN_EMPTY:
4422 nowInUnderrun = '*';
4423 break;
4424 default:
4425 nowInUnderrun = '?';
4426 break;
4427 }
Glenn Kastene213c862012-04-25 13:46:15 -07004428 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4429 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004430 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 mStreamType,
4432 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004433 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 mSessionId,
4435 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004436 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 mMute,
4439 mFillingUpStatus,
4440 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004441 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4442 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 mCblk->server,
4444 mCblk->user,
4445 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004446 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004447 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004448 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004449 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450}
4451
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004452// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004453status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004454 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004456 audio_track_cblk_t* cblk = this->cblk();
4457 uint32_t framesReady;
4458 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004460 // Check if last stepServer failed, try to step now
4461 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004462 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4463 // Since the fast mixer is higher priority than client callback thread,
4464 // it does not result in priority inversion for client.
4465 // But a non-blocking solution would be preferable to avoid
4466 // fast mixer being unable to tryLock(), and
4467 // to avoid the extra context switches if the client wakes up,
4468 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004469 if (!step()) goto getNextBuffer_exit;
4470 ALOGV("stepServer recovered");
4471 mStepServerFailed = false;
4472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004473
Glenn Kasten288ed212012-04-25 17:52:27 -07004474 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004475 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004477 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 uint32_t s = cblk->server;
4479 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4480
4481 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4482 if (framesReq > framesReady) {
4483 framesReq = framesReady;
4484 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004485 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 framesReq = bufferEnd - s;
4487 }
4488
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004489 buffer->raw = getBuffer(s, framesReq);
4490 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004492 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495
4496getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004497 buffer->raw = NULL;
4498 buffer->frameCount = 0;
4499 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4500 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501}
4502
Glenn Kasten288ed212012-04-25 17:52:27 -07004503// Note that framesReady() takes a mutex on the control block using tryLock().
4504// This could result in priority inversion if framesReady() is called by the normal mixer,
4505// as the normal mixer thread runs at lower
4506// priority than the client's callback thread: there is a short window within framesReady()
4507// during which the normal mixer could be preempted, and the client callback would block.
4508// Another problem can occur if framesReady() is called by the fast mixer:
4509// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4510// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4511size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004512 return mCblk->framesReady();
4513}
4514
Glenn Kasten288ed212012-04-25 17:52:27 -07004515// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004517 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518
John Grossman4ff14ba2012-02-08 16:37:41 -08004519 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4521 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004522 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 return true;
4524 }
4525 return false;
4526}
4527
Glenn Kasten3acbd052012-02-28 10:39:56 -08004528status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004529 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530{
4531 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004532 ALOGV("start(%d), calling pid %d session %d",
4533 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004534
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 sp<ThreadBase> thread = mThread.promote();
4536 if (thread != 0) {
4537 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004538 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 // here the track could be either new, or restarted
4540 // in both cases "unstop" the track
4541 if (mState == PAUSED) {
4542 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004543 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 } else {
4545 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004546 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 }
4548
4549 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4550 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004551 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004553
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004554#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004555 // to track the speaker usage
4556 if (status == NO_ERROR) {
4557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4558 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004559#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
4561 if (status == NO_ERROR) {
4562 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4563 playbackThread->addTrack_l(this);
4564 } else {
4565 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004566 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 }
4568 } else {
4569 status = BAD_VALUE;
4570 }
4571 return status;
4572}
4573
4574void AudioFlinger::PlaybackThread::Track::stop()
4575{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004576 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004577 sp<ThreadBase> thread = mThread.promote();
4578 if (thread != 0) {
4579 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004580 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004581 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 // If the track is not active (PAUSED and buffers full), flush buffers
4583 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4584 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4585 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004586 mState = STOPPED;
4587 } else if (!isFastTrack()) {
4588 mState = STOPPED;
4589 } else {
4590 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4591 // and then to STOPPED and reset() when presentation is complete
4592 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004594 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 }
4596 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4597 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004598 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004600
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004601#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004602 // to track the speaker usage
4603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004604#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 }
4606 }
4607}
4608
4609void AudioFlinger::PlaybackThread::Track::pause()
4610{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004611 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 sp<ThreadBase> thread = mThread.promote();
4613 if (thread != 0) {
4614 Mutex::Autolock _l(thread->mLock);
4615 if (mState == ACTIVE || mState == RESUMING) {
4616 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004617 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 if (!isOutputTrack()) {
4619 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004620 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004622
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004623#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004624 // to track the speaker usage
4625 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004626#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 }
4628 }
4629 }
4630}
4631
4632void AudioFlinger::PlaybackThread::Track::flush()
4633{
Steve Block3856b092011-10-20 11:56:00 +01004634 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 sp<ThreadBase> thread = mThread.promote();
4636 if (thread != 0) {
4637 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004638 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4639 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 return;
4641 }
4642 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004643 // FLUSHED state
4644 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004645 // do not reset the track if it is still in the process of being stopped or paused.
4646 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004647 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004648 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004649 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4650 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4651 reset();
4652 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 }
4654}
4655
4656void AudioFlinger::PlaybackThread::Track::reset()
4657{
4658 // Do not reset twice to avoid discarding data written just after a flush and before
4659 // the audioflinger thread detects the track is stopped.
4660 if (!mResetDone) {
4661 TrackBase::reset();
4662 // Force underrun condition to avoid false underrun callback until first data is
4663 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004664 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4665 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 mFillingUpStatus = FS_FILLING;
4667 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004668 if (mState == FLUSHED) {
4669 mState = IDLE;
4670 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 }
4672}
4673
4674void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4675{
4676 mMute = muted;
4677}
4678
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4680{
4681 status_t status = DEAD_OBJECT;
4682 sp<ThreadBase> thread = mThread.promote();
4683 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004684 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004685 sp<AudioFlinger> af = mClient->audioFlinger();
4686
4687 Mutex::Autolock _l(af->mLock);
4688
4689 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004690
Eric Laurent109347d2012-07-02 12:31:03 -07004691 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004692 Mutex::Autolock _dl(playbackThread->mLock);
4693 Mutex::Autolock _sl(srcThread->mLock);
4694 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4695 if (chain == 0) {
4696 return INVALID_OPERATION;
4697 }
4698
4699 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4700 if (effect == 0) {
4701 return INVALID_OPERATION;
4702 }
4703 srcThread->removeEffect_l(effect);
4704 playbackThread->addEffect_l(effect);
4705 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4706 if (effect->state() == EffectModule::ACTIVE ||
4707 effect->state() == EffectModule::STOPPING) {
4708 effect->start();
4709 }
4710
4711 sp<EffectChain> dstChain = effect->chain().promote();
4712 if (dstChain == 0) {
4713 srcThread->addEffect_l(effect);
4714 return INVALID_OPERATION;
4715 }
4716 AudioSystem::unregisterEffect(effect->id());
4717 AudioSystem::registerEffect(&effect->desc(),
4718 srcThread->id(),
4719 dstChain->strategy(),
4720 AUDIO_SESSION_OUTPUT_MIX,
4721 effect->id());
4722 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004723 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 }
4725 return status;
4726}
4727
4728void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4729{
4730 mAuxEffectId = EffectId;
4731 mAuxBuffer = buffer;
4732}
4733
Eric Laurenta011e352012-03-29 15:51:43 -07004734bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4735 size_t audioHalFrames)
4736{
4737 // a track is considered presented when the total number of frames written to audio HAL
4738 // corresponds to the number of frames written when presentationComplete() is called for the
4739 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4740 if (mPresentationCompleteFrames == 0) {
4741 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4742 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4743 mPresentationCompleteFrames, audioHalFrames);
4744 }
4745 if (framesWritten >= mPresentationCompleteFrames) {
4746 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4747 mSessionId, framesWritten);
4748 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004749 return true;
4750 }
4751 return false;
4752}
4753
4754void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4755{
4756 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4757 if (mSyncEvents[i]->type() == type) {
4758 mSyncEvents[i]->trigger();
4759 mSyncEvents.removeAt(i);
4760 i--;
4761 }
4762 }
4763}
4764
Glenn Kasten58912562012-04-03 10:45:00 -07004765// implement VolumeBufferProvider interface
4766
4767uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4768{
4769 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4770 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4771 uint32_t vlr = mCblk->getVolumeLR();
4772 uint32_t vl = vlr & 0xFFFF;
4773 uint32_t vr = vlr >> 16;
4774 // track volumes come from shared memory, so can't be trusted and must be clamped
4775 if (vl > MAX_GAIN_INT) {
4776 vl = MAX_GAIN_INT;
4777 }
4778 if (vr > MAX_GAIN_INT) {
4779 vr = MAX_GAIN_INT;
4780 }
4781 // now apply the cached master volume and stream type volume;
4782 // this is trusted but lacks any synchronization or barrier so may be stale
4783 float v = mCachedVolume;
4784 vl *= v;
4785 vr *= v;
4786 // re-combine into U4.16
4787 vlr = (vr << 16) | (vl & 0xFFFF);
4788 // FIXME look at mute, pause, and stop flags
4789 return vlr;
4790}
Eric Laurenta011e352012-03-29 15:51:43 -07004791
Eric Laurent29864602012-05-08 18:57:51 -07004792status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4793{
4794 if (mState == TERMINATED || mState == PAUSED ||
4795 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4796 (mState == STOPPED)))) {
4797 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4798 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4799 event->cancel();
4800 return INVALID_OPERATION;
4801 }
4802 TrackBase::setSyncEvent(event);
4803 return NO_ERROR;
4804}
4805
John Grossman4ff14ba2012-02-08 16:37:41 -08004806// timed audio tracks
4807
4808sp<AudioFlinger::PlaybackThread::TimedTrack>
4809AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004810 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004811 const sp<Client>& client,
4812 audio_stream_type_t streamType,
4813 uint32_t sampleRate,
4814 audio_format_t format,
4815 uint32_t channelMask,
4816 int frameCount,
4817 const sp<IMemory>& sharedBuffer,
4818 int sessionId) {
4819 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004820 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004821
Glenn Kastena0356762012-03-19 10:38:51 -07004822 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004823 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4824 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004825}
4826
4827AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004828 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004829 const sp<Client>& client,
4830 audio_stream_type_t streamType,
4831 uint32_t sampleRate,
4832 audio_format_t format,
4833 uint32_t channelMask,
4834 int frameCount,
4835 const sp<IMemory>& sharedBuffer,
4836 int sessionId)
4837 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004838 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004839 mQueueHeadInFlight(false),
4840 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004841 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004842 mTimedSilenceBuffer(NULL),
4843 mTimedSilenceBufferSize(0),
4844 mTimedAudioOutputOnTime(false),
4845 mMediaTimeTransformValid(false)
4846{
4847 LocalClock lc;
4848 mLocalTimeFreq = lc.getLocalFreq();
4849
4850 mLocalTimeToSampleTransform.a_zero = 0;
4851 mLocalTimeToSampleTransform.b_zero = 0;
4852 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4853 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4854 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4855 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004856
4857 mMediaTimeToSampleTransform.a_zero = 0;
4858 mMediaTimeToSampleTransform.b_zero = 0;
4859 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4860 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4861 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4862 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004863}
4864
4865AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4866 mClient->releaseTimedTrack();
4867 delete [] mTimedSilenceBuffer;
4868}
4869
4870status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4871 size_t size, sp<IMemory>* buffer) {
4872
4873 Mutex::Autolock _l(mTimedBufferQueueLock);
4874
4875 trimTimedBufferQueue_l();
4876
4877 // lazily initialize the shared memory heap for timed buffers
4878 if (mTimedMemoryDealer == NULL) {
4879 const int kTimedBufferHeapSize = 512 << 10;
4880
4881 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4882 "AudioFlingerTimed");
4883 if (mTimedMemoryDealer == NULL)
4884 return NO_MEMORY;
4885 }
4886
4887 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4888 if (newBuffer == NULL) {
4889 newBuffer = mTimedMemoryDealer->allocate(size);
4890 if (newBuffer == NULL)
4891 return NO_MEMORY;
4892 }
4893
4894 *buffer = newBuffer;
4895 return NO_ERROR;
4896}
4897
4898// caller must hold mTimedBufferQueueLock
4899void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4900 int64_t mediaTimeNow;
4901 {
4902 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4903 if (!mMediaTimeTransformValid)
4904 return;
4905
4906 int64_t targetTimeNow;
4907 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4908 ? mCCHelper.getCommonTime(&targetTimeNow)
4909 : mCCHelper.getLocalTime(&targetTimeNow);
4910
4911 if (OK != res)
4912 return;
4913
4914 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4915 &mediaTimeNow)) {
4916 return;
4917 }
4918 }
4919
John Grossman1c345192012-03-27 14:00:17 -07004920 size_t trimEnd;
4921 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004922 int64_t bufEnd;
4923
John Grossmanc95cfbb2012-04-12 11:53:11 -07004924 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4925 // We have a next buffer. Just use its PTS as the PTS of the frame
4926 // following the last frame in this buffer. If the stream is sparse
4927 // (ie, there are deliberate gaps left in the stream which should be
4928 // filled with silence by the TimedAudioTrack), then this can result
4929 // in one extra buffer being left un-trimmed when it could have
4930 // been. In general, this is not typical, and we would rather
4931 // optimized away the TS calculation below for the more common case
4932 // where PTSes are contiguous.
4933 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4934 } else {
4935 // We have no next buffer. Compute the PTS of the frame following
4936 // the last frame in this buffer by computing the duration of of
4937 // this frame in media time units and adding it to the PTS of the
4938 // buffer.
4939 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4940 / mCblk->frameSize;
4941
4942 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4943 &bufEnd)) {
4944 ALOGE("Failed to convert frame count of %lld to media time"
4945 " duration" " (scale factor %d/%u) in %s",
4946 frameCount,
4947 mMediaTimeToSampleTransform.a_to_b_numer,
4948 mMediaTimeToSampleTransform.a_to_b_denom,
4949 __PRETTY_FUNCTION__);
4950 break;
4951 }
4952 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004953 }
John Grossman9fbdee12012-03-26 17:51:46 -07004954
4955 if (bufEnd > mediaTimeNow)
4956 break;
4957
4958 // Is the buffer we want to use in the middle of a mix operation right
4959 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4960 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004961 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004962 mTrimQueueHeadOnRelease = true;
4963 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004964 }
4965
John Grossman9fbdee12012-03-26 17:51:46 -07004966 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004967 if (trimStart < trimEnd) {
4968 // Update the bookkeeping for framesReady()
4969 for (size_t i = trimStart; i < trimEnd; ++i) {
4970 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4971 }
4972
4973 // Now actually remove the buffers from the queue.
4974 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004975 }
4976}
4977
John Grossman1c345192012-03-27 14:00:17 -07004978void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4979 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004980 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4981 "%s called (reason \"%s\"), but timed buffer queue has no"
4982 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004983
4984 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4985 mTimedBufferQueue.removeAt(0);
4986}
4987
4988void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4989 const TimedBuffer& buf,
4990 const char* logTag) {
4991 uint32_t bufBytes = buf.buffer()->size();
4992 uint32_t consumedAlready = buf.position();
4993
Eric Laurentb388e532012-04-14 13:32:48 -07004994 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004995 "Bad bookkeeping while updating frames pending. Timed buffer is"
4996 " only %u bytes long, but claims to have consumed %u"
4997 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004998 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004999
5000 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005001 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5002 "Bad bookkeeping while updating frames pending. Should have at"
5003 " least %u queued frames, but we think we have only %u. (update"
5004 " reason: \"%s\")",
5005 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005006
5007 mFramesPendingInQueue -= bufFrames;
5008}
5009
John Grossman4ff14ba2012-02-08 16:37:41 -08005010status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5011 const sp<IMemory>& buffer, int64_t pts) {
5012
5013 {
5014 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5015 if (!mMediaTimeTransformValid)
5016 return INVALID_OPERATION;
5017 }
5018
5019 Mutex::Autolock _l(mTimedBufferQueueLock);
5020
John Grossman1c345192012-03-27 14:00:17 -07005021 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5022 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005023 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5024
5025 return NO_ERROR;
5026}
5027
5028status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5029 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5030
John Grossman1c345192012-03-27 14:00:17 -07005031 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5032 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5033 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005034
5035 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5036 target == TimedAudioTrack::COMMON_TIME)) {
5037 return BAD_VALUE;
5038 }
5039
5040 Mutex::Autolock lock(mMediaTimeTransformLock);
5041 mMediaTimeTransform = xform;
5042 mMediaTimeTransformTarget = target;
5043 mMediaTimeTransformValid = true;
5044
5045 return NO_ERROR;
5046}
5047
5048#define min(a, b) ((a) < (b) ? (a) : (b))
5049
5050// implementation of getNextBuffer for tracks whose buffers have timestamps
5051status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5052 AudioBufferProvider::Buffer* buffer, int64_t pts)
5053{
5054 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005055 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005056 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005057 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005058 return INVALID_OPERATION;
5059 }
5060
John Grossman4ff14ba2012-02-08 16:37:41 -08005061 Mutex::Autolock _l(mTimedBufferQueueLock);
5062
John Grossman9fbdee12012-03-26 17:51:46 -07005063 ALOG_ASSERT(!mQueueHeadInFlight,
5064 "getNextBuffer called without releaseBuffer!");
5065
John Grossman4ff14ba2012-02-08 16:37:41 -08005066 while (true) {
5067
5068 // if we have no timed buffers, then fail
5069 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005070 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005071 buffer->frameCount = 0;
5072 return NOT_ENOUGH_DATA;
5073 }
5074
5075 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5076
5077 // calculate the PTS of the head of the timed buffer queue expressed in
5078 // local time
5079 int64_t headLocalPTS;
5080 {
5081 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5082
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005083 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005084
5085 if (mMediaTimeTransform.a_to_b_denom == 0) {
5086 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005087 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005088 return NO_ERROR;
5089 }
5090
5091 int64_t transformedPTS;
5092 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5093 &transformedPTS)) {
5094 // the transform failed. this shouldn't happen, but if it does
5095 // then just drop this buffer
5096 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005097 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005098 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005099 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005100 return NO_ERROR;
5101 }
5102
5103 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5104 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5105 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005106 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005107 buffer->frameCount = 0;
5108 return INVALID_OPERATION;
5109 }
5110 } else {
5111 headLocalPTS = transformedPTS;
5112 }
5113 }
5114
5115 // adjust the head buffer's PTS to reflect the portion of the head buffer
5116 // that has already been consumed
5117 int64_t effectivePTS = headLocalPTS +
5118 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5119
5120 // Calculate the delta in samples between the head of the input buffer
5121 // queue and the start of the next output buffer that will be written.
5122 // If the transformation fails because of over or underflow, it means
5123 // that the sample's position in the output stream is so far out of
5124 // whack that it should just be dropped.
5125 int64_t sampleDelta;
5126 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5127 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005128 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5129 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005130 continue;
5131 }
5132 if (!mLocalTimeToSampleTransform.doForwardTransform(
5133 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005134 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005135 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005136 continue;
5137 }
5138
John Grossman1c345192012-03-27 14:00:17 -07005139 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5140 " sampleDelta=[%d.%08x]",
5141 head.pts(), head.position(), pts,
5142 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5143 + (sampleDelta >> 32)),
5144 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005145
5146 // if the delta between the ideal placement for the next input sample and
5147 // the current output position is within this threshold, then we will
5148 // concatenate the next input samples to the previous output
5149 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005150 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005151
5152 // if this is the first buffer of audio that we're emitting from this track
5153 // then it should be almost exactly on time.
5154 const int64_t kSampleStartupThreshold = 1LL << 32;
5155
5156 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005157 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005158 // the next input is close enough to being on time, so concatenate it
5159 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005160 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005161
John Grossman1c345192012-03-27 14:00:17 -07005162 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5163 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005164 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005165 }
5166
5167 // Looks like our output is not on time. Reset our on timed status.
5168 // Next time we mix samples from our input queue, then should be within
5169 // the StartupThreshold.
5170 mTimedAudioOutputOnTime = false;
5171 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005172 // the gap between the current output position and the proper start of
5173 // the next input sample is too big, so fill it with silence
5174 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5175
John Grossman9fbdee12012-03-26 17:51:46 -07005176 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005177 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5178 return NO_ERROR;
5179 } else {
5180 // the next input sample is late
5181 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5182 size_t onTimeSamplePosition =
5183 head.position() + lateFrames * mCblk->frameSize;
5184
5185 if (onTimeSamplePosition > head.buffer()->size()) {
5186 // all the remaining samples in the head are too late, so
5187 // drop it and move on
5188 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005189 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005190 continue;
5191 } else {
5192 // skip over the late samples
5193 head.setPosition(onTimeSamplePosition);
5194
5195 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005196 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005197
5198 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5199 return NO_ERROR;
5200 }
5201 }
5202 }
5203}
5204
5205// Yield samples from the timed buffer queue head up to the given output
5206// buffer's capacity.
5207//
5208// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005209void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005210 AudioBufferProvider::Buffer* buffer) {
5211
5212 const TimedBuffer& head = mTimedBufferQueue[0];
5213
5214 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5215 head.position());
5216
5217 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5218 mCblk->frameSize);
5219 size_t framesRequested = buffer->frameCount;
5220 buffer->frameCount = min(framesLeftInHead, framesRequested);
5221
John Grossman9fbdee12012-03-26 17:51:46 -07005222 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005223 mTimedAudioOutputOnTime = true;
5224}
5225
5226// Yield samples of silence up to the given output buffer's capacity
5227//
5228// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005229void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005230 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5231
5232 // lazily allocate a buffer filled with silence
5233 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5234 delete [] mTimedSilenceBuffer;
5235 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5236 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5237 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5238 }
5239
5240 buffer->raw = mTimedSilenceBuffer;
5241 size_t framesRequested = buffer->frameCount;
5242 buffer->frameCount = min(numFrames, framesRequested);
5243
5244 mTimedAudioOutputOnTime = false;
5245}
5246
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005247// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005248void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5249 AudioBufferProvider::Buffer* buffer) {
5250
5251 Mutex::Autolock _l(mTimedBufferQueueLock);
5252
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005253 // If the buffer which was just released is part of the buffer at the head
5254 // of the queue, be sure to update the amt of the buffer which has been
5255 // consumed. If the buffer being returned is not part of the head of the
5256 // queue, its either because the buffer is part of the silence buffer, or
5257 // because the head of the timed queue was trimmed after the mixer called
5258 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005259 if (buffer->raw == mTimedSilenceBuffer) {
5260 ALOG_ASSERT(!mQueueHeadInFlight,
5261 "Queue head in flight during release of silence buffer!");
5262 goto done;
5263 }
5264
5265 ALOG_ASSERT(mQueueHeadInFlight,
5266 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5267 " head in flight.");
5268
5269 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005270 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005271
5272 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005273 void* end = reinterpret_cast<void*>(
5274 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5275 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005276
John Grossman9fbdee12012-03-26 17:51:46 -07005277 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5278 "released buffer not within the head of the timed buffer"
5279 " queue; qHead = [%p, %p], released buffer = %p",
5280 start, end, buffer->raw);
5281
5282 head.setPosition(head.position() +
5283 (buffer->frameCount * mCblk->frameSize));
5284 mQueueHeadInFlight = false;
5285
John Grossman1c345192012-03-27 14:00:17 -07005286 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5287 "Bad bookkeeping during releaseBuffer! Should have at"
5288 " least %u queued frames, but we think we have only %u",
5289 buffer->frameCount, mFramesPendingInQueue);
5290
5291 mFramesPendingInQueue -= buffer->frameCount;
5292
John Grossman9fbdee12012-03-26 17:51:46 -07005293 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5294 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005295 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005296 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005297 }
John Grossman9fbdee12012-03-26 17:51:46 -07005298 } else {
5299 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5300 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005301 }
5302
John Grossman9fbdee12012-03-26 17:51:46 -07005303done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005304 buffer->raw = 0;
5305 buffer->frameCount = 0;
5306}
5307
Glenn Kasten288ed212012-04-25 17:52:27 -07005308size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005309 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005310 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005311}
5312
5313AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5314 : mPTS(0), mPosition(0) {}
5315
5316AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5317 const sp<IMemory>& buffer, int64_t pts)
5318 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5319
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320// ----------------------------------------------------------------------------
5321
5322// RecordTrack constructor must be called with AudioFlinger::mLock held
5323AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005324 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 const sp<Client>& client,
5326 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005327 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005328 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330 int sessionId)
5331 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005332 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 mOverflow(false)
5334{
5335 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005336 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5337 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5338 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5339 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5340 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5341 } else {
5342 mCblk->frameSize = sizeof(int8_t);
5343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 }
5345}
5346
5347AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5348{
5349 sp<ThreadBase> thread = mThread.promote();
5350 if (thread != 0) {
5351 AudioSystem::releaseInput(thread->id());
5352 }
5353}
5354
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005355// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005356status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357{
5358 audio_track_cblk_t* cblk = this->cblk();
5359 uint32_t framesAvail;
5360 uint32_t framesReq = buffer->frameCount;
5361
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005362 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005363 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005365 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005366 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 }
5368
5369 framesAvail = cblk->framesAvailable_l();
5370
Glenn Kastenf6b16782011-12-15 09:51:17 -08005371 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 uint32_t s = cblk->server;
5373 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5374
5375 if (framesReq > framesAvail) {
5376 framesReq = framesAvail;
5377 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005378 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 framesReq = bufferEnd - s;
5380 }
5381
5382 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005383 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384
5385 buffer->frameCount = framesReq;
5386 return NO_ERROR;
5387 }
5388
5389getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005390 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 buffer->frameCount = 0;
5392 return NOT_ENOUGH_DATA;
5393}
5394
Glenn Kasten3acbd052012-02-28 10:39:56 -08005395status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005396 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397{
5398 sp<ThreadBase> thread = mThread.promote();
5399 if (thread != 0) {
5400 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005401 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 } else {
5403 return BAD_VALUE;
5404 }
5405}
5406
5407void AudioFlinger::RecordThread::RecordTrack::stop()
5408{
5409 sp<ThreadBase> thread = mThread.promote();
5410 if (thread != 0) {
5411 RecordThread *recordThread = (RecordThread *)thread.get();
5412 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005413 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005414 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005415 // read from buffer
5416 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 }
5418}
5419
5420void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5421{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005422 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005423 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005425 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 mSessionId,
5427 mFrameCount,
5428 mState,
5429 mCblk->sampleRate,
5430 mCblk->server,
5431 mCblk->user);
5432}
5433
5434
5435// ----------------------------------------------------------------------------
5436
5437AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005438 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 DuplicatingThread *sourceThread,
5440 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005441 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005442 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005444 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5445 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 mActive(false), mSourceThread(sourceThread)
5447{
5448
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 if (mCblk != NULL) {
5450 mCblk->flags |= CBLK_DIRECTION_OUT;
5451 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 mOutBuffer.frameCount = 0;
5453 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005454 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005455 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5456 mCblk, mBuffer, mCblk->buffers,
5457 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005459 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 }
5461}
5462
5463AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5464{
5465 clearBufferQueue();
5466}
5467
Glenn Kasten3acbd052012-02-28 10:39:56 -08005468status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005469 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005471 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 if (status != NO_ERROR) {
5473 return status;
5474 }
5475
5476 mActive = true;
5477 mRetryCount = 127;
5478 return status;
5479}
5480
5481void AudioFlinger::PlaybackThread::OutputTrack::stop()
5482{
5483 Track::stop();
5484 clearBufferQueue();
5485 mOutBuffer.frameCount = 0;
5486 mActive = false;
5487}
5488
5489bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5490{
5491 Buffer *pInBuffer;
5492 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005493 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 bool outputBufferFull = false;
5495 inBuffer.frameCount = frames;
5496 inBuffer.i16 = data;
5497
5498 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5499
5500 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005501 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 sp<ThreadBase> thread = mThread.promote();
5503 if (thread != 0) {
5504 MixerThread *mixerThread = (MixerThread *)thread.get();
5505 if (mCblk->frameCount > frames){
5506 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5507 uint32_t startFrames = (mCblk->frameCount - frames);
5508 pInBuffer = new Buffer;
5509 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5510 pInBuffer->frameCount = startFrames;
5511 pInBuffer->i16 = pInBuffer->mBuffer;
5512 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5513 mBufferQueue.add(pInBuffer);
5514 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005515 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 }
5517 }
5518 }
5519 }
5520
5521 while (waitTimeLeftMs) {
5522 // First write pending buffers, then new data
5523 if (mBufferQueue.size()) {
5524 pInBuffer = mBufferQueue.itemAt(0);
5525 } else {
5526 pInBuffer = &inBuffer;
5527 }
5528
5529 if (pInBuffer->frameCount == 0) {
5530 break;
5531 }
5532
5533 if (mOutBuffer.frameCount == 0) {
5534 mOutBuffer.frameCount = pInBuffer->frameCount;
5535 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005536 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005537 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 outputBufferFull = true;
5539 break;
5540 }
5541 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5542 if (waitTimeLeftMs >= waitTimeMs) {
5543 waitTimeLeftMs -= waitTimeMs;
5544 } else {
5545 waitTimeLeftMs = 0;
5546 }
5547 }
5548
5549 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5550 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5551 mCblk->stepUser(outFrames);
5552 pInBuffer->frameCount -= outFrames;
5553 pInBuffer->i16 += outFrames * channelCount;
5554 mOutBuffer.frameCount -= outFrames;
5555 mOutBuffer.i16 += outFrames * channelCount;
5556
5557 if (pInBuffer->frameCount == 0) {
5558 if (mBufferQueue.size()) {
5559 mBufferQueue.removeAt(0);
5560 delete [] pInBuffer->mBuffer;
5561 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005562 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 } else {
5564 break;
5565 }
5566 }
5567 }
5568
5569 // If we could not write all frames, allocate a buffer and queue it for next time.
5570 if (inBuffer.frameCount) {
5571 sp<ThreadBase> thread = mThread.promote();
5572 if (thread != 0 && !thread->standby()) {
5573 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5574 pInBuffer = new Buffer;
5575 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5576 pInBuffer->frameCount = inBuffer.frameCount;
5577 pInBuffer->i16 = pInBuffer->mBuffer;
5578 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5579 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005580 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005582 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 }
5584 }
5585 }
5586
5587 // Calling write() with a 0 length buffer, means that no more data will be written:
5588 // If no more buffers are pending, fill output track buffer to make sure it is started
5589 // by output mixer.
5590 if (frames == 0 && mBufferQueue.size() == 0) {
5591 if (mCblk->user < mCblk->frameCount) {
5592 frames = mCblk->frameCount - mCblk->user;
5593 pInBuffer = new Buffer;
5594 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5595 pInBuffer->frameCount = frames;
5596 pInBuffer->i16 = pInBuffer->mBuffer;
5597 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5598 mBufferQueue.add(pInBuffer);
5599 } else if (mActive) {
5600 stop();
5601 }
5602 }
5603
5604 return outputBufferFull;
5605}
5606
5607status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5608{
5609 int active;
5610 status_t result;
5611 audio_track_cblk_t* cblk = mCblk;
5612 uint32_t framesReq = buffer->frameCount;
5613
Steve Block3856b092011-10-20 11:56:00 +01005614// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 buffer->frameCount = 0;
5616
5617 uint32_t framesAvail = cblk->framesAvailable();
5618
5619
5620 if (framesAvail == 0) {
5621 Mutex::Autolock _l(cblk->lock);
5622 goto start_loop_here;
5623 while (framesAvail == 0) {
5624 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005625 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005626 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005627 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005628 }
5629 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5630 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005631 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 }
5633 // read the server count again
5634 start_loop_here:
5635 framesAvail = cblk->framesAvailable_l();
5636 }
5637 }
5638
5639// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005640// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641// }
5642
5643 if (framesReq > framesAvail) {
5644 framesReq = framesAvail;
5645 }
5646
5647 uint32_t u = cblk->user;
5648 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5649
Marco Nelissena1472d92012-03-30 14:36:54 -07005650 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 framesReq = bufferEnd - u;
5652 }
5653
5654 buffer->frameCount = framesReq;
5655 buffer->raw = (void *)cblk->buffer(u);
5656 return NO_ERROR;
5657}
5658
5659
5660void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5661{
5662 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663
5664 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005665 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 delete [] pBuffer->mBuffer;
5667 delete pBuffer;
5668 }
5669 mBufferQueue.clear();
5670}
5671
5672// ----------------------------------------------------------------------------
5673
5674AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5675 : RefBase(),
5676 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005677 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005679 mPid(pid),
5680 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681{
5682 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5683}
5684
5685// Client destructor must be called with AudioFlinger::mLock held
5686AudioFlinger::Client::~Client()
5687{
5688 mAudioFlinger->removeClient_l(mPid);
5689}
5690
Glenn Kasten435dbe62012-01-30 10:15:48 -08005691sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692{
5693 return mMemoryDealer;
5694}
5695
John Grossman4ff14ba2012-02-08 16:37:41 -08005696// Reserve one of the limited slots for a timed audio track associated
5697// with this client
5698bool AudioFlinger::Client::reserveTimedTrack()
5699{
5700 const int kMaxTimedTracksPerClient = 4;
5701
5702 Mutex::Autolock _l(mTimedTrackLock);
5703
5704 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5705 ALOGW("can not create timed track - pid %d has exceeded the limit",
5706 mPid);
5707 return false;
5708 }
5709
5710 mTimedTrackCount++;
5711 return true;
5712}
5713
5714// Release a slot for a timed audio track
5715void AudioFlinger::Client::releaseTimedTrack()
5716{
5717 Mutex::Autolock _l(mTimedTrackLock);
5718 mTimedTrackCount--;
5719}
5720
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721// ----------------------------------------------------------------------------
5722
5723AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5724 const sp<IAudioFlingerClient>& client,
5725 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005726 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727{
5728}
5729
5730AudioFlinger::NotificationClient::~NotificationClient()
5731{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
5734void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5735{
5736 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005737 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738}
5739
5740// ----------------------------------------------------------------------------
5741
5742AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5743 : BnAudioTrack(),
5744 mTrack(track)
5745{
5746}
5747
5748AudioFlinger::TrackHandle::~TrackHandle() {
5749 // just stop the track on deletion, associated resources
5750 // will be freed from the main thread once all pending buffers have
5751 // been played. Unless it's not in the active track list, in which
5752 // case we free everything now...
5753 mTrack->destroy();
5754}
5755
Glenn Kasten90716c52012-01-26 13:40:12 -08005756sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5757 return mTrack->getCblk();
5758}
5759
Glenn Kasten3acbd052012-02-28 10:39:56 -08005760status_t AudioFlinger::TrackHandle::start() {
5761 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762}
5763
5764void AudioFlinger::TrackHandle::stop() {
5765 mTrack->stop();
5766}
5767
5768void AudioFlinger::TrackHandle::flush() {
5769 mTrack->flush();
5770}
5771
5772void AudioFlinger::TrackHandle::mute(bool e) {
5773 mTrack->mute(e);
5774}
5775
5776void AudioFlinger::TrackHandle::pause() {
5777 mTrack->pause();
5778}
5779
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5781{
5782 return mTrack->attachAuxEffect(EffectId);
5783}
5784
John Grossman4ff14ba2012-02-08 16:37:41 -08005785status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5786 sp<IMemory>* buffer) {
5787 if (!mTrack->isTimedTrack())
5788 return INVALID_OPERATION;
5789
5790 PlaybackThread::TimedTrack* tt =
5791 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5792 return tt->allocateTimedBuffer(size, buffer);
5793}
5794
5795status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5796 int64_t pts) {
5797 if (!mTrack->isTimedTrack())
5798 return INVALID_OPERATION;
5799
5800 PlaybackThread::TimedTrack* tt =
5801 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5802 return tt->queueTimedBuffer(buffer, pts);
5803}
5804
5805status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5806 const LinearTransform& xform, int target) {
5807
5808 if (!mTrack->isTimedTrack())
5809 return INVALID_OPERATION;
5810
5811 PlaybackThread::TimedTrack* tt =
5812 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5813 return tt->setMediaTimeTransform(
5814 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5815}
5816
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817status_t AudioFlinger::TrackHandle::onTransact(
5818 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5819{
5820 return BnAudioTrack::onTransact(code, data, reply, flags);
5821}
5822
5823// ----------------------------------------------------------------------------
5824
5825sp<IAudioRecord> AudioFlinger::openRecord(
5826 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005827 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005829 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005830 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005832 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 int *sessionId,
5834 status_t *status)
5835{
5836 sp<RecordThread::RecordTrack> recordTrack;
5837 sp<RecordHandle> recordHandle;
5838 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 status_t lStatus;
5840 RecordThread *thread;
5841 size_t inFrameCount;
5842 int lSessionId;
5843
5844 // check calling permissions
5845 if (!recordingAllowed()) {
5846 lStatus = PERMISSION_DENIED;
5847 goto Exit;
5848 }
5849
5850 // add client to list
5851 { // scope for mLock
5852 Mutex::Autolock _l(mLock);
5853 thread = checkRecordThread_l(input);
5854 if (thread == NULL) {
5855 lStatus = BAD_VALUE;
5856 goto Exit;
5857 }
5858
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005859 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860
5861 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005862 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 lSessionId = *sessionId;
5864 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005865 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 if (sessionId != NULL) {
5867 *sessionId = lSessionId;
5868 }
5869 }
5870 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005871 recordTrack = thread->createRecordTrack_l(client,
5872 sampleRate,
5873 format,
5874 channelMask,
5875 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005876 lSessionId,
5877 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005879 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5881 // destructor is called by the TrackBase destructor with mLock held
5882 client.clear();
5883 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 goto Exit;
5885 }
5886
5887 // return to handle to client
5888 recordHandle = new RecordHandle(recordTrack);
5889 lStatus = NO_ERROR;
5890
5891Exit:
5892 if (status) {
5893 *status = lStatus;
5894 }
5895 return recordHandle;
5896}
5897
5898// ----------------------------------------------------------------------------
5899
5900AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5901 : BnAudioRecord(),
5902 mRecordTrack(recordTrack)
5903{
5904}
5905
5906AudioFlinger::RecordHandle::~RecordHandle() {
5907 stop();
5908}
5909
Glenn Kasten90716c52012-01-26 13:40:12 -08005910sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5911 return mRecordTrack->getCblk();
5912}
5913
Glenn Kasten3acbd052012-02-28 10:39:56 -08005914status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005915 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005916 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917}
5918
5919void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005920 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 mRecordTrack->stop();
5922}
5923
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924status_t AudioFlinger::RecordHandle::onTransact(
5925 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5926{
5927 return BnAudioRecord::onTransact(code, data, reply, flags);
5928}
5929
5930// ----------------------------------------------------------------------------
5931
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005932AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5933 AudioStreamIn *input,
5934 uint32_t sampleRate,
5935 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005936 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005937 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005938 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005939 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5940 // mRsmpInIndex and mInputBytes set by readInputParameters()
5941 mReqChannelCount(popcount(channels)),
5942 mReqSampleRate(sampleRate)
5943 // mBytesRead is only meaningful while active, and so is cleared in start()
5944 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945{
Glenn Kasten480b4682012-02-28 12:30:08 -08005946 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005947
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 readInputParameters();
5949}
5950
5951
5952AudioFlinger::RecordThread::~RecordThread()
5953{
5954 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005955 delete mResampler;
5956 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957}
5958
5959void AudioFlinger::RecordThread::onFirstRef()
5960{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005961 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962}
5963
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005964status_t AudioFlinger::RecordThread::readyToRun()
5965{
5966 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005967 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005968 return status;
5969}
5970
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971bool AudioFlinger::RecordThread::threadLoop()
5972{
5973 AudioBufferProvider::Buffer buffer;
5974 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005975 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976
Eric Laurent44d98482010-09-30 16:12:31 -07005977 nsecs_t lastWarning = 0;
5978
Eric Laurentfeb0db62011-07-22 09:04:31 -07005979 acquireWakeLock();
5980
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 // start recording
5982 while (!exitPending()) {
5983
5984 processConfigEvents();
5985
5986 { // scope for mLock
5987 Mutex::Autolock _l(mLock);
5988 checkForNewParameters_l();
5989 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5990 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005991 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 mStandby = true;
5993 }
5994
5995 if (exitPending()) break;
5996
Eric Laurentfeb0db62011-07-22 09:04:31 -07005997 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005998 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 // go to sleep
6000 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006001 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006002 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 continue;
6004 }
6005 if (mActiveTrack != 0) {
6006 if (mActiveTrack->mState == TrackBase::PAUSING) {
6007 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006008 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 mStandby = true;
6010 }
6011 mActiveTrack.clear();
6012 mStartStopCond.broadcast();
6013 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6014 if (mReqChannelCount != mActiveTrack->channelCount()) {
6015 mActiveTrack.clear();
6016 mStartStopCond.broadcast();
6017 } else if (mBytesRead != 0) {
6018 // record start succeeds only if first read from audio input
6019 // succeeds
6020 if (mBytesRead > 0) {
6021 mActiveTrack->mState = TrackBase::ACTIVE;
6022 } else {
6023 mActiveTrack.clear();
6024 }
6025 mStartStopCond.broadcast();
6026 }
6027 mStandby = false;
6028 }
6029 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006030 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 }
6032
6033 if (mActiveTrack != 0) {
6034 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6035 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036 unlockEffectChains(effectChains);
6037 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 continue;
6039 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006040 for (size_t i = 0; i < effectChains.size(); i ++) {
6041 effectChains[i]->process_l();
6042 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006043
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006045 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006047 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 // no resampling
6049 while (framesOut) {
6050 size_t framesIn = mFrameCount - mRsmpInIndex;
6051 if (framesIn) {
6052 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6053 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6054 if (framesIn > framesOut)
6055 framesIn = framesOut;
6056 mRsmpInIndex += framesIn;
6057 framesOut -= framesIn;
6058 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006059 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 memcpy(dst, src, framesIn * mFrameSize);
6061 } else {
6062 int16_t *src16 = (int16_t *)src;
6063 int16_t *dst16 = (int16_t *)dst;
6064 if (mChannelCount == 1) {
6065 while (framesIn--) {
6066 *dst16++ = *src16;
6067 *dst16++ = *src16++;
6068 }
6069 } else {
6070 while (framesIn--) {
6071 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6072 src16 += 2;
6073 }
6074 }
6075 }
6076 }
6077 if (framesOut && mFrameCount == mRsmpInIndex) {
6078 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006079 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006080 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081 framesOut = 0;
6082 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006083 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084 mRsmpInIndex = 0;
6085 }
6086 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006087 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6089 // Force input into standby so that it tries to
6090 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006091 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006092 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 }
6094 mRsmpInIndex = mFrameCount;
6095 framesOut = 0;
6096 buffer.frameCount = 0;
6097 }
6098 }
6099 }
6100 } else {
6101 // resampling
6102
6103 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6104 // alter output frame count as if we were expecting stereo samples
6105 if (mChannelCount == 1 && mReqChannelCount == 1) {
6106 framesOut >>= 1;
6107 }
6108 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6109 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6110 // are 32 bit aligned which should be always true.
6111 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006112 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113 // the resampler always outputs stereo samples: do post stereo to mono conversion
6114 int16_t *src = (int16_t *)mRsmpOutBuffer;
6115 int16_t *dst = buffer.i16;
6116 while (framesOut--) {
6117 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6118 src += 2;
6119 }
6120 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006121 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 }
6123
6124 }
Eric Laurenta011e352012-03-29 15:51:43 -07006125 if (mFramestoDrop == 0) {
6126 mActiveTrack->releaseBuffer(&buffer);
6127 } else {
6128 if (mFramestoDrop > 0) {
6129 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006130 if (mFramestoDrop <= 0) {
6131 clearSyncStartEvent();
6132 }
6133 } else {
6134 mFramestoDrop += buffer.frameCount;
6135 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6136 mSyncStartEvent->isCancelled()) {
6137 ALOGW("Synced record %s, session %d, trigger session %d",
6138 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6139 mActiveTrack->sessionId(),
6140 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6141 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006142 }
6143 }
6144 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 mActiveTrack->overflow();
6146 }
6147 // client isn't retrieving buffers fast enough
6148 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006149 if (!mActiveTrack->setOverflow()) {
6150 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006151 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006152 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006153 lastWarning = now;
6154 }
6155 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 // Release the processor for a while before asking for a new buffer.
6157 // This will give the application more chance to read from the buffer and
6158 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 }
6161 }
Eric Laurentec437d82011-07-26 20:54:46 -07006162 // enable changes in effect chain
6163 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006164 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165 }
6166
6167 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006168 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
6170 mActiveTrack.clear();
6171
6172 mStartStopCond.broadcast();
6173
Eric Laurentfeb0db62011-07-22 09:04:31 -07006174 releaseWakeLock();
6175
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 return false;
6178}
6179
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006180
6181sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6182 const sp<AudioFlinger::Client>& client,
6183 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006184 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006185 int channelMask,
6186 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187 int sessionId,
6188 status_t *status)
6189{
6190 sp<RecordTrack> track;
6191 status_t lStatus;
6192
6193 lStatus = initCheck();
6194 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006195 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006196 goto Exit;
6197 }
6198
6199 { // scope for mLock
6200 Mutex::Autolock _l(mLock);
6201
6202 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006203 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006204
Glenn Kasten7378ca52012-01-20 13:44:40 -08006205 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006206 lStatus = NO_MEMORY;
6207 goto Exit;
6208 }
6209
6210 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006211 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6212 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006213 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006214 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6215 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 }
6217 lStatus = NO_ERROR;
6218
6219Exit:
6220 if (status) {
6221 *status = lStatus;
6222 }
6223 return track;
6224}
6225
Eric Laurenta011e352012-03-29 15:51:43 -07006226status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006227 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006228 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229{
Glenn Kasten58912562012-04-03 10:45:00 -07006230 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006231 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006233
6234 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006235 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006236 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6237 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6238 triggerSession,
6239 recordTrack->sessionId(),
6240 syncStartEventCallback,
6241 this);
Eric Laurent29864602012-05-08 18:57:51 -07006242 // Sync event can be cancelled by the trigger session if the track is not in a
6243 // compatible state in which case we start record immediately
6244 if (mSyncStartEvent->isCancelled()) {
6245 clearSyncStartEvent();
6246 } else {
6247 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6248 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6249 }
Eric Laurenta011e352012-03-29 15:51:43 -07006250 }
6251
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006253 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 if (mActiveTrack != 0) {
6255 if (recordTrack != mActiveTrack.get()) {
6256 status = -EBUSY;
6257 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6258 mActiveTrack->mState = TrackBase::ACTIVE;
6259 }
6260 return status;
6261 }
6262
6263 recordTrack->mState = TrackBase::IDLE;
6264 mActiveTrack = recordTrack;
6265 mLock.unlock();
6266 status_t status = AudioSystem::startInput(mId);
6267 mLock.lock();
6268 if (status != NO_ERROR) {
6269 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006270 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 return status;
6272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 mRsmpInIndex = mFrameCount;
6274 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006275 if (mResampler != NULL) {
6276 mResampler->reset();
6277 }
6278 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006280 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 mWaitWorkCV.signal();
6282 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006283 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 mActiveTrack.clear();
6285 status = INVALID_OPERATION;
6286 goto startError;
6287 }
6288 mStartStopCond.wait(mLock);
6289 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006290 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 status = BAD_VALUE;
6292 goto startError;
6293 }
Steve Block3856b092011-10-20 11:56:00 +01006294 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 return status;
6296 }
6297startError:
6298 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006299 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 return status;
6301}
6302
Eric Laurenta011e352012-03-29 15:51:43 -07006303void AudioFlinger::RecordThread::clearSyncStartEvent()
6304{
6305 if (mSyncStartEvent != 0) {
6306 mSyncStartEvent->cancel();
6307 }
6308 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006309 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006310}
6311
6312void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6313{
6314 sp<SyncEvent> strongEvent = event.promote();
6315
6316 if (strongEvent != 0) {
6317 RecordThread *me = (RecordThread *)strongEvent->cookie();
6318 me->handleSyncStartEvent(strongEvent);
6319 }
6320}
6321
6322void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6323{
Eric Laurent29864602012-05-08 18:57:51 -07006324 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006325 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6326 // from audio HAL
6327 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006328 }
6329}
6330
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006332 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006333 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006335 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6337 mActiveTrack->mState = TrackBase::PAUSING;
6338 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006339 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 return;
6341 }
6342 mStartStopCond.wait(mLock);
6343 // if we have been restarted, recordTrack == mActiveTrack.get() here
6344 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6345 mLock.unlock();
6346 AudioSystem::stopInput(mId);
6347 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006348 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 }
6350 }
6351 }
6352}
6353
Eric Laurenta011e352012-03-29 15:51:43 -07006354bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6355{
6356 return false;
6357}
6358
6359status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6360{
6361 if (!isValidSyncEvent(event)) {
6362 return BAD_VALUE;
6363 }
6364
6365 Mutex::Autolock _l(mLock);
6366
6367 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6368 mTrack->setSyncEvent(event);
6369 return NO_ERROR;
6370 }
6371 return NAME_NOT_FOUND;
6372}
6373
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6375{
6376 const size_t SIZE = 256;
6377 char buffer[SIZE];
6378 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379
6380 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6381 result.append(buffer);
6382
6383 if (mActiveTrack != 0) {
6384 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006385 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 mActiveTrack->dump(buffer, SIZE);
6387 result.append(buffer);
6388
6389 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6390 result.append(buffer);
6391 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6392 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006393 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 result.append(buffer);
6395 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6396 result.append(buffer);
6397 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6398 result.append(buffer);
6399
6400
6401 } else {
6402 result.append("No record client\n");
6403 }
6404 write(fd, result.string(), result.size());
6405
6406 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006407 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408
6409 return NO_ERROR;
6410}
6411
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006412// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006413status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414{
6415 size_t framesReq = buffer->frameCount;
6416 size_t framesReady = mFrameCount - mRsmpInIndex;
6417 int channelCount;
6418
6419 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006420 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006422 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6424 // Force input into standby so that it tries to
6425 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006426 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006427 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006428 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006429 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 buffer->frameCount = 0;
6431 return NOT_ENOUGH_DATA;
6432 }
6433 mRsmpInIndex = 0;
6434 framesReady = mFrameCount;
6435 }
6436
6437 if (framesReq > framesReady) {
6438 framesReq = framesReady;
6439 }
6440
6441 if (mChannelCount == 1 && mReqChannelCount == 2) {
6442 channelCount = 1;
6443 } else {
6444 channelCount = 2;
6445 }
6446 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6447 buffer->frameCount = framesReq;
6448 return NO_ERROR;
6449}
6450
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006451// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6453{
6454 mRsmpInIndex += buffer->frameCount;
6455 buffer->frameCount = 0;
6456}
6457
6458bool AudioFlinger::RecordThread::checkForNewParameters_l()
6459{
6460 bool reconfig = false;
6461
6462 while (!mNewParameters.isEmpty()) {
6463 status_t status = NO_ERROR;
6464 String8 keyValuePair = mNewParameters[0];
6465 AudioParameter param = AudioParameter(keyValuePair);
6466 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006467 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 int reqSamplingRate = mReqSampleRate;
6469 int reqChannelCount = mReqChannelCount;
6470
6471 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6472 reqSamplingRate = value;
6473 reconfig = true;
6474 }
6475 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006476 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 reconfig = true;
6478 }
6479 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006480 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 reconfig = true;
6482 }
6483 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6484 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006485 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 // if frame count is changed after track creation
6487 if (mActiveTrack != 0) {
6488 status = INVALID_OPERATION;
6489 } else {
6490 reconfig = true;
6491 }
6492 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006493 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6494 // forward device change to effects that have requested to be
6495 // aware of attached audio device.
6496 for (size_t i = 0; i < mEffectChains.size(); i++) {
6497 mEffectChains[i]->setDevice_l(value);
6498 }
6499 // store input device and output device but do not forward output device to audio HAL.
6500 // Note that status is ignored by the caller for output device
6501 // (see AudioFlinger::setParameters()
6502 if (value & AUDIO_DEVICE_OUT_ALL) {
6503 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6504 status = BAD_VALUE;
6505 } else {
6506 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006507 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6508 if (mTrack != NULL) {
6509 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006510 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006511 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6512 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6513 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006514 }
6515 mDevice |= (uint32_t)value;
6516 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006518 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006520 mInput->stream->common.standby(&mInput->stream->common);
6521 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6522 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 }
6524 if (reconfig) {
6525 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006526 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006527 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006528 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006529 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6530 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531 status = NO_ERROR;
6532 }
6533 if (status == NO_ERROR) {
6534 readInputParameters();
6535 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6536 }
6537 }
6538 }
6539
6540 mNewParameters.removeAt(0);
6541
6542 mParamStatus = status;
6543 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006544 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6545 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006546 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 }
6548 return reconfig;
6549}
6550
6551String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6552{
Dima Zavinfce7a472011-04-19 22:30:36 -07006553 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006554 String8 out_s8 = String8();
6555
6556 Mutex::Autolock _l(mLock);
6557 if (initCheck() != NO_ERROR) {
6558 return out_s8;
6559 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006560
Dima Zavin799a70e2011-04-18 16:57:27 -07006561 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006562 out_s8 = String8(s);
6563 free(s);
6564 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565}
6566
6567void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6568 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006569 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570
6571 switch (event) {
6572 case AudioSystem::INPUT_OPENED:
6573 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006574 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 desc.samplingRate = mSampleRate;
6576 desc.format = mFormat;
6577 desc.frameCount = mFrameCount;
6578 desc.latency = 0;
6579 param2 = &desc;
6580 break;
6581
6582 case AudioSystem::INPUT_CLOSED:
6583 default:
6584 break;
6585 }
6586 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6587}
6588
6589void AudioFlinger::RecordThread::readInputParameters()
6590{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006591 delete mRsmpInBuffer;
6592 // mRsmpInBuffer is always assigned a new[] below
6593 delete mRsmpOutBuffer;
6594 mRsmpOutBuffer = NULL;
6595 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006596 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597
Dima Zavin799a70e2011-04-18 16:57:27 -07006598 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006599 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6600 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006601 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006602 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006603 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006605 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6607
Glenn Kasten53d76db2012-03-08 12:32:47 -08006608 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 {
6610 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006611 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6612 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 if (mChannelCount == 1 && mReqChannelCount == 2) {
6614 channelCount = 1;
6615 } else {
6616 channelCount = 2;
6617 }
6618 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6619 mResampler->setSampleRate(mSampleRate);
6620 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6621 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6622
6623 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6624 if (mChannelCount == 1 && mReqChannelCount == 1) {
6625 mFrameCount >>= 1;
6626 }
6627
6628 }
6629 mRsmpInIndex = mFrameCount;
6630}
6631
6632unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6633{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006634 Mutex::Autolock _l(mLock);
6635 if (initCheck() != NO_ERROR) {
6636 return 0;
6637 }
6638
Dima Zavin799a70e2011-04-18 16:57:27 -07006639 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640}
6641
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006642uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6643{
6644 Mutex::Autolock _l(mLock);
6645 uint32_t result = 0;
6646 if (getEffectChain_l(sessionId) != 0) {
6647 result = EFFECT_SESSION;
6648 }
6649
6650 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6651 result |= TRACK_SESSION;
6652 }
6653
6654 return result;
6655}
6656
Eric Laurent59bd0da2011-08-01 09:52:20 -07006657AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6658{
6659 Mutex::Autolock _l(mLock);
6660 return mTrack;
6661}
6662
Glenn Kastenaed850d2012-01-26 09:46:34 -08006663AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006664{
6665 Mutex::Autolock _l(mLock);
6666 return mInput;
6667}
6668
6669AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6670{
6671 Mutex::Autolock _l(mLock);
6672 AudioStreamIn *input = mInput;
6673 mInput = NULL;
6674 return input;
6675}
6676
6677// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006678audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006679{
6680 if (mInput == NULL) {
6681 return NULL;
6682 }
6683 return &mInput->stream->common;
6684}
6685
6686
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687// ----------------------------------------------------------------------------
6688
Eric Laurenta4c5a552012-03-29 10:12:40 -07006689audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6690{
6691 if (!settingsAllowed()) {
6692 return 0;
6693 }
6694 Mutex::Autolock _l(mLock);
6695 return loadHwModule_l(name);
6696}
6697
6698// loadHwModule_l() must be called with AudioFlinger::mLock held
6699audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6700{
6701 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6702 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6703 ALOGW("loadHwModule() module %s already loaded", name);
6704 return mAudioHwDevs.keyAt(i);
6705 }
6706 }
6707
Eric Laurenta4c5a552012-03-29 10:12:40 -07006708 audio_hw_device_t *dev;
6709
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006710 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006711 if (rc) {
6712 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6713 return 0;
6714 }
6715
6716 mHardwareStatus = AUDIO_HW_INIT;
6717 rc = dev->init_check(dev);
6718 mHardwareStatus = AUDIO_HW_IDLE;
6719 if (rc) {
6720 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6721 return 0;
6722 }
6723
6724 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6725 (NULL != dev->set_master_volume)) {
6726 AutoMutex lock(mHardwareLock);
6727 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6728 dev->set_master_volume(dev, mMasterVolume);
6729 mHardwareStatus = AUDIO_HW_IDLE;
6730 }
6731
6732 audio_module_handle_t handle = nextUniqueId();
6733 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6734
6735 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006736 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006737
6738 return handle;
6739
6740}
6741
6742audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6743 audio_devices_t *pDevices,
6744 uint32_t *pSamplingRate,
6745 audio_format_t *pFormat,
6746 audio_channel_mask_t *pChannelMask,
6747 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006748 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749{
6750 status_t status;
6751 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006752 struct audio_config config = {
6753 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6754 channel_mask: pChannelMask ? *pChannelMask : 0,
6755 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6756 };
6757 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006758 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759
Eric Laurenta4c5a552012-03-29 10:12:40 -07006760 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6761 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006762 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006763 config.sample_rate,
6764 config.format,
6765 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006766 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767
6768 if (pDevices == NULL || *pDevices == 0) {
6769 return 0;
6770 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006771
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 Mutex::Autolock _l(mLock);
6773
Eric Laurenta4c5a552012-03-29 10:12:40 -07006774 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006775 if (outHwDev == NULL)
6776 return 0;
6777
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006778 audio_io_handle_t id = nextUniqueId();
6779
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006780 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006781
6782 status = outHwDev->open_output_stream(outHwDev,
6783 id,
6784 *pDevices,
6785 (audio_output_flags_t)flags,
6786 &config,
6787 &outStream);
6788
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006789 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006790 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006791 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006792 config.sample_rate,
6793 config.format,
6794 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006795 status);
6796
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006797 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006798 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006799
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006800 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006801 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6802 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006804 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805 } else {
6806 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006807 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 }
6809 mPlaybackThreads.add(id, thread);
6810
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006811 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6812 if (pFormat != NULL) *pFormat = config.format;
6813 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006814 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815
6816 // notify client processes of the new output creation
6817 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006818
6819 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006820 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006821 ALOGI("Using module %d has the primary audio interface", module);
6822 mPrimaryHardwareDev = outHwDev;
6823
6824 AutoMutex lock(mHardwareLock);
6825 mHardwareStatus = AUDIO_HW_SET_MODE;
6826 outHwDev->set_mode(outHwDev, mMode);
6827
6828 // Determine the level of master volume support the primary audio HAL has,
6829 // and set the initial master volume at the same time.
6830 float initialVolume = 1.0;
6831 mMasterVolumeSupportLvl = MVS_NONE;
6832
6833 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6834 if ((NULL != outHwDev->get_master_volume) &&
6835 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6836 mMasterVolumeSupportLvl = MVS_FULL;
6837 } else {
6838 mMasterVolumeSupportLvl = MVS_SETONLY;
6839 initialVolume = 1.0;
6840 }
6841
6842 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6843 if ((NULL == outHwDev->set_master_volume) ||
6844 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6845 mMasterVolumeSupportLvl = MVS_NONE;
6846 }
6847 // now that we have a primary device, initialize master volume on other devices
6848 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6849 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6850
6851 if ((dev != mPrimaryHardwareDev) &&
6852 (NULL != dev->set_master_volume)) {
6853 dev->set_master_volume(dev, initialVolume);
6854 }
6855 }
6856 mHardwareStatus = AUDIO_HW_IDLE;
6857 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6858 ? initialVolume
6859 : 1.0;
6860 mMasterVolume = initialVolume;
6861 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 return id;
6863 }
6864
6865 return 0;
6866}
6867
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006868audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6869 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870{
6871 Mutex::Autolock _l(mLock);
6872 MixerThread *thread1 = checkMixerThread_l(output1);
6873 MixerThread *thread2 = checkMixerThread_l(output2);
6874
6875 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006876 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 return 0;
6878 }
6879
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006880 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6882 thread->addOutputTrack(thread2);
6883 mPlaybackThreads.add(id, thread);
6884 // notify client processes of the new output creation
6885 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6886 return id;
6887}
6888
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006889status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890{
6891 // keep strong reference on the playback thread so that
6892 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006893 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 {
6895 Mutex::Autolock _l(mLock);
6896 thread = checkPlaybackThread_l(output);
6897 if (thread == NULL) {
6898 return BAD_VALUE;
6899 }
6900
Steve Block3856b092011-10-20 11:56:00 +01006901 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006903 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006905 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6907 dupThread->removeOutputTrack((MixerThread *)thread.get());
6908 }
6909 }
6910 }
Glenn Kastena1117922012-01-26 10:53:32 -08006911 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912 mPlaybackThreads.removeItem(output);
6913 }
6914 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006915 // The thread entity (active unit of execution) is no longer running here,
6916 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006918 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006919 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006920 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006921 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006922 out->hwDev->close_output_stream(out->hwDev, out->stream);
6923 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924 }
6925 return NO_ERROR;
6926}
6927
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006928status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929{
6930 Mutex::Autolock _l(mLock);
6931 PlaybackThread *thread = checkPlaybackThread_l(output);
6932
6933 if (thread == NULL) {
6934 return BAD_VALUE;
6935 }
6936
Steve Block3856b092011-10-20 11:56:00 +01006937 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 thread->suspend();
6939
6940 return NO_ERROR;
6941}
6942
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006943status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944{
6945 Mutex::Autolock _l(mLock);
6946 PlaybackThread *thread = checkPlaybackThread_l(output);
6947
6948 if (thread == NULL) {
6949 return BAD_VALUE;
6950 }
6951
Steve Block3856b092011-10-20 11:56:00 +01006952 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953
6954 thread->restore();
6955
6956 return NO_ERROR;
6957}
6958
Eric Laurenta4c5a552012-03-29 10:12:40 -07006959audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6960 audio_devices_t *pDevices,
6961 uint32_t *pSamplingRate,
6962 audio_format_t *pFormat,
6963 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964{
6965 status_t status;
6966 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006967 struct audio_config config = {
6968 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6969 channel_mask: pChannelMask ? *pChannelMask : 0,
6970 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6971 };
6972 uint32_t reqSamplingRate = config.sample_rate;
6973 audio_format_t reqFormat = config.format;
6974 audio_channel_mask_t reqChannels = config.channel_mask;
6975 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006976 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977
6978 if (pDevices == NULL || *pDevices == 0) {
6979 return 0;
6980 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006981
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 Mutex::Autolock _l(mLock);
6983
Eric Laurenta4c5a552012-03-29 10:12:40 -07006984 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006985 if (inHwDev == NULL)
6986 return 0;
6987
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006988 audio_io_handle_t id = nextUniqueId();
6989
6990 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006991 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006992 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006993 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006994 config.sample_rate,
6995 config.format,
6996 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 status);
6998
6999 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7000 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7001 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007002 if (status == BAD_VALUE &&
7003 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7004 (config.sample_rate <= 2 * reqSamplingRate) &&
7005 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01007006 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007007 inStream = NULL;
7008 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 }
7010
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007011 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007012 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7013
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007014 // Start record thread
7015 // RecorThread require both input and output device indication to forward to audio
7016 // pre processing modules
7017 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7018 thread = new RecordThread(this,
7019 input,
7020 reqSamplingRate,
7021 reqChannels,
7022 id,
7023 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007025 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007026 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007027 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007028 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029
Dima Zavin799a70e2011-04-18 16:57:27 -07007030 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031
7032 // notify client processes of the new input creation
7033 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7034 return id;
7035 }
7036
7037 return 0;
7038}
7039
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007040status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041{
7042 // keep strong reference on the record thread so that
7043 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007044 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 {
7046 Mutex::Autolock _l(mLock);
7047 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007048 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049 return BAD_VALUE;
7050 }
7051
Steve Block3856b092011-10-20 11:56:00 +01007052 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007053 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 mRecordThreads.removeItem(input);
7055 }
7056 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007057 // The thread entity (active unit of execution) is no longer running here,
7058 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007060 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007061 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007062 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007063 in->hwDev->close_input_stream(in->hwDev, in->stream);
7064 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065
7066 return NO_ERROR;
7067}
7068
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007069status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070{
7071 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007072 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073
7074 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7075 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007076 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078
7079 return NO_ERROR;
7080}
7081
7082
7083int AudioFlinger::newAudioSessionId()
7084{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007085 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086}
7087
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007088void AudioFlinger::acquireAudioSessionId(int audioSession)
7089{
7090 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007091 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007092 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007093 size_t num = mAudioSessionRefs.size();
7094 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007095 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007096 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7097 ref->mCnt++;
7098 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007099 return;
7100 }
7101 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007102 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7103 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007104}
7105
7106void AudioFlinger::releaseAudioSessionId(int audioSession)
7107{
7108 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007109 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007110 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007111 size_t num = mAudioSessionRefs.size();
7112 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007113 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007114 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7115 ref->mCnt--;
7116 ALOGV(" decremented refcount to %d", ref->mCnt);
7117 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007118 mAudioSessionRefs.removeAt(i);
7119 delete ref;
7120 purgeStaleEffects_l();
7121 }
7122 return;
7123 }
7124 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007125 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007126}
7127
7128void AudioFlinger::purgeStaleEffects_l() {
7129
Steve Block3856b092011-10-20 11:56:00 +01007130 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007131
7132 Vector< sp<EffectChain> > chains;
7133
7134 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7135 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7136 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7137 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007138 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7139 chains.push(ec);
7140 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007141 }
7142 }
7143 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7144 sp<RecordThread> t = mRecordThreads.valueAt(i);
7145 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7146 sp<EffectChain> ec = t->mEffectChains[j];
7147 chains.push(ec);
7148 }
7149 }
7150
7151 for (size_t i = 0; i < chains.size(); i++) {
7152 sp<EffectChain> ec = chains[i];
7153 int sessionid = ec->sessionId();
7154 sp<ThreadBase> t = ec->mThread.promote();
7155 if (t == 0) {
7156 continue;
7157 }
7158 size_t numsessionrefs = mAudioSessionRefs.size();
7159 bool found = false;
7160 for (size_t k = 0; k < numsessionrefs; k++) {
7161 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007162 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007163 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007164 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007165 found = true;
7166 break;
7167 }
7168 }
7169 if (!found) {
7170 // remove all effects from the chain
7171 while (ec->mEffects.size()) {
7172 sp<EffectModule> effect = ec->mEffects[0];
7173 effect->unPin();
7174 Mutex::Autolock _l (t->mLock);
7175 t->removeEffect_l(effect);
7176 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7177 sp<EffectHandle> handle = effect->mHandles[j].promote();
7178 if (handle != 0) {
7179 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007180 if (handle->mHasControl && handle->mEnabled) {
7181 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7182 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007183 }
7184 }
7185 AudioSystem::unregisterEffect(effect->id());
7186 }
7187 }
7188 }
7189 return;
7190}
7191
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007193AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194{
Glenn Kastena1117922012-01-26 10:53:32 -08007195 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196}
7197
7198// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007199AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200{
7201 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007202 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007203}
7204
7205// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007206AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207{
Glenn Kastena1117922012-01-26 10:53:32 -08007208 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209}
7210
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007211uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007213 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214}
7215
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007216AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007217{
7218 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7219 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007220 AudioStreamOut *output = thread->getOutput();
7221 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007222 return thread;
7223 }
7224 }
7225 return NULL;
7226}
7227
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007228uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007229{
7230 PlaybackThread *thread = primaryPlaybackThread_l();
7231
7232 if (thread == NULL) {
7233 return 0;
7234 }
7235
7236 return thread->device();
7237}
7238
Eric Laurenta011e352012-03-29 15:51:43 -07007239sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7240 int triggerSession,
7241 int listenerSession,
7242 sync_event_callback_t callBack,
7243 void *cookie)
7244{
7245 Mutex::Autolock _l(mLock);
7246
7247 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7248 status_t playStatus = NAME_NOT_FOUND;
7249 status_t recStatus = NAME_NOT_FOUND;
7250 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7251 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7252 if (playStatus == NO_ERROR) {
7253 return event;
7254 }
7255 }
7256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7257 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7258 if (recStatus == NO_ERROR) {
7259 return event;
7260 }
7261 }
7262 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7263 mPendingSyncEvents.add(event);
7264 } else {
7265 ALOGV("createSyncEvent() invalid event %d", event->type());
7266 event.clear();
7267 }
7268 return event;
7269}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007270
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271// ----------------------------------------------------------------------------
7272// Effect management
7273// ----------------------------------------------------------------------------
7274
7275
Glenn Kastenf587ba52012-01-26 16:25:10 -08007276status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277{
7278 Mutex::Autolock _l(mLock);
7279 return EffectQueryNumberEffects(numEffects);
7280}
7281
Glenn Kastenf587ba52012-01-26 16:25:10 -08007282status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283{
7284 Mutex::Autolock _l(mLock);
7285 return EffectQueryEffect(index, descriptor);
7286}
7287
Glenn Kasten5e92a782012-01-30 07:40:52 -08007288status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007289 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290{
7291 Mutex::Autolock _l(mLock);
7292 return EffectGetDescriptor(pUuid, descriptor);
7293}
7294
7295
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7297 effect_descriptor_t *pDesc,
7298 const sp<IEffectClient>& effectClient,
7299 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007300 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301 int sessionId,
7302 status_t *status,
7303 int *id,
7304 int *enabled)
7305{
7306 status_t lStatus = NO_ERROR;
7307 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007310 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007311 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312
7313 if (pDesc == NULL) {
7314 lStatus = BAD_VALUE;
7315 goto Exit;
7316 }
7317
Eric Laurent84e9a102010-09-23 16:10:16 -07007318 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007320 lStatus = PERMISSION_DENIED;
7321 goto Exit;
7322 }
7323
Dima Zavinfce7a472011-04-19 22:30:36 -07007324 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007325 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007326 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007327 lStatus = PERMISSION_DENIED;
7328 goto Exit;
7329 }
7330
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007331 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007332 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007333 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007334 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007335 lStatus = BAD_VALUE;
7336 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007337 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007338 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007339 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007340 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007341 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007342 }
7343 }
7344
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 {
7346 Mutex::Autolock _l(mLock);
7347
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348
7349 if (!EffectIsNullUuid(&pDesc->uuid)) {
7350 // if uuid is specified, request effect descriptor
7351 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7352 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007353 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 goto Exit;
7355 }
7356 } else {
7357 // if uuid is not specified, look for an available implementation
7358 // of the required type in effect factory
7359 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007360 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361 lStatus = BAD_VALUE;
7362 goto Exit;
7363 }
7364 uint32_t numEffects = 0;
7365 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007366 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 bool found = false;
7368
7369 lStatus = EffectQueryNumberEffects(&numEffects);
7370 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007371 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 goto Exit;
7373 }
7374 for (uint32_t i = 0; i < numEffects; i++) {
7375 lStatus = EffectQueryEffect(i, &desc);
7376 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007377 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 continue;
7379 }
7380 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7381 // If matching type found save effect descriptor. If the session is
7382 // 0 and the effect is not auxiliary, continue enumeration in case
7383 // an auxiliary version of this effect type is available
7384 found = true;
7385 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007386 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7388 break;
7389 }
7390 }
7391 }
7392 if (!found) {
7393 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007394 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395 goto Exit;
7396 }
7397 // For same effect type, chose auxiliary version over insert version if
7398 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007399 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7401 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7402 }
7403 }
7404
7405 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007406 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7408 lStatus = INVALID_OPERATION;
7409 goto Exit;
7410 }
7411
Eric Laurent59255e42011-07-27 19:49:51 -07007412 // check recording permission for visualizer
7413 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7414 !recordingAllowed()) {
7415 lStatus = PERMISSION_DENIED;
7416 goto Exit;
7417 }
7418
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 // return effect descriptor
7420 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7421
7422 // If output is not specified try to find a matching audio session ID in one of the
7423 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007424 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7425 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426 // Note: io is never 0 when creating an effect on an input
7427 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007428 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7430 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007431 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007432 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007435 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007436 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7437 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7438 io = mRecordThreads.keyAt(i);
7439 break;
7440 }
7441 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007442 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007443 // If no output thread contains the requested session ID, default to
7444 // first output. The effect chain will be moved to the correct output
7445 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007446 if (io == 0 && mPlaybackThreads.size()) {
7447 io = mPlaybackThreads.keyAt(0);
7448 }
Steve Block3856b092011-10-20 11:56:00 +01007449 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007450 }
7451 ThreadBase *thread = checkRecordThread_l(io);
7452 if (thread == NULL) {
7453 thread = checkPlaybackThread_l(io);
7454 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007455 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456 lStatus = BAD_VALUE;
7457 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007460
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007461 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007463 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007464 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7465 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 if (handle != 0 && id != NULL) {
7467 *id = handle->id();
7468 }
7469 }
7470
7471Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007472 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 *status = lStatus;
7474 }
7475 return handle;
7476}
7477
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007478status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7479 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007480{
Steve Block3856b092011-10-20 11:56:00 +01007481 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007482 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007483 Mutex::Autolock _l(mLock);
7484 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007485 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007486 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 }
Eric Laurentde070132010-07-13 04:45:46 -07007488 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7489 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007490 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007491 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 }
Eric Laurentde070132010-07-13 04:45:46 -07007493 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7494 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007495 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007496 return BAD_VALUE;
7497 }
7498
7499 Mutex::Autolock _dl(dstThread->mLock);
7500 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007501 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007502
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503 return NO_ERROR;
7504}
7505
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007506// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007507status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007508 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007509 AudioFlinger::PlaybackThread *dstThread,
7510 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007511{
Steve Block3856b092011-10-20 11:56:00 +01007512 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007513 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007514
Eric Laurent59255e42011-07-27 19:49:51 -07007515 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007516 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007517 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007518 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007519 return INVALID_OPERATION;
7520 }
7521
Eric Laurent39e94f82010-07-28 01:32:47 -07007522 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007523 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007524 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007525 // removed.
7526 srcThread->removeEffectChain_l(chain);
7527
7528 // transfer all effects one by one so that new effect chain is created on new thread with
7529 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007530 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007531 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007532 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007533 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7534 while (effect != 0) {
7535 srcThread->removeEffect_l(effect);
7536 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007537 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7538 if (effect->state() == EffectModule::ACTIVE ||
7539 effect->state() == EffectModule::STOPPING) {
7540 effect->start();
7541 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007542 // if the move request is not received from audio policy manager, the effect must be
7543 // re-registered with the new strategy and output
7544 if (dstChain == 0) {
7545 dstChain = effect->chain().promote();
7546 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007547 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007548 srcThread->addEffect_l(effect);
7549 return NO_INIT;
7550 }
7551 strategy = dstChain->strategy();
7552 }
7553 if (reRegister) {
7554 AudioSystem::unregisterEffect(effect->id());
7555 AudioSystem::registerEffect(&effect->desc(),
7556 dstOutput,
7557 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007558 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007559 effect->id());
7560 }
Eric Laurentde070132010-07-13 04:45:46 -07007561 effect = chain->getEffectFromId_l(0);
7562 }
7563
7564 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565}
7566
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007567
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007569sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570 const sp<AudioFlinger::Client>& client,
7571 const sp<IEffectClient>& effectClient,
7572 int32_t priority,
7573 int sessionId,
7574 effect_descriptor_t *desc,
7575 int *enabled,
7576 status_t *status
7577 )
7578{
7579 sp<EffectModule> effect;
7580 sp<EffectHandle> handle;
7581 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007583 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584 bool effectCreated = false;
7585 bool effectRegistered = false;
7586
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007587 lStatus = initCheck();
7588 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007589 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 goto Exit;
7591 }
7592
7593 // Do not allow effects with session ID 0 on direct output or duplicating threads
7594 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007595 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007596 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007597 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 lStatus = BAD_VALUE;
7599 goto Exit;
7600 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007601 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007602 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007603 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007604 desc->name, desc->flags, mType);
7605 lStatus = BAD_VALUE;
7606 goto Exit;
7607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608
Steve Block3856b092011-10-20 11:56:00 +01007609 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610
7611 { // scope for mLock
7612 Mutex::Autolock _l(mLock);
7613
7614 // check for existing effect chain with the requested audio session
7615 chain = getEffectChain_l(sessionId);
7616 if (chain == 0) {
7617 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007618 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 chain = new EffectChain(this, sessionId);
7620 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007621 chain->setStrategy(getStrategyForSession_l(sessionId));
7622 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007624 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625 }
7626
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007627 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628
7629 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007630 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007632 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633 if (lStatus != NO_ERROR) {
7634 goto Exit;
7635 }
7636 effectRegistered = true;
7637 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007638 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 lStatus = effect->status();
7640 if (lStatus != NO_ERROR) {
7641 goto Exit;
7642 }
Eric Laurentcab11242010-07-15 12:50:15 -07007643 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644 if (lStatus != NO_ERROR) {
7645 goto Exit;
7646 }
7647 effectCreated = true;
7648
7649 effect->setDevice(mDevice);
7650 effect->setMode(mAudioFlinger->getMode());
7651 }
7652 // create effect handle and connect it to effect module
7653 handle = new EffectHandle(effect, client, effectClient, priority);
7654 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007655 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 *enabled = (int)effect->isEnabled();
7657 }
7658 }
7659
7660Exit:
7661 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007662 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007664 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665 }
7666 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007667 AudioSystem::unregisterEffect(effect->id());
7668 }
7669 if (chainCreated) {
7670 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 }
7672 handle.clear();
7673 }
7674
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007675 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007676 *status = lStatus;
7677 }
7678 return handle;
7679}
7680
Eric Laurent717e1282012-06-29 16:36:52 -07007681sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7682{
7683 Mutex::Autolock _l(mLock);
7684 return getEffect_l(sessionId, effectId);
7685}
7686
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007687sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7688{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007689 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007690 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007691}
7692
Eric Laurentde070132010-07-13 04:45:46 -07007693// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7694// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007695status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007696{
7697 // check for existing effect chain with the requested audio session
7698 int sessionId = effect->sessionId();
7699 sp<EffectChain> chain = getEffectChain_l(sessionId);
7700 bool chainCreated = false;
7701
7702 if (chain == 0) {
7703 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007704 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007705 chain = new EffectChain(this, sessionId);
7706 addEffectChain_l(chain);
7707 chain->setStrategy(getStrategyForSession_l(sessionId));
7708 chainCreated = true;
7709 }
Steve Block3856b092011-10-20 11:56:00 +01007710 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007711
7712 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007713 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007714 this, effect->desc().name, chain.get());
7715 return BAD_VALUE;
7716 }
7717
7718 status_t status = chain->addEffect_l(effect);
7719 if (status != NO_ERROR) {
7720 if (chainCreated) {
7721 removeEffectChain_l(chain);
7722 }
7723 return status;
7724 }
7725
7726 effect->setDevice(mDevice);
7727 effect->setMode(mAudioFlinger->getMode());
7728 return NO_ERROR;
7729}
7730
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007731void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007732
Steve Block3856b092011-10-20 11:56:00 +01007733 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007735 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7736 detachAuxEffect_l(effect->id());
7737 }
7738
7739 sp<EffectChain> chain = effect->chain().promote();
7740 if (chain != 0) {
7741 // remove effect chain if removing last effect
7742 if (chain->removeEffect_l(effect) == 0) {
7743 removeEffectChain_l(chain);
7744 }
7745 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007746 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007747 }
7748}
7749
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007750void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007751 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007752{
7753 effectChains = mEffectChains;
7754 for (size_t i = 0; i < mEffectChains.size(); i++) {
7755 mEffectChains[i]->lock();
7756 }
7757}
7758
7759void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007760 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007761{
7762 for (size_t i = 0; i < effectChains.size(); i++) {
7763 effectChains[i]->unlock();
7764 }
7765}
7766
7767sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7768{
7769 Mutex::Autolock _l(mLock);
7770 return getEffectChain_l(sessionId);
7771}
7772
7773sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7774{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007775 size_t size = mEffectChains.size();
7776 for (size_t i = 0; i < size; i++) {
7777 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007778 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007779 }
7780 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007781 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007782}
7783
Glenn Kastenf78aee72012-01-04 11:00:47 -08007784void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007785{
7786 Mutex::Autolock _l(mLock);
7787 size_t size = mEffectChains.size();
7788 for (size_t i = 0; i < size; i++) {
7789 mEffectChains[i]->setMode_l(mode);
7790 }
7791}
7792
7793void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007794 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007795 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007796
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007798 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 // delete the effect module if removing last handle on it
7800 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007801 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007802 removeEffect_l(effect);
7803 AudioSystem::unregisterEffect(effect->id());
7804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007805 }
7806}
7807
7808status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7809{
7810 int session = chain->sessionId();
7811 int16_t *buffer = mMixBuffer;
7812 bool ownsBuffer = false;
7813
Steve Block3856b092011-10-20 11:56:00 +01007814 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815 if (session > 0) {
7816 // Only one effect chain can be present in direct output thread and it uses
7817 // the mix buffer as input
7818 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007819 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 buffer = new int16_t[numSamples];
7821 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007822 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 ownsBuffer = true;
7824 }
7825
7826 // Attach all tracks with same session ID to this chain.
7827 for (size_t i = 0; i < mTracks.size(); ++i) {
7828 sp<Track> track = mTracks[i];
7829 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007830 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007832 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007833 }
7834 }
7835
7836 // indicate all active tracks in the chain
7837 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7838 sp<Track> track = mActiveTracks[i].promote();
7839 if (track == 0) continue;
7840 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007841 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007842 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007843 }
7844 }
7845 }
7846
7847 chain->setInBuffer(buffer, ownsBuffer);
7848 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007849 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007850 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007851 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7852 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007854 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7855 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007856 // Effect chain for other sessions are inserted at beginning of effect
7857 // chains list to be processed before output mix effects. Relative order between other
7858 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859 size_t size = mEffectChains.size();
7860 size_t i = 0;
7861 for (i = 0; i < size; i++) {
7862 if (mEffectChains[i]->sessionId() < session) break;
7863 }
7864 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007865 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866
7867 return NO_ERROR;
7868}
7869
7870size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7871{
7872 int session = chain->sessionId();
7873
Steve Block3856b092011-10-20 11:56:00 +01007874 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875
7876 for (size_t i = 0; i < mEffectChains.size(); i++) {
7877 if (chain == mEffectChains[i]) {
7878 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007879 // detach all active tracks from the chain
7880 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7881 sp<Track> track = mActiveTracks[i].promote();
7882 if (track == 0) continue;
7883 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007884 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007885 chain.get(), session);
7886 chain->decActiveTrackCnt();
7887 }
7888 }
7889
Mathias Agopian65ab4712010-07-14 17:59:35 -07007890 // detach all tracks with same session ID from this chain
7891 for (size_t i = 0; i < mTracks.size(); ++i) {
7892 sp<Track> track = mTracks[i];
7893 if (session == track->sessionId()) {
7894 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007895 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 }
7897 }
Eric Laurentde070132010-07-13 04:45:46 -07007898 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899 }
7900 }
7901 return mEffectChains.size();
7902}
7903
Eric Laurentde070132010-07-13 04:45:46 -07007904status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7905 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906{
7907 Mutex::Autolock _l(mLock);
7908 return attachAuxEffect_l(track, EffectId);
7909}
7910
Eric Laurentde070132010-07-13 04:45:46 -07007911status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7912 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007913{
7914 status_t status = NO_ERROR;
7915
7916 if (EffectId == 0) {
7917 track->setAuxBuffer(0, NULL);
7918 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007919 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7920 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921 if (effect != 0) {
7922 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7923 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7924 } else {
7925 status = INVALID_OPERATION;
7926 }
7927 } else {
7928 status = BAD_VALUE;
7929 }
7930 }
7931 return status;
7932}
7933
7934void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7935{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007936 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 sp<Track> track = mTracks[i];
7938 if (track->auxEffectId() == effectId) {
7939 attachAuxEffect_l(track, 0);
7940 }
7941 }
7942}
7943
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007944status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7945{
7946 // only one chain per input thread
7947 if (mEffectChains.size() != 0) {
7948 return INVALID_OPERATION;
7949 }
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007951
7952 chain->setInBuffer(NULL);
7953 chain->setOutBuffer(NULL);
7954
Eric Laurent59255e42011-07-27 19:49:51 -07007955 checkSuspendOnAddEffectChain_l(chain);
7956
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007957 mEffectChains.add(chain);
7958
7959 return NO_ERROR;
7960}
7961
7962size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7963{
Steve Block3856b092011-10-20 11:56:00 +01007964 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007965 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007966 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7967 chain.get(), mEffectChains.size(), this);
7968 if (mEffectChains.size() == 1) {
7969 mEffectChains.removeAt(0);
7970 }
7971 return 0;
7972}
7973
Mathias Agopian65ab4712010-07-14 17:59:35 -07007974// ----------------------------------------------------------------------------
7975// EffectModule implementation
7976// ----------------------------------------------------------------------------
7977
7978#undef LOG_TAG
7979#define LOG_TAG "AudioFlinger::EffectModule"
7980
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007981AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007982 const wp<AudioFlinger::EffectChain>& chain,
7983 effect_descriptor_t *desc,
7984 int id,
7985 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007986 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7987 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7988 // mDescriptor is set below
7989 // mConfig is set by configure() and not used before then
7990 mEffectInterface(NULL),
7991 mStatus(NO_INIT), mState(IDLE),
7992 // mMaxDisableWaitCnt is set by configure() and not used before then
7993 // mDisableWaitCnt is set by process() and updateState() and not used before then
7994 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007995{
Steve Block3856b092011-10-20 11:56:00 +01007996 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007998 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999 return;
8000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001
8002 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
8003
8004 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008005 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008006
8007 if (mStatus != NO_ERROR) {
8008 return;
8009 }
8010 lStatus = init();
8011 if (lStatus < 0) {
8012 mStatus = lStatus;
8013 goto Error;
8014 }
8015
Steve Block3856b092011-10-20 11:56:00 +01008016 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017 return;
8018Error:
8019 EffectRelease(mEffectInterface);
8020 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008021 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022}
8023
8024AudioFlinger::EffectModule::~EffectModule()
8025{
Steve Block3856b092011-10-20 11:56:00 +01008026 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008028 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8029 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8030 sp<ThreadBase> thread = mThread.promote();
8031 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008032 audio_stream_t *stream = thread->stream();
8033 if (stream != NULL) {
8034 stream->remove_audio_effect(stream, mEffectInterface);
8035 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008036 }
8037 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008038 // release effect engine
8039 EffectRelease(mEffectInterface);
8040 }
8041}
8042
Glenn Kasten435dbe62012-01-30 10:15:48 -08008043status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044{
8045 status_t status;
8046
8047 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048 int priority = handle->priority();
8049 size_t size = mHandles.size();
8050 sp<EffectHandle> h;
8051 size_t i;
8052 for (i = 0; i < size; i++) {
8053 h = mHandles[i].promote();
8054 if (h == 0) continue;
8055 if (h->priority() <= priority) break;
8056 }
8057 // if inserted in first place, move effect control from previous owner to this handle
8058 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008059 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008061 enabled = h->enabled();
8062 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 }
Eric Laurent59255e42011-07-27 19:49:51 -07008064 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 status = NO_ERROR;
8066 } else {
8067 status = ALREADY_EXISTS;
8068 }
Steve Block3856b092011-10-20 11:56:00 +01008069 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008070 mHandles.insertAt(handle, i);
8071 return status;
8072}
8073
8074size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8075{
8076 Mutex::Autolock _l(mLock);
8077 size_t size = mHandles.size();
8078 size_t i;
8079 for (i = 0; i < size; i++) {
8080 if (mHandles[i] == handle) break;
8081 }
8082 if (i == size) {
8083 return size;
8084 }
Steve Block3856b092011-10-20 11:56:00 +01008085 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008086
8087 bool enabled = false;
8088 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008089 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008090 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008091 enabled = hdl->enabled();
8092 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093 mHandles.removeAt(i);
8094 size = mHandles.size();
8095 // if removed from first place, move effect control from this handle to next in line
8096 if (i == 0 && size != 0) {
8097 sp<EffectHandle> h = mHandles[0].promote();
8098 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008099 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 }
8101 }
8102
Eric Laurentec437d82011-07-26 20:54:46 -07008103 // Prevent calls to process() and other functions on effect interface from now on.
8104 // The effect engine will be released by the destructor when the last strong reference on
8105 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008106 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008107 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008108 }
8109
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 return size;
8111}
8112
Eric Laurent59255e42011-07-27 19:49:51 -07008113sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8114{
8115 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008116 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008117}
8118
Glenn Kasten58123c32012-02-03 10:32:24 -08008119void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008121 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008122 // keep a strong reference on this EffectModule to avoid calling the
8123 // destructor before we exit
8124 sp<EffectModule> keep(this);
8125 {
8126 sp<ThreadBase> thread = mThread.promote();
8127 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008128 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129 }
8130 }
8131}
8132
8133void AudioFlinger::EffectModule::updateState() {
8134 Mutex::Autolock _l(mLock);
8135
8136 switch (mState) {
8137 case RESTART:
8138 reset_l();
8139 // FALL THROUGH
8140
8141 case STARTING:
8142 // clear auxiliary effect input buffer for next accumulation
8143 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8144 memset(mConfig.inputCfg.buffer.raw,
8145 0,
8146 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8147 }
8148 start_l();
8149 mState = ACTIVE;
8150 break;
8151 case STOPPING:
8152 stop_l();
8153 mDisableWaitCnt = mMaxDisableWaitCnt;
8154 mState = STOPPED;
8155 break;
8156 case STOPPED:
8157 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8158 // turn off sequence.
8159 if (--mDisableWaitCnt == 0) {
8160 reset_l();
8161 mState = IDLE;
8162 }
8163 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008164 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008165 break;
8166 }
8167}
8168
8169void AudioFlinger::EffectModule::process()
8170{
8171 Mutex::Autolock _l(mLock);
8172
Eric Laurentec437d82011-07-26 20:54:46 -07008173 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 mConfig.inputCfg.buffer.raw == NULL ||
8175 mConfig.outputCfg.buffer.raw == NULL) {
8176 return;
8177 }
8178
Eric Laurent8f45bd72010-08-31 13:50:07 -07008179 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8181 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008182 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008184 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 }
8186
8187 // do the actual processing in the effect engine
8188 int ret = (*mEffectInterface)->process(mEffectInterface,
8189 &mConfig.inputCfg.buffer,
8190 &mConfig.outputCfg.buffer);
8191
8192 // force transition to IDLE state when engine is ready
8193 if (mState == STOPPED && ret == -ENODATA) {
8194 mDisableWaitCnt = 1;
8195 }
8196
8197 // clear auxiliary effect input buffer for next accumulation
8198 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008199 memset(mConfig.inputCfg.buffer.raw, 0,
8200 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008201 }
8202 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008203 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8204 // If an insert effect is idle and input buffer is different from output buffer,
8205 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008207 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008208 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8209 int16_t *in = mConfig.inputCfg.buffer.s16;
8210 int16_t *out = mConfig.outputCfg.buffer.s16;
8211 for (size_t i = 0; i < frameCnt; i++) {
8212 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214 }
8215 }
8216}
8217
8218void AudioFlinger::EffectModule::reset_l()
8219{
8220 if (mEffectInterface == NULL) {
8221 return;
8222 }
8223 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8224}
8225
8226status_t AudioFlinger::EffectModule::configure()
8227{
8228 uint32_t channels;
8229 if (mEffectInterface == NULL) {
8230 return NO_INIT;
8231 }
8232
8233 sp<ThreadBase> thread = mThread.promote();
8234 if (thread == 0) {
8235 return DEAD_OBJECT;
8236 }
8237
8238 // TODO: handle configuration of effects replacing track process
8239 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008240 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008241 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008242 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243 }
8244
8245 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008246 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008247 } else {
8248 mConfig.inputCfg.channels = channels;
8249 }
8250 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008251 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8252 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253 mConfig.inputCfg.samplingRate = thread->sampleRate();
8254 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8255 mConfig.inputCfg.bufferProvider.cookie = NULL;
8256 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8257 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8258 mConfig.outputCfg.bufferProvider.cookie = NULL;
8259 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8260 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8261 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8262 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008263 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008264 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008265 // - in other sessions:
8266 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8267 // other effect: overwrites output buffer: input buffer == output buffer
8268 // Auxiliary effect:
8269 // accumulates in output buffer: input buffer != output buffer
8270 // Therefore: accumulate <=> input buffer != output buffer
8271 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8272 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8273 } else {
8274 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8275 }
8276 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8277 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8278 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8279 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8280
Steve Block3856b092011-10-20 11:56:00 +01008281 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008282 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8283
Mathias Agopian65ab4712010-07-14 17:59:35 -07008284 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008285 uint32_t size = sizeof(int);
8286 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008287 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008288 sizeof(effect_config_t),
8289 &mConfig,
8290 &size,
8291 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292 if (status == 0) {
8293 status = cmdStatus;
8294 }
8295
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008296 if (status == 0 &&
8297 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8298 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8299 effect_param_t *p = (effect_param_t *)buf32;
8300
8301 p->psize = sizeof(uint32_t);
8302 p->vsize = sizeof(uint32_t);
8303 size = sizeof(int);
8304 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8305
8306 uint32_t latency = 0;
8307 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8308 if (pbt != NULL) {
8309 latency = pbt->latency_l();
8310 }
8311
8312 *((int32_t *)p->data + 1)= latency;
8313 (*mEffectInterface)->command(mEffectInterface,
8314 EFFECT_CMD_SET_PARAM,
8315 sizeof(effect_param_t) + 8,
8316 &buf32,
8317 &size,
8318 &cmdStatus);
8319 }
8320
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8322 (1000 * mConfig.outputCfg.buffer.frameCount);
8323
8324 return status;
8325}
8326
8327status_t AudioFlinger::EffectModule::init()
8328{
8329 Mutex::Autolock _l(mLock);
8330 if (mEffectInterface == NULL) {
8331 return NO_INIT;
8332 }
8333 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008334 uint32_t size = sizeof(status_t);
8335 status_t status = (*mEffectInterface)->command(mEffectInterface,
8336 EFFECT_CMD_INIT,
8337 0,
8338 NULL,
8339 &size,
8340 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341 if (status == 0) {
8342 status = cmdStatus;
8343 }
8344 return status;
8345}
8346
Eric Laurentec35a142011-10-05 17:42:25 -07008347status_t AudioFlinger::EffectModule::start()
8348{
8349 Mutex::Autolock _l(mLock);
8350 return start_l();
8351}
8352
Mathias Agopian65ab4712010-07-14 17:59:35 -07008353status_t AudioFlinger::EffectModule::start_l()
8354{
8355 if (mEffectInterface == NULL) {
8356 return NO_INIT;
8357 }
8358 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008359 uint32_t size = sizeof(status_t);
8360 status_t status = (*mEffectInterface)->command(mEffectInterface,
8361 EFFECT_CMD_ENABLE,
8362 0,
8363 NULL,
8364 &size,
8365 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008366 if (status == 0) {
8367 status = cmdStatus;
8368 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008369 if (status == 0 &&
8370 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8371 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8372 sp<ThreadBase> thread = mThread.promote();
8373 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008374 audio_stream_t *stream = thread->stream();
8375 if (stream != NULL) {
8376 stream->add_audio_effect(stream, mEffectInterface);
8377 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008378 }
8379 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380 return status;
8381}
8382
Eric Laurentec437d82011-07-26 20:54:46 -07008383status_t AudioFlinger::EffectModule::stop()
8384{
8385 Mutex::Autolock _l(mLock);
8386 return stop_l();
8387}
8388
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389status_t AudioFlinger::EffectModule::stop_l()
8390{
8391 if (mEffectInterface == NULL) {
8392 return NO_INIT;
8393 }
8394 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008395 uint32_t size = sizeof(status_t);
8396 status_t status = (*mEffectInterface)->command(mEffectInterface,
8397 EFFECT_CMD_DISABLE,
8398 0,
8399 NULL,
8400 &size,
8401 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008402 if (status == 0) {
8403 status = cmdStatus;
8404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008405 if (status == 0 &&
8406 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8407 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8408 sp<ThreadBase> thread = mThread.promote();
8409 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008410 audio_stream_t *stream = thread->stream();
8411 if (stream != NULL) {
8412 stream->remove_audio_effect(stream, mEffectInterface);
8413 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008414 }
8415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416 return status;
8417}
8418
Eric Laurent25f43952010-07-28 05:40:18 -07008419status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8420 uint32_t cmdSize,
8421 void *pCmdData,
8422 uint32_t *replySize,
8423 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424{
8425 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008426// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427
Eric Laurentec437d82011-07-26 20:54:46 -07008428 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429 return NO_INIT;
8430 }
Eric Laurent25f43952010-07-28 05:40:18 -07008431 status_t status = (*mEffectInterface)->command(mEffectInterface,
8432 cmdCode,
8433 cmdSize,
8434 pCmdData,
8435 replySize,
8436 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008438 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 for (size_t i = 1; i < mHandles.size(); i++) {
8440 sp<EffectHandle> h = mHandles[i].promote();
8441 if (h != 0) {
8442 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8443 }
8444 }
8445 }
8446 return status;
8447}
8448
8449status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8450{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008451
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008453 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454
8455 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008456 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8457 if (enabled && status != NO_ERROR) {
8458 return status;
8459 }
8460
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 switch (mState) {
8462 // going from disabled to enabled
8463 case IDLE:
8464 mState = STARTING;
8465 break;
8466 case STOPPED:
8467 mState = RESTART;
8468 break;
8469 case STOPPING:
8470 mState = ACTIVE;
8471 break;
8472
8473 // going from enabled to disabled
8474 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008475 mState = STOPPED;
8476 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477 case STARTING:
8478 mState = IDLE;
8479 break;
8480 case ACTIVE:
8481 mState = STOPPING;
8482 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008483 case DESTROYED:
8484 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008485 }
8486 for (size_t i = 1; i < mHandles.size(); i++) {
8487 sp<EffectHandle> h = mHandles[i].promote();
8488 if (h != 0) {
8489 h->setEnabled(enabled);
8490 }
8491 }
8492 }
8493 return NO_ERROR;
8494}
8495
Glenn Kastenc59c0042012-02-02 14:06:11 -08008496bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497{
8498 switch (mState) {
8499 case RESTART:
8500 case STARTING:
8501 case ACTIVE:
8502 return true;
8503 case IDLE:
8504 case STOPPING:
8505 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008506 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 default:
8508 return false;
8509 }
8510}
8511
Glenn Kastenc59c0042012-02-02 14:06:11 -08008512bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008513{
8514 switch (mState) {
8515 case RESTART:
8516 case ACTIVE:
8517 case STOPPING:
8518 case STOPPED:
8519 return true;
8520 case IDLE:
8521 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008522 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008523 default:
8524 return false;
8525 }
8526}
8527
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8529{
8530 Mutex::Autolock _l(mLock);
8531 status_t status = NO_ERROR;
8532
8533 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8534 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008535 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008536 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8537 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 status_t cmdStatus;
8539 uint32_t volume[2];
8540 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008541 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008542 volume[0] = *left;
8543 volume[1] = *right;
8544 if (controller) {
8545 pVolume = volume;
8546 }
Eric Laurent25f43952010-07-28 05:40:18 -07008547 status = (*mEffectInterface)->command(mEffectInterface,
8548 EFFECT_CMD_SET_VOLUME,
8549 size,
8550 volume,
8551 &size,
8552 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008553 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8554 *left = volume[0];
8555 *right = volume[1];
8556 }
8557 }
8558 return status;
8559}
8560
8561status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8562{
8563 Mutex::Autolock _l(mLock);
8564 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008565 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8566 // audio pre processing modules on RecordThread can receive both output and
8567 // input device indication in the same call
8568 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8569 if (dev) {
8570 status_t cmdStatus;
8571 uint32_t size = sizeof(status_t);
8572
8573 status = (*mEffectInterface)->command(mEffectInterface,
8574 EFFECT_CMD_SET_DEVICE,
8575 sizeof(uint32_t),
8576 &dev,
8577 &size,
8578 &cmdStatus);
8579 if (status == NO_ERROR) {
8580 status = cmdStatus;
8581 }
8582 }
8583 dev = device & AUDIO_DEVICE_IN_ALL;
8584 if (dev) {
8585 status_t cmdStatus;
8586 uint32_t size = sizeof(status_t);
8587
8588 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8589 EFFECT_CMD_SET_INPUT_DEVICE,
8590 sizeof(uint32_t),
8591 &dev,
8592 &size,
8593 &cmdStatus);
8594 if (status2 == NO_ERROR) {
8595 status2 = cmdStatus;
8596 }
8597 if (status == NO_ERROR) {
8598 status = status2;
8599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600 }
8601 }
8602 return status;
8603}
8604
Glenn Kastenf78aee72012-01-04 11:00:47 -08008605status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606{
8607 Mutex::Autolock _l(mLock);
8608 status_t status = NO_ERROR;
8609 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008611 uint32_t size = sizeof(status_t);
8612 status = (*mEffectInterface)->command(mEffectInterface,
8613 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008614 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008615 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008616 &size,
8617 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 if (status == NO_ERROR) {
8619 status = cmdStatus;
8620 }
8621 }
8622 return status;
8623}
8624
Eric Laurent59255e42011-07-27 19:49:51 -07008625void AudioFlinger::EffectModule::setSuspended(bool suspended)
8626{
8627 Mutex::Autolock _l(mLock);
8628 mSuspended = suspended;
8629}
Glenn Kastena3a85482012-01-04 11:01:11 -08008630
8631bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008632{
8633 Mutex::Autolock _l(mLock);
8634 return mSuspended;
8635}
8636
Mathias Agopian65ab4712010-07-14 17:59:35 -07008637status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8638{
8639 const size_t SIZE = 256;
8640 char buffer[SIZE];
8641 String8 result;
8642
8643 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8644 result.append(buffer);
8645
8646 bool locked = tryLock(mLock);
8647 // failed to lock - AudioFlinger is probably deadlocked
8648 if (!locked) {
8649 result.append("\t\tCould not lock Fx mutex:\n");
8650 }
8651
8652 result.append("\t\tSession Status State Engine:\n");
8653 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8654 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8655 result.append(buffer);
8656
8657 result.append("\t\tDescriptor:\n");
8658 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8659 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8660 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8661 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8662 result.append(buffer);
8663 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8664 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8665 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8666 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8667 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008668 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008669 mDescriptor.apiVersion,
8670 mDescriptor.flags);
8671 result.append(buffer);
8672 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8673 mDescriptor.name);
8674 result.append(buffer);
8675 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8676 mDescriptor.implementor);
8677 result.append(buffer);
8678
8679 result.append("\t\t- Input configuration:\n");
8680 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8681 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8682 (uint32_t)mConfig.inputCfg.buffer.raw,
8683 mConfig.inputCfg.buffer.frameCount,
8684 mConfig.inputCfg.samplingRate,
8685 mConfig.inputCfg.channels,
8686 mConfig.inputCfg.format);
8687 result.append(buffer);
8688
8689 result.append("\t\t- Output configuration:\n");
8690 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8691 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8692 (uint32_t)mConfig.outputCfg.buffer.raw,
8693 mConfig.outputCfg.buffer.frameCount,
8694 mConfig.outputCfg.samplingRate,
8695 mConfig.outputCfg.channels,
8696 mConfig.outputCfg.format);
8697 result.append(buffer);
8698
8699 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8700 result.append(buffer);
8701 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8702 for (size_t i = 0; i < mHandles.size(); ++i) {
8703 sp<EffectHandle> handle = mHandles[i].promote();
8704 if (handle != 0) {
8705 handle->dump(buffer, SIZE);
8706 result.append(buffer);
8707 }
8708 }
8709
8710 result.append("\n");
8711
8712 write(fd, result.string(), result.length());
8713
8714 if (locked) {
8715 mLock.unlock();
8716 }
8717
8718 return NO_ERROR;
8719}
8720
8721// ----------------------------------------------------------------------------
8722// EffectHandle implementation
8723// ----------------------------------------------------------------------------
8724
8725#undef LOG_TAG
8726#define LOG_TAG "AudioFlinger::EffectHandle"
8727
8728AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8729 const sp<AudioFlinger::Client>& client,
8730 const sp<IEffectClient>& effectClient,
8731 int32_t priority)
8732 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008733 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008734 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735{
Steve Block3856b092011-10-20 11:56:00 +01008736 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008738 if (client == 0) {
8739 return;
8740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008741 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8742 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8743 if (mCblkMemory != 0) {
8744 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8745
Glenn Kastena0d68332012-01-27 16:47:15 -08008746 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747 new(mCblk) effect_param_cblk_t();
8748 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008751 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752 return;
8753 }
8754}
8755
8756AudioFlinger::EffectHandle::~EffectHandle()
8757{
Steve Block3856b092011-10-20 11:56:00 +01008758 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008759 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008760 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761}
8762
8763status_t AudioFlinger::EffectHandle::enable()
8764{
Steve Block3856b092011-10-20 11:56:00 +01008765 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766 if (!mHasControl) return INVALID_OPERATION;
8767 if (mEffect == 0) return DEAD_OBJECT;
8768
Eric Laurentdb7c0792011-08-10 10:37:50 -07008769 if (mEnabled) {
8770 return NO_ERROR;
8771 }
8772
Eric Laurent59255e42011-07-27 19:49:51 -07008773 mEnabled = true;
8774
8775 sp<ThreadBase> thread = mEffect->thread().promote();
8776 if (thread != 0) {
8777 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8778 }
8779
8780 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8781 if (mEffect->suspended()) {
8782 return NO_ERROR;
8783 }
8784
Eric Laurentdb7c0792011-08-10 10:37:50 -07008785 status_t status = mEffect->setEnabled(true);
8786 if (status != NO_ERROR) {
8787 if (thread != 0) {
8788 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8789 }
8790 mEnabled = false;
8791 }
8792 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008793}
8794
8795status_t AudioFlinger::EffectHandle::disable()
8796{
Steve Block3856b092011-10-20 11:56:00 +01008797 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008799 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008800
Eric Laurentdb7c0792011-08-10 10:37:50 -07008801 if (!mEnabled) {
8802 return NO_ERROR;
8803 }
Eric Laurent59255e42011-07-27 19:49:51 -07008804 mEnabled = false;
8805
8806 if (mEffect->suspended()) {
8807 return NO_ERROR;
8808 }
8809
8810 status_t status = mEffect->setEnabled(false);
8811
8812 sp<ThreadBase> thread = mEffect->thread().promote();
8813 if (thread != 0) {
8814 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8815 }
8816
8817 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818}
8819
8820void AudioFlinger::EffectHandle::disconnect()
8821{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008822 disconnect(true);
8823}
8824
Glenn Kasten58123c32012-02-03 10:32:24 -08008825void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008826{
Glenn Kasten58123c32012-02-03 10:32:24 -08008827 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008828 if (mEffect == 0) {
8829 return;
8830 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008831 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008832
Eric Laurenta85a74a2011-10-19 11:44:54 -07008833 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008834 sp<ThreadBase> thread = mEffect->thread().promote();
8835 if (thread != 0) {
8836 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8837 }
Eric Laurent59255e42011-07-27 19:49:51 -07008838 }
8839
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 // release sp on module => module destructor can be called now
8841 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008843 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008844 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008845 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8846 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008847 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008848 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008849 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8850 mClient.clear();
8851 }
8852}
8853
Eric Laurent25f43952010-07-28 05:40:18 -07008854status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8855 uint32_t cmdSize,
8856 void *pCmdData,
8857 uint32_t *replySize,
8858 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859{
Steve Block3856b092011-10-20 11:56:00 +01008860// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008861// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008862
8863 // only get parameter command is permitted for applications not controlling the effect
8864 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8865 return INVALID_OPERATION;
8866 }
8867 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008868 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869
8870 // handle commands that are not forwarded transparently to effect engine
8871 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8872 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8873 // no risk to block the whole media server process or mixer threads is we are stuck here
8874 Mutex::Autolock _l(mCblk->lock);
8875 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8876 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8877 mCblk->serverIndex = 0;
8878 mCblk->clientIndex = 0;
8879 return BAD_VALUE;
8880 }
8881 status_t status = NO_ERROR;
8882 while (mCblk->serverIndex < mCblk->clientIndex) {
8883 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008884 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 int *p = (int *)(mBuffer + mCblk->serverIndex);
8886 int size = *p++;
8887 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008888 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008889 break;
8890 }
8891 effect_param_t *param = (effect_param_t *)p;
8892 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008893 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 mCblk->serverIndex += size;
8895 continue;
8896 }
Eric Laurent25f43952010-07-28 05:40:18 -07008897 uint32_t psize = sizeof(effect_param_t) +
8898 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8899 param->vsize;
8900 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8901 psize,
8902 p,
8903 &rsize,
8904 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008905 // stop at first error encountered
8906 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008907 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008908 *(int *)pReplyData = reply;
8909 break;
8910 } else if (reply != NO_ERROR) {
8911 *(int *)pReplyData = reply;
8912 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008913 }
8914 mCblk->serverIndex += size;
8915 }
8916 mCblk->serverIndex = 0;
8917 mCblk->clientIndex = 0;
8918 return status;
8919 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008920 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921 return enable();
8922 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008923 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924 return disable();
8925 }
8926
8927 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8928}
8929
Eric Laurent59255e42011-07-27 19:49:51 -07008930void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931{
Steve Block3856b092011-10-20 11:56:00 +01008932 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008933
8934 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008935 mEnabled = enabled;
8936
Mathias Agopian65ab4712010-07-14 17:59:35 -07008937 if (signal && mEffectClient != 0) {
8938 mEffectClient->controlStatusChanged(hasControl);
8939 }
8940}
8941
Eric Laurent25f43952010-07-28 05:40:18 -07008942void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8943 uint32_t cmdSize,
8944 void *pCmdData,
8945 uint32_t replySize,
8946 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008947{
8948 if (mEffectClient != 0) {
8949 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8950 }
8951}
8952
8953
8954
8955void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8956{
8957 if (mEffectClient != 0) {
8958 mEffectClient->enableStatusChanged(enabled);
8959 }
8960}
8961
8962status_t AudioFlinger::EffectHandle::onTransact(
8963 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8964{
8965 return BnEffect::onTransact(code, data, reply, flags);
8966}
8967
8968
8969void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8970{
Glenn Kastena0d68332012-01-27 16:47:15 -08008971 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972
8973 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008974 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 mPriority,
8976 mHasControl,
8977 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008978 mCblk ? mCblk->clientIndex : 0,
8979 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 );
8981
8982 if (locked) {
8983 mCblk->lock.unlock();
8984 }
8985}
8986
8987#undef LOG_TAG
8988#define LOG_TAG "AudioFlinger::EffectChain"
8989
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008990AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008992 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008993 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8994 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995{
Dima Zavinfce7a472011-04-19 22:30:36 -07008996 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008997 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008998 return;
8999 }
9000 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9001 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002}
9003
9004AudioFlinger::EffectChain::~EffectChain()
9005{
9006 if (mOwnInBuffer) {
9007 delete mInBuffer;
9008 }
9009
9010}
9011
Eric Laurent59255e42011-07-27 19:49:51 -07009012// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009013sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009015 size_t size = mEffects.size();
9016
9017 for (size_t i = 0; i < size; i++) {
9018 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009019 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009020 }
9021 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009022 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023}
9024
Eric Laurent59255e42011-07-27 19:49:51 -07009025// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009026sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028 size_t size = mEffects.size();
9029
9030 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009031 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9032 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009033 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034 }
9035 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009036 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009037}
9038
Eric Laurent59255e42011-07-27 19:49:51 -07009039// getEffectFromType_l() must be called with ThreadBase::mLock held
9040sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9041 const effect_uuid_t *type)
9042{
Eric Laurent59255e42011-07-27 19:49:51 -07009043 size_t size = mEffects.size();
9044
9045 for (size_t i = 0; i < size; i++) {
9046 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009047 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009048 }
9049 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009050 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009051}
9052
Eric Laurent91b14c42012-05-30 12:30:29 -07009053void AudioFlinger::EffectChain::clearInputBuffer()
9054{
9055 Mutex::Autolock _l(mLock);
9056 sp<ThreadBase> thread = mThread.promote();
9057 if (thread == 0) {
9058 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9059 return;
9060 }
9061 clearInputBuffer_l(thread);
9062}
9063
9064// Must be called with EffectChain::mLock locked
9065void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9066{
9067 size_t numSamples = thread->frameCount() * thread->channelCount();
9068 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9069
9070}
9071
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072// Must be called with EffectChain::mLock locked
9073void AudioFlinger::EffectChain::process_l()
9074{
Eric Laurentdac69112010-09-28 14:09:57 -07009075 sp<ThreadBase> thread = mThread.promote();
9076 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009077 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009078 return;
9079 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009080 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9081 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009082 // always process effects unless no more tracks are on the session and the effect tail
9083 // has been rendered
9084 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009085 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009086 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009087
Eric Laurent544fe9b2011-11-11 15:42:52 -08009088 if (!tracksOnSession && mTailBufferCount == 0) {
9089 doProcess = false;
9090 }
9091
9092 if (activeTrackCnt() == 0) {
9093 // if no track is active and the effect tail has not been rendered,
9094 // the input buffer must be cleared here as the mixer process will not do it
9095 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009096 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009097 if (mTailBufferCount > 0) {
9098 mTailBufferCount--;
9099 }
9100 }
9101 }
Eric Laurentdac69112010-09-28 14:09:57 -07009102 }
9103
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009105 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009106 for (size_t i = 0; i < size; i++) {
9107 mEffects[i]->process();
9108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009109 }
9110 for (size_t i = 0; i < size; i++) {
9111 mEffects[i]->updateState();
9112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009113}
9114
Eric Laurentcab11242010-07-15 12:50:15 -07009115// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009116status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009117{
9118 effect_descriptor_t desc = effect->desc();
9119 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9120
9121 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009122 effect->setChain(this);
9123 sp<ThreadBase> thread = mThread.promote();
9124 if (thread == 0) {
9125 return NO_INIT;
9126 }
9127 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128
9129 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9130 // Auxiliary effects are inserted at the beginning of mEffects vector as
9131 // they are processed first and accumulated in chain input buffer
9132 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009133
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 // the input buffer for auxiliary effect contains mono samples in
9135 // 32 bit format. This is to avoid saturation in AudoMixer
9136 // accumulation stage. Saturation is done in EffectModule::process() before
9137 // calling the process in effect engine
9138 size_t numSamples = thread->frameCount();
9139 int32_t *buffer = new int32_t[numSamples];
9140 memset(buffer, 0, numSamples * sizeof(int32_t));
9141 effect->setInBuffer((int16_t *)buffer);
9142 // auxiliary effects output samples to chain input buffer for further processing
9143 // by insert effects
9144 effect->setOutBuffer(mInBuffer);
9145 } else {
9146 // Insert effects are inserted at the end of mEffects vector as they are processed
9147 // after track and auxiliary effects.
9148 // Insert effect order as a function of indicated preference:
9149 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9150 // another effect is present
9151 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9152 // last effect claiming first position
9153 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9154 // first effect claiming last position
9155 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9156 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9157 // already present
9158
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009159 size_t size = mEffects.size();
9160 size_t idx_insert = size;
9161 ssize_t idx_insert_first = -1;
9162 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009163
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009164 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165 effect_descriptor_t d = mEffects[i]->desc();
9166 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9167 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9168 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9169 // check invalid effect chaining combinations
9170 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9171 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009172 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009173 return INVALID_OPERATION;
9174 }
9175 // remember position of first insert effect and by default
9176 // select this as insert position for new effect
9177 if (idx_insert == size) {
9178 idx_insert = i;
9179 }
9180 // remember position of last insert effect claiming
9181 // first position
9182 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9183 idx_insert_first = i;
9184 }
9185 // remember position of first insert effect claiming
9186 // last position
9187 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9188 idx_insert_last == -1) {
9189 idx_insert_last = i;
9190 }
9191 }
9192 }
9193
9194 // modify idx_insert from first position if needed
9195 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9196 if (idx_insert_last != -1) {
9197 idx_insert = idx_insert_last;
9198 } else {
9199 idx_insert = size;
9200 }
9201 } else {
9202 if (idx_insert_first != -1) {
9203 idx_insert = idx_insert_first + 1;
9204 }
9205 }
9206
9207 // always read samples from chain input buffer
9208 effect->setInBuffer(mInBuffer);
9209
9210 // if last effect in the chain, output samples to chain
9211 // output buffer, otherwise to chain input buffer
9212 if (idx_insert == size) {
9213 if (idx_insert != 0) {
9214 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9215 mEffects[idx_insert-1]->configure();
9216 }
9217 effect->setOutBuffer(mOutBuffer);
9218 } else {
9219 effect->setOutBuffer(mInBuffer);
9220 }
9221 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222
Steve Block3856b092011-10-20 11:56:00 +01009223 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 }
9225 effect->configure();
9226 return NO_ERROR;
9227}
9228
Eric Laurentcab11242010-07-15 12:50:15 -07009229// removeEffect_l() must be called with PlaybackThread::mLock held
9230size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009231{
9232 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009233 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9235
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009236 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009238 // calling stop here will remove pre-processing effect from the audio HAL.
9239 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9240 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009241 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9242 mEffects[i]->state() == EffectModule::STOPPING) {
9243 mEffects[i]->stop();
9244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9246 delete[] effect->inBuffer();
9247 } else {
9248 if (i == size - 1 && i != 0) {
9249 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9250 mEffects[i - 1]->configure();
9251 }
9252 }
9253 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009254 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255 break;
9256 }
9257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009258
9259 return mEffects.size();
9260}
9261
Eric Laurentcab11242010-07-15 12:50:15 -07009262// setDevice_l() must be called with PlaybackThread::mLock held
9263void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264{
9265 size_t size = mEffects.size();
9266 for (size_t i = 0; i < size; i++) {
9267 mEffects[i]->setDevice(device);
9268 }
9269}
9270
Eric Laurentcab11242010-07-15 12:50:15 -07009271// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009272void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273{
9274 size_t size = mEffects.size();
9275 for (size_t i = 0; i < size; i++) {
9276 mEffects[i]->setMode(mode);
9277 }
9278}
9279
Eric Laurentcab11242010-07-15 12:50:15 -07009280// setVolume_l() must be called with PlaybackThread::mLock held
9281bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282{
9283 uint32_t newLeft = *left;
9284 uint32_t newRight = *right;
9285 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009286 int ctrlIdx = -1;
9287 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288
Eric Laurentcab11242010-07-15 12:50:15 -07009289 // first update volume controller
9290 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009291 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009292 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9293 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009294 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009295 break;
9296 }
9297 }
9298
9299 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009300 if (hasControl) {
9301 *left = mNewLeftVolume;
9302 *right = mNewRightVolume;
9303 }
9304 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009305 }
9306
9307 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009308 mLeftVolume = newLeft;
9309 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009310
9311 // second get volume update from volume controller
9312 if (ctrlIdx >= 0) {
9313 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009314 mNewLeftVolume = newLeft;
9315 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009316 }
9317 // then indicate volume to all other effects in chain.
9318 // Pass altered volume to effects before volume controller
9319 // and requested volume to effects after controller
9320 uint32_t lVol = newLeft;
9321 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009322
Mathias Agopian65ab4712010-07-14 17:59:35 -07009323 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009324 if ((int)i == ctrlIdx) continue;
9325 // this also works for ctrlIdx == -1 when there is no volume controller
9326 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009327 lVol = *left;
9328 rVol = *right;
9329 }
9330 mEffects[i]->setVolume(&lVol, &rVol, false);
9331 }
9332 *left = newLeft;
9333 *right = newRight;
9334
9335 return hasControl;
9336}
9337
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9339{
9340 const size_t SIZE = 256;
9341 char buffer[SIZE];
9342 String8 result;
9343
9344 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9345 result.append(buffer);
9346
9347 bool locked = tryLock(mLock);
9348 // failed to lock - AudioFlinger is probably deadlocked
9349 if (!locked) {
9350 result.append("\tCould not lock mutex:\n");
9351 }
9352
Eric Laurentcab11242010-07-15 12:50:15 -07009353 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9354 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 mEffects.size(),
9356 (uint32_t)mInBuffer,
9357 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009358 mActiveTrackCnt);
9359 result.append(buffer);
9360 write(fd, result.string(), result.size());
9361
9362 for (size_t i = 0; i < mEffects.size(); ++i) {
9363 sp<EffectModule> effect = mEffects[i];
9364 if (effect != 0) {
9365 effect->dump(fd, args);
9366 }
9367 }
9368
9369 if (locked) {
9370 mLock.unlock();
9371 }
9372
9373 return NO_ERROR;
9374}
9375
Eric Laurent59255e42011-07-27 19:49:51 -07009376// must be called with ThreadBase::mLock held
9377void AudioFlinger::EffectChain::setEffectSuspended_l(
9378 const effect_uuid_t *type, bool suspend)
9379{
9380 sp<SuspendedEffectDesc> desc;
9381 // use effect type UUID timelow as key as there is no real risk of identical
9382 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009383 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009384 if (suspend) {
9385 if (index >= 0) {
9386 desc = mSuspendedEffects.valueAt(index);
9387 } else {
9388 desc = new SuspendedEffectDesc();
9389 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9390 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009391 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009392 }
9393 if (desc->mRefCount++ == 0) {
9394 sp<EffectModule> effect = getEffectIfEnabled(type);
9395 if (effect != 0) {
9396 desc->mEffect = effect;
9397 effect->setSuspended(true);
9398 effect->setEnabled(false);
9399 }
9400 }
9401 } else {
9402 if (index < 0) {
9403 return;
9404 }
9405 desc = mSuspendedEffects.valueAt(index);
9406 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009407 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009408 desc->mRefCount = 1;
9409 }
9410 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009411 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009412 if (desc->mEffect != 0) {
9413 sp<EffectModule> effect = desc->mEffect.promote();
9414 if (effect != 0) {
9415 effect->setSuspended(false);
9416 sp<EffectHandle> handle = effect->controlHandle();
9417 if (handle != 0) {
9418 effect->setEnabled(handle->enabled());
9419 }
9420 }
9421 desc->mEffect.clear();
9422 }
9423 mSuspendedEffects.removeItemsAt(index);
9424 }
9425 }
9426}
9427
9428// must be called with ThreadBase::mLock held
9429void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9430{
9431 sp<SuspendedEffectDesc> desc;
9432
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009433 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009434 if (suspend) {
9435 if (index >= 0) {
9436 desc = mSuspendedEffects.valueAt(index);
9437 } else {
9438 desc = new SuspendedEffectDesc();
9439 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009440 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009441 }
9442 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009443 Vector< sp<EffectModule> > effects;
9444 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009445 for (size_t i = 0; i < effects.size(); i++) {
9446 setEffectSuspended_l(&effects[i]->desc().type, true);
9447 }
9448 }
9449 } else {
9450 if (index < 0) {
9451 return;
9452 }
9453 desc = mSuspendedEffects.valueAt(index);
9454 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009455 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009456 desc->mRefCount = 1;
9457 }
9458 if (--desc->mRefCount == 0) {
9459 Vector<const effect_uuid_t *> types;
9460 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9461 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9462 continue;
9463 }
9464 types.add(&mSuspendedEffects.valueAt(i)->mType);
9465 }
9466 for (size_t i = 0; i < types.size(); i++) {
9467 setEffectSuspended_l(types[i], false);
9468 }
Steve Block3856b092011-10-20 11:56:00 +01009469 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009470 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9471 }
9472 }
9473}
9474
Eric Laurent6bffdb82011-09-23 08:40:41 -07009475
9476// The volume effect is used for automated tests only
9477#ifndef OPENSL_ES_H_
9478static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9479 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9480const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9481#endif //OPENSL_ES_H_
9482
Eric Laurentdb7c0792011-08-10 10:37:50 -07009483bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9484{
9485 // auxiliary effects and visualizer are never suspended on output mix
9486 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9487 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009488 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9489 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009490 return false;
9491 }
9492 return true;
9493}
9494
Glenn Kastend0539712012-01-30 12:56:03 -08009495void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009496{
Glenn Kastend0539712012-01-30 12:56:03 -08009497 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009498 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009499 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9500 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009501 }
Eric Laurent59255e42011-07-27 19:49:51 -07009502 }
Eric Laurent59255e42011-07-27 19:49:51 -07009503}
9504
9505sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9506 const effect_uuid_t *type)
9507{
Glenn Kasten090f0192012-01-30 13:00:02 -08009508 sp<EffectModule> effect = getEffectFromType_l(type);
9509 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009510}
9511
9512void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9513 bool enabled)
9514{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009515 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 if (enabled) {
9517 if (index < 0) {
9518 // if the effect is not suspend check if all effects are suspended
9519 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9520 if (index < 0) {
9521 return;
9522 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009523 if (!isEffectEligibleForSuspend(effect->desc())) {
9524 return;
9525 }
Eric Laurent59255e42011-07-27 19:49:51 -07009526 setEffectSuspended_l(&effect->desc().type, enabled);
9527 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009528 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009529 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009530 return;
9531 }
Eric Laurent59255e42011-07-27 19:49:51 -07009532 }
Steve Block3856b092011-10-20 11:56:00 +01009533 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009534 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009535 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9536 // if effect is requested to suspended but was not yet enabled, supend it now.
9537 if (desc->mEffect == 0) {
9538 desc->mEffect = effect;
9539 effect->setEnabled(false);
9540 effect->setSuspended(true);
9541 }
9542 } else {
9543 if (index < 0) {
9544 return;
9545 }
Steve Block3856b092011-10-20 11:56:00 +01009546 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009547 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009548 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9549 desc->mEffect.clear();
9550 effect->setSuspended(false);
9551 }
9552}
9553
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554#undef LOG_TAG
9555#define LOG_TAG "AudioFlinger"
9556
9557// ----------------------------------------------------------------------------
9558
9559status_t AudioFlinger::onTransact(
9560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9561{
9562 return BnAudioFlinger::onTransact(code, data, reply, flags);
9563}
9564
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565}; // namespace android