blob: 65255bac0d1a9c3e8bda5c576638a778016925fe [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 Kastendd8104c2012-07-02 12:42:44 -0700967size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
968 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969{
Eric Laurenta1884f92011-08-23 08:25:03 -0700970 status_t ret = initCheck();
971 if (ret != NO_ERROR) {
972 return 0;
973 }
974
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800975 AutoMutex lock(mHardwareLock);
976 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700977 struct audio_config config = {
978 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700979 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700980 format: format,
981 };
982 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800983 mHardwareStatus = AUDIO_HW_IDLE;
984 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985}
986
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800987unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988{
989 if (ioHandle == 0) {
990 return 0;
991 }
992
993 Mutex::Autolock _l(mLock);
994
995 RecordThread *recordThread = checkRecordThread_l(ioHandle);
996 if (recordThread != NULL) {
997 return recordThread->getInputFramesLost();
998 }
999 return 0;
1000}
1001
1002status_t AudioFlinger::setVoiceVolume(float value)
1003{
Eric Laurenta1884f92011-08-23 08:25:03 -07001004 status_t ret = initCheck();
1005 if (ret != NO_ERROR) {
1006 return ret;
1007 }
1008
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 // check calling permissions
1010 if (!settingsAllowed()) {
1011 return PERMISSION_DENIED;
1012 }
1013
1014 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001015 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001016 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 mHardwareStatus = AUDIO_HW_IDLE;
1018
1019 return ret;
1020}
1021
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001022status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1023 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024{
1025 status_t status;
1026
1027 Mutex::Autolock _l(mLock);
1028
1029 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1030 if (playbackThread != NULL) {
1031 return playbackThread->getRenderPosition(halFrames, dspFrames);
1032 }
1033
1034 return BAD_VALUE;
1035}
1036
1037void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1038{
1039
1040 Mutex::Autolock _l(mLock);
1041
Glenn Kastenbb001922012-02-03 11:10:26 -08001042 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 if (mNotificationClients.indexOfKey(pid) < 0) {
1044 sp<NotificationClient> notificationClient = new NotificationClient(this,
1045 client,
1046 pid);
Steve Block3856b092011-10-20 11:56:00 +01001047 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048
1049 mNotificationClients.add(pid, notificationClient);
1050
1051 sp<IBinder> binder = client->asBinder();
1052 binder->linkToDeath(notificationClient);
1053
1054 // the config change is always sent from playback or record threads to avoid deadlock
1055 // with AudioSystem::gLock
1056 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1057 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1058 }
1059
1060 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1061 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1062 }
1063 }
1064}
1065
1066void AudioFlinger::removeNotificationClient(pid_t pid)
1067{
1068 Mutex::Autolock _l(mLock);
1069
Glenn Kastena3b09252012-01-20 09:19:01 -08001070 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001071
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001073 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001074 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001075 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001076 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001077 ALOGV(" pid %d @ %d", ref->mPid, i);
1078 if (ref->mPid == pid) {
1079 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001080 mAudioSessionRefs.removeAt(i);
1081 delete ref;
1082 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001083 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001084 } else {
1085 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001086 }
1087 }
1088 if (removed) {
1089 purgeStaleEffects_l();
1090 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091}
1092
1093// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001094void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095{
1096 size_t size = mNotificationClients.size();
1097 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001098 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1099 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 }
1101}
1102
1103// removeClient_l() must be called with AudioFlinger::mLock held
1104void AudioFlinger::removeClient_l(pid_t pid)
1105{
Steve Block3856b092011-10-20 11:56:00 +01001106 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 mClients.removeItem(pid);
1108}
1109
Eric Laurent717e1282012-06-29 16:36:52 -07001110// getEffectThread_l() must be called with AudioFlinger::mLock held
1111sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1112{
1113 sp<PlaybackThread> thread;
1114
1115 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1116 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1117 ALOG_ASSERT(thread == 0);
1118 thread = mPlaybackThreads.valueAt(i);
1119 }
1120 }
1121
1122 return thread;
1123}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124
1125// ----------------------------------------------------------------------------
1126
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001127AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1128 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001130 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001131 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001132 // mChannelMask
1133 mChannelCount(0),
1134 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1135 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001136 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001137 mDevice(device),
1138 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139{
1140}
1141
1142AudioFlinger::ThreadBase::~ThreadBase()
1143{
1144 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001145 // do not lock the mutex in destructor
1146 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001147 if (mPowerManager != 0) {
1148 sp<IBinder> binder = mPowerManager->asBinder();
1149 binder->unlinkToDeath(mDeathRecipient);
1150 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151}
1152
1153void AudioFlinger::ThreadBase::exit()
1154{
Steve Block3856b092011-10-20 11:56:00 +01001155 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001157 // This lock prevents the following race in thread (uniprocessor for illustration):
1158 // if (!exitPending()) {
1159 // // context switch from here to exit()
1160 // // exit() calls requestExit(), what exitPending() observes
1161 // // exit() calls signal(), which is dropped since no waiters
1162 // // context switch back from exit() to here
1163 // mWaitWorkCV.wait(...);
1164 // // now thread is hung
1165 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001166 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 requestExit();
1168 mWaitWorkCV.signal();
1169 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001170 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1171 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 requestExitAndWait();
1173}
1174
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1176{
1177 status_t status;
1178
Steve Block3856b092011-10-20 11:56:00 +01001179 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 Mutex::Autolock _l(mLock);
1181
1182 mNewParameters.add(keyValuePairs);
1183 mWaitWorkCV.signal();
1184 // wait condition with timeout in case the thread loop has exited
1185 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001186 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 status = mParamStatus;
1188 mWaitWorkCV.signal();
1189 } else {
1190 status = TIMED_OUT;
1191 }
1192 return status;
1193}
1194
1195void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1196{
1197 Mutex::Autolock _l(mLock);
1198 sendConfigEvent_l(event, param);
1199}
1200
1201// sendConfigEvent_l() must be called with ThreadBase::mLock held
1202void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1203{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001204 ConfigEvent configEvent;
1205 configEvent.mEvent = event;
1206 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001208 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mWaitWorkCV.signal();
1210}
1211
1212void AudioFlinger::ThreadBase::processConfigEvents()
1213{
1214 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001215 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001216 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001217 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 mConfigEvents.removeAt(0);
1219 // release mLock before locking AudioFlinger mLock: lock order is always
1220 // AudioFlinger then ThreadBase to avoid cross deadlock
1221 mLock.unlock();
1222 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001223 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 mLock.lock();
1226 }
1227 mLock.unlock();
1228}
1229
1230status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1231{
1232 const size_t SIZE = 256;
1233 char buffer[SIZE];
1234 String8 result;
1235
1236 bool locked = tryLock(mLock);
1237 if (!locked) {
1238 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1239 write(fd, buffer, strlen(buffer));
1240 }
1241
Eric Laurent612bbb52012-03-14 15:03:26 -07001242 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1243 result.append(buffer);
1244 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1245 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1247 result.append(buffer);
1248 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1249 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001250 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1251 result.append(buffer);
1252 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 result.append(buffer);
1254 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1255 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001256 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1257 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1259 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001260 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261 result.append(buffer);
1262
1263 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1264 result.append(buffer);
1265 result.append(" Index Command");
1266 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1267 snprintf(buffer, SIZE, "\n %02d ", i);
1268 result.append(buffer);
1269 result.append(mNewParameters[i]);
1270 }
1271
1272 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1273 result.append(buffer);
1274 snprintf(buffer, SIZE, " Index event param\n");
1275 result.append(buffer);
1276 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001277 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278 result.append(buffer);
1279 }
1280 result.append("\n");
1281
1282 write(fd, result.string(), result.size());
1283
1284 if (locked) {
1285 mLock.unlock();
1286 }
1287 return NO_ERROR;
1288}
1289
Eric Laurent1d2bff02011-07-24 17:49:51 -07001290status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1291{
1292 const size_t SIZE = 256;
1293 char buffer[SIZE];
1294 String8 result;
1295
1296 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1297 write(fd, buffer, strlen(buffer));
1298
1299 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1300 sp<EffectChain> chain = mEffectChains[i];
1301 if (chain != 0) {
1302 chain->dump(fd, args);
1303 }
1304 }
1305 return NO_ERROR;
1306}
1307
Eric Laurentfeb0db62011-07-22 09:04:31 -07001308void AudioFlinger::ThreadBase::acquireWakeLock()
1309{
1310 Mutex::Autolock _l(mLock);
1311 acquireWakeLock_l();
1312}
1313
1314void AudioFlinger::ThreadBase::acquireWakeLock_l()
1315{
1316 if (mPowerManager == 0) {
1317 // use checkService() to avoid blocking if power service is not up yet
1318 sp<IBinder> binder =
1319 defaultServiceManager()->checkService(String16("power"));
1320 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001321 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001322 } else {
1323 mPowerManager = interface_cast<IPowerManager>(binder);
1324 binder->linkToDeath(mDeathRecipient);
1325 }
1326 }
1327 if (mPowerManager != 0) {
1328 sp<IBinder> binder = new BBinder();
1329 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1330 binder,
1331 String16(mName));
1332 if (status == NO_ERROR) {
1333 mWakeLockToken = binder;
1334 }
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001336 }
1337}
1338
1339void AudioFlinger::ThreadBase::releaseWakeLock()
1340{
1341 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001342 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001343}
1344
1345void AudioFlinger::ThreadBase::releaseWakeLock_l()
1346{
1347 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001348 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001349 if (mPowerManager != 0) {
1350 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1351 }
1352 mWakeLockToken.clear();
1353 }
1354}
1355
1356void AudioFlinger::ThreadBase::clearPowerManager()
1357{
1358 Mutex::Autolock _l(mLock);
1359 releaseWakeLock_l();
1360 mPowerManager.clear();
1361}
1362
1363void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1364{
1365 sp<ThreadBase> thread = mThread.promote();
1366 if (thread != 0) {
1367 thread->clearPowerManager();
1368 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001369 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001370}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001371
Eric Laurent59255e42011-07-27 19:49:51 -07001372void AudioFlinger::ThreadBase::setEffectSuspended(
1373 const effect_uuid_t *type, bool suspend, int sessionId)
1374{
1375 Mutex::Autolock _l(mLock);
1376 setEffectSuspended_l(type, suspend, sessionId);
1377}
1378
1379void AudioFlinger::ThreadBase::setEffectSuspended_l(
1380 const effect_uuid_t *type, bool suspend, int sessionId)
1381{
Glenn Kasten090f0192012-01-30 13:00:02 -08001382 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001383 if (chain != 0) {
1384 if (type != NULL) {
1385 chain->setEffectSuspended_l(type, suspend);
1386 } else {
1387 chain->setEffectSuspendedAll_l(suspend);
1388 }
1389 }
1390
1391 updateSuspendedSessions_l(type, suspend, sessionId);
1392}
1393
1394void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1395{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001396 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001397 if (index < 0) {
1398 return;
1399 }
1400
1401 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1402 mSuspendedSessions.editValueAt(index);
1403
1404 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001405 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001406 for (int j = 0; j < desc->mRefCount; j++) {
1407 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1408 chain->setEffectSuspendedAll_l(true);
1409 } else {
Steve Block3856b092011-10-20 11:56:00 +01001410 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001411 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001412 chain->setEffectSuspended_l(&desc->mType, true);
1413 }
1414 }
1415 }
1416}
1417
Eric Laurent59255e42011-07-27 19:49:51 -07001418void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1419 bool suspend,
1420 int sessionId)
1421{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001422 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001423
1424 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1425
1426 if (suspend) {
1427 if (index >= 0) {
1428 sessionEffects = mSuspendedSessions.editValueAt(index);
1429 } else {
1430 mSuspendedSessions.add(sessionId, sessionEffects);
1431 }
1432 } else {
1433 if (index < 0) {
1434 return;
1435 }
1436 sessionEffects = mSuspendedSessions.editValueAt(index);
1437 }
1438
1439
1440 int key = EffectChain::kKeyForSuspendAll;
1441 if (type != NULL) {
1442 key = type->timeLow;
1443 }
1444 index = sessionEffects.indexOfKey(key);
1445
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001446 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001447 if (suspend) {
1448 if (index >= 0) {
1449 desc = sessionEffects.valueAt(index);
1450 } else {
1451 desc = new SuspendedSessionDesc();
1452 if (type != NULL) {
1453 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1454 }
1455 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001456 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001457 }
1458 desc->mRefCount++;
1459 } else {
1460 if (index < 0) {
1461 return;
1462 }
1463 desc = sessionEffects.valueAt(index);
1464 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001465 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001466 sessionEffects.removeItemsAt(index);
1467 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001468 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001469 sessionId);
1470 mSuspendedSessions.removeItem(sessionId);
1471 }
1472 }
1473 }
1474 if (!sessionEffects.isEmpty()) {
1475 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1476 }
1477}
1478
1479void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1480 bool enabled,
1481 int sessionId)
1482{
1483 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001484 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1485}
Eric Laurent59255e42011-07-27 19:49:51 -07001486
Eric Laurenta85a74a2011-10-19 11:44:54 -07001487void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1488 bool enabled,
1489 int sessionId)
1490{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001491 if (mType != RECORD) {
1492 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1493 // another session. This gives the priority to well behaved effect control panels
1494 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001495 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1496 // global effects
1497 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001498 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1499 }
1500 }
Eric Laurent59255e42011-07-27 19:49:51 -07001501
1502 sp<EffectChain> chain = getEffectChain_l(sessionId);
1503 if (chain != 0) {
1504 chain->checkSuspendOnEffectEnabled(effect, enabled);
1505 }
1506}
1507
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508// ----------------------------------------------------------------------------
1509
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001510AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1511 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001512 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001513 uint32_t device,
1514 type_t type)
1515 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001516 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1517 // Assumes constructor is called by AudioFlinger with it's mLock held,
1518 // but it would be safer to explicitly pass initial masterMute as parameter
1519 mMasterMute(audioFlinger->masterMute_l()),
1520 // mStreamTypes[] initialized in constructor body
1521 mOutput(output),
1522 // Assumes constructor is called by AudioFlinger with it's mLock held,
1523 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001524 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001525 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001526 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001527 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001528 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001529 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001530 // index 0 is reserved for normal mixer's submix
1531 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532{
Glenn Kasten480b4682012-02-28 12:30:08 -08001533 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001534
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 readOutputParameters();
1536
Glenn Kasten263709e2012-01-06 08:40:01 -08001537 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001538 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1539 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1540 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001541 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1542 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001544 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1545 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546}
1547
1548AudioFlinger::PlaybackThread::~PlaybackThread()
1549{
1550 delete [] mMixBuffer;
1551}
1552
1553status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1554{
1555 dumpInternals(fd, args);
1556 dumpTracks(fd, args);
1557 dumpEffectChains(fd, args);
1558 return NO_ERROR;
1559}
1560
1561status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1562{
1563 const size_t SIZE = 256;
1564 char buffer[SIZE];
1565 String8 result;
1566
Glenn Kasten58912562012-04-03 10:45:00 -07001567 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1568 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1569 const stream_type_t *st = &mStreamTypes[i];
1570 if (i > 0) {
1571 result.appendFormat(", ");
1572 }
1573 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1574 if (st->mute) {
1575 result.append("M");
1576 }
1577 }
1578 result.append("\n");
1579 write(fd, result.string(), result.length());
1580 result.clear();
1581
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1583 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001584 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 for (size_t i = 0; i < mTracks.size(); ++i) {
1586 sp<Track> track = mTracks[i];
1587 if (track != 0) {
1588 track->dump(buffer, SIZE);
1589 result.append(buffer);
1590 }
1591 }
1592
1593 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1594 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001595 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001597 sp<Track> track = mActiveTracks[i].promote();
1598 if (track != 0) {
1599 track->dump(buffer, SIZE);
1600 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 }
1602 }
1603 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001604
1605 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1606 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1607 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1608 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1609
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 return NO_ERROR;
1611}
1612
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1614{
1615 const size_t SIZE = 256;
1616 char buffer[SIZE];
1617 String8 result;
1618
1619 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1620 result.append(buffer);
1621 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1622 result.append(buffer);
1623 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1624 result.append(buffer);
1625 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1626 result.append(buffer);
1627 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1628 result.append(buffer);
1629 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1630 result.append(buffer);
1631 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1632 result.append(buffer);
1633 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001634 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635
1636 dumpBase(fd, args);
1637
1638 return NO_ERROR;
1639}
1640
1641// Thread virtuals
1642status_t AudioFlinger::PlaybackThread::readyToRun()
1643{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001644 status_t status = initCheck();
1645 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001646 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001647 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001648 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001650 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651}
1652
1653void AudioFlinger::PlaybackThread::onFirstRef()
1654{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001655 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656}
1657
1658// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001659sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001661 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001663 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001664 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 int frameCount,
1666 const sp<IMemory>& sharedBuffer,
1667 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001668 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001669 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 status_t *status)
1671{
1672 sp<Track> track;
1673 status_t lStatus;
1674
Glenn Kasten73d22752012-03-19 13:38:30 -07001675 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1676
1677 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001678 if (flags & IAudioFlinger::TRACK_FAST) {
1679 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001680 // not timed
1681 (!isTimed) &&
1682 // either of these use cases:
1683 (
1684 // use case 1: shared buffer with any frame count
1685 (
1686 (sharedBuffer != 0)
1687 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001688 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001689 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001690 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001691 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001692 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001693 )
1694 ) &&
1695 // PCM data
1696 audio_is_linear_pcm(format) &&
1697 // mono or stereo
1698 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1699 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001700#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001701 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001702 (sampleRate == mSampleRate) &&
1703#endif
1704 // normal mixer has an associated fast mixer
1705 hasFastMixer() &&
1706 // there are sufficient fast track slots available
1707 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001708 // FIXME test that MixerThread for this fast track has a capable output HAL
1709 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001711 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1712 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001713 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001714 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001715 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001716 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001717 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001718 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001719 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1720 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1721 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1722 audio_is_linear_pcm(format),
1723 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001724 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001725 // For compatibility with AudioTrack calculation, buffer depth is forced
1726 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1727 // This is probably too conservative, but legacy application code may depend on it.
1728 // If you change this calculation, also review the start threshold which is related.
1729 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1730 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1731 if (minBufCount < 2) {
1732 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001733 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001734 int minFrameCount = mNormalFrameCount * minBufCount;
1735 if (frameCount < minFrameCount) {
1736 frameCount = minFrameCount;
1737 }
1738 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001739 }
1740
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001742 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1743 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001744 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001745 "for output %p with format %d",
1746 sampleRate, format, channelMask, mOutput, mFormat);
1747 lStatus = BAD_VALUE;
1748 goto Exit;
1749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 }
1751 } else {
1752 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1753 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001754 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 lStatus = BAD_VALUE;
1756 goto Exit;
1757 }
1758 }
1759
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001760 lStatus = initCheck();
1761 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001762 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 goto Exit;
1764 }
1765
1766 { // scope for mLock
1767 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001768
1769 // all tracks in same audio session must share the same routing strategy otherwise
1770 // conflicts will happen when tracks are moved from one output to another by audio policy
1771 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001772 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001775 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001776 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001777 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001778 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001779 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001780 lStatus = BAD_VALUE;
1781 goto Exit;
1782 }
1783 }
1784 }
1785
John Grossman4ff14ba2012-02-08 16:37:41 -08001786 if (!isTimed) {
1787 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001788 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001789 } else {
1790 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1791 channelMask, frameCount, sharedBuffer, sessionId);
1792 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001793 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 lStatus = NO_MEMORY;
1795 goto Exit;
1796 }
1797 mTracks.add(track);
1798
1799 sp<EffectChain> chain = getEffectChain_l(sessionId);
1800 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001801 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001803 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001804 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 }
1806 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001807
1808#ifdef HAVE_REQUEST_PRIORITY
1809 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1810 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1811 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1812 // so ask activity manager to do this on our behalf
1813 int err = requestPriority(callingPid, tid, 1);
1814 if (err != 0) {
1815 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1816 1, callingPid, tid, err);
1817 }
1818 }
1819#endif
1820
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 lStatus = NO_ERROR;
1822
1823Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001824 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 *status = lStatus;
1826 }
1827 return track;
1828}
1829
Eric Laurente737cda2012-05-22 18:55:44 -07001830uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1831{
1832 if (mFastMixer != NULL) {
1833 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1834 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1835 }
1836 return latency;
1837}
1838
1839uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1840{
1841 return latency;
1842}
1843
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844uint32_t AudioFlinger::PlaybackThread::latency() const
1845{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001846 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001847 return latency_l();
1848}
1849uint32_t AudioFlinger::PlaybackThread::latency_l() const
1850{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001851 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001852 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001853 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 return 0;
1855 }
1856}
1857
Glenn Kasten6637baa2012-01-09 09:40:36 -08001858void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001860 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862}
1863
Glenn Kasten6637baa2012-01-09 09:40:36 -08001864void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001866 Mutex::Autolock _l(mLock);
1867 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868}
1869
Glenn Kasten6637baa2012-01-09 09:40:36 -08001870void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001872 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874}
1875
Glenn Kasten6637baa2012-01-09 09:40:36 -08001876void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001878 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880}
1881
Glenn Kastenfff6d712012-01-12 16:38:12 -08001882float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001884 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 return mStreamTypes[stream].volume;
1886}
1887
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888// addTrack_l() must be called with ThreadBase::mLock held
1889status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1890{
1891 status_t status = ALREADY_EXISTS;
1892
1893 // set retry count for buffer fill
1894 track->mRetryCount = kMaxTrackStartupRetries;
1895 if (mActiveTracks.indexOf(track) < 0) {
1896 // the track is newly added, make sure it fills up all its
1897 // buffers before playing. This is to ensure the client will
1898 // effectively get the latency it requested.
1899 track->mFillingUpStatus = Track::FS_FILLING;
1900 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001901 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 mActiveTracks.add(track);
1903 if (track->mainBuffer() != mMixBuffer) {
1904 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1905 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001906 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001907 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 }
1909 }
1910
1911 status = NO_ERROR;
1912 }
1913
Steve Block3856b092011-10-20 11:56:00 +01001914 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 mWaitWorkCV.broadcast();
1916
1917 return status;
1918}
1919
1920// destroyTrack_l() must be called with ThreadBase::mLock held
1921void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1922{
1923 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001924 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001926 removeTrack_l(track);
1927 }
1928}
1929
1930void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1931{
Eric Laurent29864602012-05-08 18:57:51 -07001932 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001933 mTracks.remove(track);
1934 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001935 // redundant as track is about to be destroyed, for dumpsys only
1936 track->mName = -1;
1937 if (track->isFastTrack()) {
1938 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001939 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001940 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1941 mFastTrackAvailMask |= 1 << index;
1942 // redundant as track is about to be destroyed, for dumpsys only
1943 track->mFastIndex = -1;
1944 }
Eric Laurentb469b942011-05-09 12:09:06 -07001945 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1946 if (chain != 0) {
1947 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 }
1949}
1950
1951String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1952{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001953 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001954 char *s;
1955
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001956 Mutex::Autolock _l(mLock);
1957 if (initCheck() != NO_ERROR) {
1958 return out_s8;
1959 }
1960
Dima Zavin799a70e2011-04-18 16:57:27 -07001961 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001962 out_s8 = String8(s);
1963 free(s);
1964 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965}
1966
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1969 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001970 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971
Steve Block3856b092011-10-20 11:56:00 +01001972 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973
1974 switch (event) {
1975 case AudioSystem::OUTPUT_OPENED:
1976 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001977 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 desc.samplingRate = mSampleRate;
1979 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001980 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 desc.latency = latency();
1982 param2 = &desc;
1983 break;
1984
1985 case AudioSystem::STREAM_CONFIG_CHANGED:
1986 param2 = &param;
1987 case AudioSystem::OUTPUT_CLOSED:
1988 default:
1989 break;
1990 }
1991 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1992}
1993
1994void AudioFlinger::PlaybackThread::readOutputParameters()
1995{
Dima Zavin799a70e2011-04-18 16:57:27 -07001996 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001997 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1998 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001999 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002000 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002001 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002002 if (mFrameCount & 15) {
2003 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2004 mFrameCount);
2005 }
2006
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002007 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002008 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002009 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002010 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002011 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2012 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2013 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2014 maxNormalFrameCount = maxNormalFrameCount & ~15;
2015 if (maxNormalFrameCount < minNormalFrameCount) {
2016 maxNormalFrameCount = minNormalFrameCount;
2017 }
2018 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2019 if (multiplier <= 1.0) {
2020 multiplier = 1.0;
2021 } else if (multiplier <= 2.0) {
2022 if (2 * mFrameCount <= maxNormalFrameCount) {
2023 multiplier = 2.0;
2024 } else {
2025 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2026 }
2027 } else {
2028 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2029 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2030 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2031 // FIXME this rounding up should not be done if no HAL SRC
2032 uint32_t truncMult = (uint32_t) multiplier;
2033 if ((truncMult & 1)) {
2034 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2035 ++truncMult;
2036 }
2037 }
2038 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002039 }
Glenn Kasten58912562012-04-03 10:45:00 -07002040 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002041 mNormalFrameCount = multiplier * mFrameCount;
2042 // round up to nearest 16 frames to satisfy AudioMixer
2043 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002044 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045
Glenn Kastene9dd0172012-01-27 18:08:45 -08002046 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002047 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2048 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049
Eric Laurentde070132010-07-13 04:45:46 -07002050 // force reconfiguration of effect chains and engines to take new buffer size and audio
2051 // parameters into account
2052 // Note that mLock is not held when readOutputParameters() is called from the constructor
2053 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2054 // matter.
2055 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2056 Vector< sp<EffectChain> > effectChains = mEffectChains;
2057 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002058 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060}
2061
Eric Laurente737cda2012-05-22 18:55:44 -07002062
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2064{
Glenn Kastena0d68332012-01-27 16:47:15 -08002065 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 return BAD_VALUE;
2067 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002068 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002069 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 return INVALID_OPERATION;
2071 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002072 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073
Dima Zavin799a70e2011-04-18 16:57:27 -07002074 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075}
2076
Eric Laurent39e94f82010-07-28 01:32:47 -07002077uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078{
2079 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002080 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002082 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 }
2084
2085 for (size_t i = 0; i < mTracks.size(); ++i) {
2086 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002087 if (sessionId == track->sessionId() &&
2088 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002089 result |= TRACK_SESSION;
2090 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 }
2092 }
2093
Eric Laurent39e94f82010-07-28 01:32:47 -07002094 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095}
2096
Eric Laurentde070132010-07-13 04:45:46 -07002097uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2098{
Dima Zavinfce7a472011-04-19 22:30:36 -07002099 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002100 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002101 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2102 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002103 }
2104 for (size_t i = 0; i < mTracks.size(); i++) {
2105 sp<Track> track = mTracks[i];
2106 if (sessionId == track->sessionId() &&
2107 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002108 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002109 }
2110 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002111 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002112}
2113
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114
Glenn Kastenaed850d2012-01-26 09:46:34 -08002115AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002116{
2117 Mutex::Autolock _l(mLock);
2118 return mOutput;
2119}
2120
2121AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2122{
2123 Mutex::Autolock _l(mLock);
2124 AudioStreamOut *output = mOutput;
2125 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002126 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2127 // must push a NULL and wait for ack
2128 mOutputSink.clear();
2129 mPipeSink.clear();
2130 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002131 return output;
2132}
2133
2134// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002135audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002136{
2137 if (mOutput == NULL) {
2138 return NULL;
2139 }
2140 return &mOutput->stream->common;
2141}
2142
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002143uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002144{
Eric Laurentab9071b2012-06-04 13:45:29 -07002145 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002146}
2147
Eric Laurenta011e352012-03-29 15:51:43 -07002148status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2149{
2150 if (!isValidSyncEvent(event)) {
2151 return BAD_VALUE;
2152 }
2153
2154 Mutex::Autolock _l(mLock);
2155
2156 for (size_t i = 0; i < mTracks.size(); ++i) {
2157 sp<Track> track = mTracks[i];
2158 if (event->triggerSession() == track->sessionId()) {
2159 track->setSyncEvent(event);
2160 return NO_ERROR;
2161 }
2162 }
2163
2164 return NAME_NOT_FOUND;
2165}
2166
2167bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2168{
2169 switch (event->type()) {
2170 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2171 return true;
2172 default:
2173 break;
2174 }
2175 return false;
2176}
2177
Eric Laurent44a957f2012-05-15 15:26:05 -07002178void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2179{
2180 size_t count = tracksToRemove.size();
2181 if (CC_UNLIKELY(count)) {
2182 for (size_t i = 0 ; i < count ; i++) {
2183 const sp<Track>& track = tracksToRemove.itemAt(i);
2184 if ((track->sharedBuffer() != 0) &&
2185 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2186 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2187 }
2188 }
2189 }
2190
2191}
2192
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193// ----------------------------------------------------------------------------
2194
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002195AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002196 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002197 : PlaybackThread(audioFlinger, output, id, device, type),
2198 // mAudioMixer below
2199#ifdef SOAKER
2200 mSoaker(NULL),
2201#endif
2202 // mFastMixer below
2203 mFastMixerFutex(0)
2204 // mOutputSink below
2205 // mPipeSink below
2206 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207{
Glenn Kasten58912562012-04-03 10:45:00 -07002208 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2209 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2210 "mFrameCount=%d, mNormalFrameCount=%d",
2211 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2212 mNormalFrameCount);
2213 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2214
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215 // FIXME - Current mixer implementation only supports stereo output
2216 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002217 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218 }
Glenn Kasten58912562012-04-03 10:45:00 -07002219
2220 // create an NBAIO sink for the HAL output stream, and negotiate
2221 mOutputSink = new AudioStreamOutSink(output->stream);
2222 size_t numCounterOffers = 0;
2223 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2224 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2225 ALOG_ASSERT(index == 0);
2226
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002227 // initialize fast mixer depending on configuration
2228 bool initFastMixer;
2229 switch (kUseFastMixer) {
2230 case FastMixer_Never:
2231 initFastMixer = false;
2232 break;
2233 case FastMixer_Always:
2234 initFastMixer = true;
2235 break;
2236 case FastMixer_Static:
2237 case FastMixer_Dynamic:
2238 initFastMixer = mFrameCount < mNormalFrameCount;
2239 break;
2240 }
2241 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002242
2243 // create a MonoPipe to connect our submix to FastMixer
2244 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002245 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2246 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2247 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2248 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002249 const NBAIO_Format offers[1] = {format};
2250 size_t numCounterOffers = 0;
2251 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2252 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002253 monoPipe->setAvgFrames((mScreenState & 1) ?
2254 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002255 mPipeSink = monoPipe;
2256
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002257#ifdef TEE_SINK_FRAMES
2258 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2259 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2260 numCounterOffers = 0;
2261 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2262 ALOG_ASSERT(index == 0);
2263 mTeeSink = teeSink;
2264 PipeReader *teeSource = new PipeReader(*teeSink);
2265 numCounterOffers = 0;
2266 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2267 ALOG_ASSERT(index == 0);
2268 mTeeSource = teeSource;
2269#endif
2270
Glenn Kasten58912562012-04-03 10:45:00 -07002271#ifdef SOAKER
2272 // create a soaker as workaround for governor issues
2273 mSoaker = new Soaker();
2274 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2275 mSoaker->run("Soaker", PRIORITY_LOWEST);
2276#endif
2277
2278 // create fast mixer and configure it initially with just one fast track for our submix
2279 mFastMixer = new FastMixer();
2280 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002281#ifdef STATE_QUEUE_DUMP
2282 sq->setObserverDump(&mStateQueueObserverDump);
2283 sq->setMutatorDump(&mStateQueueMutatorDump);
2284#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002285 FastMixerState *state = sq->begin();
2286 FastTrack *fastTrack = &state->mFastTracks[0];
2287 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2288 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2289 fastTrack->mVolumeProvider = NULL;
2290 fastTrack->mGeneration++;
2291 state->mFastTracksGen++;
2292 state->mTrackMask = 1;
2293 // fast mixer will use the HAL output sink
2294 state->mOutputSink = mOutputSink.get();
2295 state->mOutputSinkGen++;
2296 state->mFrameCount = mFrameCount;
2297 state->mCommand = FastMixerState::COLD_IDLE;
2298 // already done in constructor initialization list
2299 //mFastMixerFutex = 0;
2300 state->mColdFutexAddr = &mFastMixerFutex;
2301 state->mColdGen++;
2302 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002303 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002304 sq->end();
2305 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2306
2307 // start the fast mixer
2308 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2309#ifdef HAVE_REQUEST_PRIORITY
2310 pid_t tid = mFastMixer->getTid();
2311 int err = requestPriority(getpid_cached, tid, 2);
2312 if (err != 0) {
2313 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2314 2, getpid_cached, tid, err);
2315 }
2316#endif
2317
Glenn Kastenc15d6652012-05-30 14:52:57 -07002318#ifdef AUDIO_WATCHDOG
2319 // create and start the watchdog
2320 mAudioWatchdog = new AudioWatchdog();
2321 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2322 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2323 tid = mAudioWatchdog->getTid();
2324 err = requestPriority(getpid_cached, tid, 1);
2325 if (err != 0) {
2326 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2327 1, getpid_cached, tid, err);
2328 }
2329#endif
2330
Glenn Kasten58912562012-04-03 10:45:00 -07002331 } else {
2332 mFastMixer = NULL;
2333 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002334
2335 switch (kUseFastMixer) {
2336 case FastMixer_Never:
2337 case FastMixer_Dynamic:
2338 mNormalSink = mOutputSink;
2339 break;
2340 case FastMixer_Always:
2341 mNormalSink = mPipeSink;
2342 break;
2343 case FastMixer_Static:
2344 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2345 break;
2346 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347}
2348
2349AudioFlinger::MixerThread::~MixerThread()
2350{
Glenn Kasten58912562012-04-03 10:45:00 -07002351 if (mFastMixer != NULL) {
2352 FastMixerStateQueue *sq = mFastMixer->sq();
2353 FastMixerState *state = sq->begin();
2354 if (state->mCommand == FastMixerState::COLD_IDLE) {
2355 int32_t old = android_atomic_inc(&mFastMixerFutex);
2356 if (old == -1) {
2357 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2358 }
2359 }
2360 state->mCommand = FastMixerState::EXIT;
2361 sq->end();
2362 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2363 mFastMixer->join();
2364 // Though the fast mixer thread has exited, it's state queue is still valid.
2365 // We'll use that extract the final state which contains one remaining fast track
2366 // corresponding to our sub-mix.
2367 state = sq->begin();
2368 ALOG_ASSERT(state->mTrackMask == 1);
2369 FastTrack *fastTrack = &state->mFastTracks[0];
2370 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2371 delete fastTrack->mBufferProvider;
2372 sq->end(false /*didModify*/);
2373 delete mFastMixer;
2374#ifdef SOAKER
2375 if (mSoaker != NULL) {
2376 mSoaker->requestExitAndWait();
2377 }
2378 delete mSoaker;
2379#endif
Glenn Kastenc15d6652012-05-30 14:52:57 -07002380 if (mAudioWatchdog != 0) {
2381 mAudioWatchdog->requestExit();
2382 mAudioWatchdog->requestExitAndWait();
2383 mAudioWatchdog.clear();
2384 }
Glenn Kasten58912562012-04-03 10:45:00 -07002385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 delete mAudioMixer;
2387}
2388
Glenn Kasten83efdd02012-02-24 07:21:32 -08002389class CpuStats {
2390public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002391 CpuStats();
2392 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002393#ifdef DEBUG_CPU_USAGE
2394private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002395 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2396 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2397
2398 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2399
2400 int mCpuNum; // thread's current CPU number
2401 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002402#endif
2403};
2404
Glenn Kasten190a46f2012-03-06 11:27:10 -08002405CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002406#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002407 : mCpuNum(-1), mCpukHz(-1)
2408#endif
2409{
2410}
2411
2412void CpuStats::sample(const String8 &title) {
2413#ifdef DEBUG_CPU_USAGE
2414 // get current thread's delta CPU time in wall clock ns
2415 double wcNs;
2416 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2417
2418 // record sample for wall clock statistics
2419 if (valid) {
2420 mWcStats.sample(wcNs);
2421 }
2422
2423 // get the current CPU number
2424 int cpuNum = sched_getcpu();
2425
2426 // get the current CPU frequency in kHz
2427 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2428
2429 // check if either CPU number or frequency changed
2430 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2431 mCpuNum = cpuNum;
2432 mCpukHz = cpukHz;
2433 // ignore sample for purposes of cycles
2434 valid = false;
2435 }
2436
2437 // if no change in CPU number or frequency, then record sample for cycle statistics
2438 if (valid && mCpukHz > 0) {
2439 double cycles = wcNs * cpukHz * 0.000001;
2440 mHzStats.sample(cycles);
2441 }
2442
2443 unsigned n = mWcStats.n();
2444 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002445 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002446 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002447 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2448 double perLoop = elapsed / (double) n;
2449 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002450 double perLoop1k = perLoop * 0.001;
2451 double mean = mWcStats.mean();
2452 double stddev = mWcStats.stddev();
2453 double minimum = mWcStats.minimum();
2454 double maximum = mWcStats.maximum();
2455 double meanCycles = mHzStats.mean();
2456 double stddevCycles = mHzStats.stddev();
2457 double minCycles = mHzStats.minimum();
2458 double maxCycles = mHzStats.maximum();
2459 mCpuUsage.resetElapsed();
2460 mWcStats.reset();
2461 mHzStats.reset();
2462 ALOGD("CPU usage for %s over past %.1f secs\n"
2463 " (%u mixer loops at %.1f mean ms per loop):\n"
2464 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2465 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2466 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2467 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002468 elapsed * .000000001, n, perLoop * .000001,
2469 mean * .001,
2470 stddev * .001,
2471 minimum * .001,
2472 maximum * .001,
2473 mean / perLoop100,
2474 stddev / perLoop100,
2475 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002476 maximum / perLoop100,
2477 meanCycles / perLoop1k,
2478 stddevCycles / perLoop1k,
2479 minCycles / perLoop1k,
2480 maxCycles / perLoop1k);
2481
Glenn Kasten83efdd02012-02-24 07:21:32 -08002482 }
2483 }
2484#endif
2485};
2486
Glenn Kasten37d825e2012-02-24 07:21:48 -08002487void AudioFlinger::PlaybackThread::checkSilentMode_l()
2488{
2489 if (!mMasterMute) {
2490 char value[PROPERTY_VALUE_MAX];
2491 if (property_get("ro.audio.silent", value, "0") > 0) {
2492 char *endptr;
2493 unsigned long ul = strtoul(value, &endptr, 0);
2494 if (*endptr == '\0' && ul != 0) {
2495 ALOGD("Silence is golden");
2496 // The setprop command will not allow a property to be changed after
2497 // the first time it is set, so we don't have to worry about un-muting.
2498 setMasterMute_l(true);
2499 }
2500 }
2501 }
2502}
2503
Glenn Kasten000f0e32012-03-01 17:10:56 -08002504bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505{
2506 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002507
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002509
2510 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002512
Glenn Kasten000f0e32012-03-01 17:10:56 -08002513 // DUPLICATING
2514 // FIXME could this be made local to while loop?
2515 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002516
Glenn Kasten66fcab92012-02-24 14:59:21 -08002517 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002518 sleepTime = idleSleepTime;
2519
2520if (mType == MIXER) {
2521 sleepTimeShift = 0;
2522}
2523
Glenn Kasten83efdd02012-02-24 07:21:32 -08002524 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002525 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526
Eric Laurentfeb0db62011-07-22 09:04:31 -07002527 acquireWakeLock();
2528
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 while (!exitPending())
2530 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002531 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002532
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002533 Vector< sp<EffectChain> > effectChains;
2534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 processConfigEvents();
2536
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 { // scope for mLock
2538
2539 Mutex::Autolock _l(mLock);
2540
2541 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002542 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 }
2544
Glenn Kastenfa26a852012-03-06 11:28:04 -08002545 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002546
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002548 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002549 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002551
2552 threadLoop_standby();
2553
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 mStandby = true;
2555 mBytesWritten = 0;
2556 }
2557
Glenn Kasten3e074702012-02-28 18:40:35 -08002558 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 // we're about to wait, flush the binder command buffer
2560 IPCThreadState::self()->flushCommands();
2561
Glenn Kastenfa26a852012-03-06 11:28:04 -08002562 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 if (exitPending()) break;
2565
Eric Laurentfeb0db62011-07-22 09:04:31 -07002566 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002568 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002570 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002571 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572
Eric Laurentda747442012-04-25 18:53:13 -07002573 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002574 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575
Glenn Kasten37d825e2012-02-24 07:21:48 -08002576 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577
Glenn Kasten000f0e32012-03-01 17:10:56 -08002578 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002580 if (mType == MIXER) {
2581 sleepTimeShift = 0;
2582 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002583
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584 continue;
2585 }
2586 }
2587
Glenn Kasten81028042012-04-30 18:15:12 -07002588 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002589 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590
2591 // prevent any changes in effect chain list and in each effect chain
2592 // during mixing and effect process as the audio buffers could be deleted
2593 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002594 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596
Glenn Kastenfec279f2012-03-08 07:47:15 -08002597 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002598 threadLoop_mix();
2599 } else {
2600 threadLoop_sleepTime();
2601 }
2602
2603 if (mSuspended > 0) {
2604 sleepTime = suspendSleepTimeUs();
2605 }
2606
2607 // only process effects if we're going to write
2608 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002609 for (size_t i = 0; i < effectChains.size(); i ++) {
2610 effectChains[i]->process_l();
2611 }
2612 }
2613
2614 // enable changes in effect chain
2615 unlockEffectChains(effectChains);
2616
2617 // sleepTime == 0 means we must write to audio hardware
2618 if (sleepTime == 0) {
2619
2620 threadLoop_write();
2621
2622if (mType == MIXER) {
2623 // write blocked detection
2624 nsecs_t now = systemTime();
2625 nsecs_t delta = now - mLastWriteTime;
2626 if (!mStandby && delta > maxPeriod) {
2627 mNumDelayedWrites++;
2628 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002629#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002630 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002631#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002632 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2633 ns2ms(delta), mNumDelayedWrites, this);
2634 lastWarning = now;
2635 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636 }
2637}
2638
2639 mStandby = false;
2640 } else {
2641 usleep(sleepTime);
2642 }
2643
Glenn Kasten58912562012-04-03 10:45:00 -07002644 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002645 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002646 // same lock. This will also mutate and push a new fast mixer state.
2647 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002648 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002649
Glenn Kastenfa26a852012-03-06 11:28:04 -08002650 // FIXME I don't understand the need for this here;
2651 // it was in the original code but maybe the
2652 // assignment in saveOutputTracks() makes this unnecessary?
2653 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002654
2655 // Effect chains will be actually deleted here if they were removed from
2656 // mEffectChains list during mixing or effects processing
2657 effectChains.clear();
2658
2659 // FIXME Note that the above .clear() is no longer necessary since effectChains
2660 // is now local to this block, but will keep it for now (at least until merge done).
2661 }
2662
2663if (mType == MIXER || mType == DIRECT) {
2664 // put output stream into standby mode
2665 if (!mStandby) {
2666 mOutput->stream->common.standby(&mOutput->stream->common);
2667 }
2668}
2669if (mType == DUPLICATING) {
2670 // for DuplicatingThread, standby mode is handled by the outputTracks
2671}
2672
2673 releaseWakeLock();
2674
2675 ALOGV("Thread %p type %d exiting", this, mType);
2676 return false;
2677}
2678
Glenn Kasten58912562012-04-03 10:45:00 -07002679void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2680{
Glenn Kasten58912562012-04-03 10:45:00 -07002681 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2682}
2683
2684void AudioFlinger::MixerThread::threadLoop_write()
2685{
2686 // FIXME we should only do one push per cycle; confirm this is true
2687 // Start the fast mixer if it's not already running
2688 if (mFastMixer != NULL) {
2689 FastMixerStateQueue *sq = mFastMixer->sq();
2690 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002691 if (state->mCommand != FastMixerState::MIX_WRITE &&
2692 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002693 if (state->mCommand == FastMixerState::COLD_IDLE) {
2694 int32_t old = android_atomic_inc(&mFastMixerFutex);
2695 if (old == -1) {
2696 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2697 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002698 if (mAudioWatchdog != 0) {
2699 mAudioWatchdog->resume();
2700 }
Glenn Kasten58912562012-04-03 10:45:00 -07002701 }
2702 state->mCommand = FastMixerState::MIX_WRITE;
2703 sq->end();
2704 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002705 if (kUseFastMixer == FastMixer_Dynamic) {
2706 mNormalSink = mPipeSink;
2707 }
Glenn Kasten58912562012-04-03 10:45:00 -07002708 } else {
2709 sq->end(false /*didModify*/);
2710 }
2711 }
2712 PlaybackThread::threadLoop_write();
2713}
2714
Glenn Kasten000f0e32012-03-01 17:10:56 -08002715// shared by MIXER and DIRECT, overridden by DUPLICATING
2716void AudioFlinger::PlaybackThread::threadLoop_write()
2717{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002718 // FIXME rewrite to reduce number of system calls
2719 mLastWriteTime = systemTime();
2720 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002721 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002722
Eric Laurent67c0a582012-05-01 19:31:12 -07002723 // If an NBAIO sink is present, use it to write the normal mixer's submix
2724 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002725#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002726 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002727#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002728 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002729#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002730 // update the setpoint when gScreenState changes
2731 uint32_t screenState = gScreenState;
2732 if (screenState != mScreenState) {
2733 mScreenState = screenState;
2734 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2735 if (pipe != NULL) {
2736 pipe->setAvgFrames((mScreenState & 1) ?
2737 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2738 }
2739 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002740 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002741#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002742 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002743#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002744 if (framesWritten > 0) {
2745 bytesWritten = framesWritten << mBitShift;
2746 } else {
2747 bytesWritten = framesWritten;
2748 }
2749 // otherwise use the HAL / AudioStreamOut directly
2750 } else {
2751 // Direct output thread.
2752 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002753 }
2754
Eric Laurent67c0a582012-05-01 19:31:12 -07002755 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002756 mNumWrites++;
2757 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002758}
2759
Glenn Kasten58912562012-04-03 10:45:00 -07002760void AudioFlinger::MixerThread::threadLoop_standby()
2761{
2762 // Idle the fast mixer if it's currently running
2763 if (mFastMixer != NULL) {
2764 FastMixerStateQueue *sq = mFastMixer->sq();
2765 FastMixerState *state = sq->begin();
2766 if (!(state->mCommand & FastMixerState::IDLE)) {
2767 state->mCommand = FastMixerState::COLD_IDLE;
2768 state->mColdFutexAddr = &mFastMixerFutex;
2769 state->mColdGen++;
2770 mFastMixerFutex = 0;
2771 sq->end();
2772 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2773 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002774 if (kUseFastMixer == FastMixer_Dynamic) {
2775 mNormalSink = mOutputSink;
2776 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002777 if (mAudioWatchdog != 0) {
2778 mAudioWatchdog->pause();
2779 }
Glenn Kasten58912562012-04-03 10:45:00 -07002780 } else {
2781 sq->end(false /*didModify*/);
2782 }
2783 }
2784 PlaybackThread::threadLoop_standby();
2785}
2786
Glenn Kasten000f0e32012-03-01 17:10:56 -08002787// shared by MIXER and DIRECT, overridden by DUPLICATING
2788void AudioFlinger::PlaybackThread::threadLoop_standby()
2789{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2791 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002792}
2793
2794void AudioFlinger::MixerThread::threadLoop_mix()
2795{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002796 // obtain the presentation timestamp of the next output buffer
2797 int64_t pts;
2798 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002799
Glenn Kasten952eeb22012-03-06 11:30:57 -08002800 if (NULL != mOutput->stream->get_next_write_timestamp) {
2801 status = mOutput->stream->get_next_write_timestamp(
2802 mOutput->stream, &pts);
2803 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002804
Glenn Kasten952eeb22012-03-06 11:30:57 -08002805 if (status != NO_ERROR) {
2806 pts = AudioBufferProvider::kInvalidPTS;
2807 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002808
Glenn Kasten952eeb22012-03-06 11:30:57 -08002809 // mix buffers...
2810 mAudioMixer->process(pts);
2811 // increase sleep time progressively when application underrun condition clears.
2812 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2813 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2814 // such that we would underrun the audio HAL.
2815 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2816 sleepTimeShift--;
2817 }
2818 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002819 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002821}
2822
2823void AudioFlinger::MixerThread::threadLoop_sleepTime()
2824{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002825 // If no tracks are ready, sleep once for the duration of an output
2826 // buffer size, then write 0s to the output
2827 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002828 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002829 sleepTime = activeSleepTime >> sleepTimeShift;
2830 if (sleepTime < kMinThreadSleepTimeUs) {
2831 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002833 // reduce sleep time in case of consecutive application underruns to avoid
2834 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2835 // duration we would end up writing less data than needed by the audio HAL if
2836 // the condition persists.
2837 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2838 sleepTimeShift++;
2839 }
2840 } else {
2841 sleepTime = idleSleepTime;
2842 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002843 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002844 memset (mMixBuffer, 0, mixBufferSize);
2845 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002846 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002847 }
2848 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849}
2850
2851// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002852AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002853 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854{
2855
Glenn Kasten29c23c32012-01-26 13:37:52 -08002856 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002858 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 size_t mixedTracks = 0;
2860 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002861 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002862 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002863 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864
2865 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002866 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867
Eric Laurent571d49c2010-08-11 05:20:11 -07002868 if (masterMute) {
2869 masterVolume = 0;
2870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002872 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002874 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002875 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 masterVolume = (float)((v + (1 << 23)) >> 24);
2877 chain.clear();
2878 }
2879
Glenn Kasten288ed212012-04-25 17:52:27 -07002880 // prepare a new state to push
2881 FastMixerStateQueue *sq = NULL;
2882 FastMixerState *state = NULL;
2883 bool didModify = false;
2884 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2885 if (mFastMixer != NULL) {
2886 sq = mFastMixer->sq();
2887 state = sq->begin();
2888 }
2889
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002891 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 if (t == 0) continue;
2893
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002894 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002896
Glenn Kasten288ed212012-04-25 17:52:27 -07002897 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002898 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002899
2900 // It's theoretically possible (though unlikely) for a fast track to be created
2901 // and then removed within the same normal mix cycle. This is not a problem, as
2902 // the track never becomes active so it's fast mixer slot is never touched.
2903 // The converse, of removing an (active) track and then creating a new track
2904 // at the identical fast mixer slot within the same normal mix cycle,
2905 // is impossible because the slot isn't marked available until the end of each cycle.
2906 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002907 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2908 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 FastTrack *fastTrack = &state->mFastTracks[j];
2910
2911 // Determine whether the track is currently in underrun condition,
2912 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002913 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2914 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002915 uint32_t recentFull = (underruns.mBitFields.mFull -
2916 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2917 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2918 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2919 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2920 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2921 uint32_t recentUnderruns = recentPartial + recentEmpty;
2922 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002923 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002924 // or stopped which can occur when flush() is called while active
2925 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002926 track->mUnderrunCount += recentUnderruns;
2927 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002928
Glenn Kastend08f48c2012-05-01 18:14:02 -07002929 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002930 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002931 bool isActive = true;
2932 switch (track->mState) {
2933 case TrackBase::STOPPING_1:
2934 // track stays active in STOPPING_1 state until first underrun
2935 if (recentUnderruns > 0) {
2936 track->mState = TrackBase::STOPPING_2;
2937 }
2938 break;
2939 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002940 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002941 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002942 break;
2943 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002944 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002945 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002946 break;
2947 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002948 if (recentFull > 0 || recentPartial > 0) {
2949 // track has provided at least some frames recently: reset retry count
2950 track->mRetryCount = kMaxTrackRetries;
2951 }
2952 if (recentUnderruns == 0) {
2953 // no recent underruns: stay active
2954 break;
2955 }
2956 // there has recently been an underrun of some kind
2957 if (track->sharedBuffer() == 0) {
2958 // were any of the recent underruns "empty" (no frames available)?
2959 if (recentEmpty == 0) {
2960 // no, then ignore the partial underruns as they are allowed indefinitely
2961 break;
2962 }
2963 // there has recently been an "empty" underrun: decrement the retry counter
2964 if (--(track->mRetryCount) > 0) {
2965 break;
2966 }
2967 // indicate to client process that the track was disabled because of underrun;
2968 // it will then automatically call start() when data is available
2969 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2970 // remove from active list, but state remains ACTIVE [confusing but true]
2971 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002972 break;
2973 }
2974 // fall through
2975 case TrackBase::STOPPING_2:
2976 case TrackBase::PAUSED:
2977 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002978 case TrackBase::STOPPED:
2979 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002980 // Check for presentation complete if track is inactive
2981 // We have consumed all the buffers of this track.
2982 // This would be incomplete if we auto-paused on underrun
2983 {
2984 size_t audioHALFrames =
2985 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2986 size_t framesWritten =
2987 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2988 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2989 // track stays in active list until presentation is complete
2990 break;
2991 }
2992 }
2993 if (track->isStopping_2()) {
2994 track->mState = TrackBase::STOPPED;
2995 }
2996 if (track->isStopped()) {
2997 // Can't reset directly, as fast mixer is still polling this track
2998 // track->reset();
2999 // So instead mark this track as needing to be reset after push with ack
3000 resetMask |= 1 << i;
3001 }
3002 isActive = false;
3003 break;
3004 case TrackBase::IDLE:
3005 default:
3006 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003007 }
3008
3009 if (isActive) {
3010 // was it previously inactive?
3011 if (!(state->mTrackMask & (1 << j))) {
3012 ExtendedAudioBufferProvider *eabp = track;
3013 VolumeProvider *vp = track;
3014 fastTrack->mBufferProvider = eabp;
3015 fastTrack->mVolumeProvider = vp;
3016 fastTrack->mSampleRate = track->mSampleRate;
3017 fastTrack->mChannelMask = track->mChannelMask;
3018 fastTrack->mGeneration++;
3019 state->mTrackMask |= 1 << j;
3020 didModify = true;
3021 // no acknowledgement required for newly active tracks
3022 }
3023 // cache the combined master volume and stream type volume for fast mixer; this
3024 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3025 track->mCachedVolume = track->isMuted() ?
3026 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3027 ++fastTracks;
3028 } else {
3029 // was it previously active?
3030 if (state->mTrackMask & (1 << j)) {
3031 fastTrack->mBufferProvider = NULL;
3032 fastTrack->mGeneration++;
3033 state->mTrackMask &= ~(1 << j);
3034 didModify = true;
3035 // If any fast tracks were removed, we must wait for acknowledgement
3036 // because we're about to decrement the last sp<> on those tracks.
3037 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003038 } else {
3039 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003040 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003041 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003042 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003043 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003044 }
3045 continue;
3046 }
3047
3048 { // local variable scope to avoid goto warning
3049
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 audio_track_cblk_t* cblk = track->cblk();
3051
3052 // The first time a track is added we wait
3053 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003054 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003055 // make sure that we have enough frames to mix one full buffer.
3056 // enforce this condition only once to enable draining the buffer in case the client
3057 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003058 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003059 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003060 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003061 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003062 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003063 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003064 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003065 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003066 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003067 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003068 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003069 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003070 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3071 // the minimum track buffer size is normally twice the number of frames necessary
3072 // to fill one buffer and the resampler should not leave more than one buffer worth
3073 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003074 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003075 }
3076 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003077 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 !track->isPaused() && !track->isTerminated())
3079 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003080 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081
3082 mixedTracks++;
3083
3084 // track->mainBuffer() != mMixBuffer means there is an effect chain
3085 // connected to the track
3086 chain.clear();
3087 if (track->mainBuffer() != mMixBuffer) {
3088 chain = getEffectChain_l(track->sessionId());
3089 // Delegate volume control to effect in track effect chain if needed
3090 if (chain != 0) {
3091 tracksWithEffect++;
3092 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003093 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003094 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 }
3096 }
3097
3098
3099 int param = AudioMixer::VOLUME;
3100 if (track->mFillingUpStatus == Track::FS_FILLED) {
3101 // no ramp for the first volume setting
3102 track->mFillingUpStatus = Track::FS_ACTIVE;
3103 if (track->mState == TrackBase::RESUMING) {
3104 track->mState = TrackBase::ACTIVE;
3105 param = AudioMixer::RAMP_VOLUME;
3106 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003107 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 } else if (cblk->server != 0) {
3109 // If the track is stopped before the first frame was mixed,
3110 // do not apply ramp
3111 param = AudioMixer::RAMP_VOLUME;
3112 }
3113
3114 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003115 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003116 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003117 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003118 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 if (track->isPausing()) {
3120 track->setPaused();
3121 }
3122 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003123
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003125 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003127 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003128 vl = vlr & 0xFFFF;
3129 vr = vlr >> 16;
3130 // track volumes come from shared memory, so can't be trusted and must be clamped
3131 if (vl > MAX_GAIN_INT) {
3132 ALOGV("Track left volume out of range: %04X", vl);
3133 vl = MAX_GAIN_INT;
3134 }
3135 if (vr > MAX_GAIN_INT) {
3136 ALOGV("Track right volume out of range: %04X", vr);
3137 vr = MAX_GAIN_INT;
3138 }
3139 // now apply the master volume and stream type volume
3140 vl = (uint32_t)(v * vl) << 12;
3141 vr = (uint32_t)(v * vr) << 12;
3142 // assuming master volume and stream type volume each go up to 1.0,
3143 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144
Glenn Kasten05632a52012-01-03 14:22:33 -08003145 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3146 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003147 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003148 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003149 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003150 }
3151 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003153 // Delegate volume control to effect in track effect chain if needed
3154 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3155 // Do not ramp volume if volume is controlled by effect
3156 param = AudioMixer::VOLUME;
3157 track->mHasVolumeController = true;
3158 } else {
3159 // force no volume ramp when volume controller was just disabled or removed
3160 // from effect chain to avoid volume spike
3161 if (track->mHasVolumeController) {
3162 param = AudioMixer::VOLUME;
3163 }
3164 track->mHasVolumeController = false;
3165 }
3166
3167 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003168 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003169 vl = (vl + (1 << 11)) >> 12;
3170 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3171 vr = (vr + (1 << 11)) >> 12;
3172 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003173
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003174 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 -07003175
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003177 mAudioMixer->setBufferProvider(name, track);
3178 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003180 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3181 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3182 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003184 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 AudioMixer::TRACK,
3186 AudioMixer::FORMAT, (void *)track->format());
3187 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003188 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003190 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003192 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 AudioMixer::RESAMPLE,
3194 AudioMixer::SAMPLE_RATE,
3195 (void *)(cblk->sampleRate));
3196 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003197 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 AudioMixer::TRACK,
3199 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3200 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003201 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 AudioMixer::TRACK,
3203 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3204
3205 // reset retry count
3206 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003207
Eric Laurent27741442012-01-17 19:20:12 -08003208 // If one track is ready, set the mixer ready if:
3209 // - the mixer was not ready during previous round OR
3210 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003211 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003212 mixerStatus != MIXER_TRACKS_ENABLED) {
3213 mixerStatus = MIXER_TRACKS_READY;
3214 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003216 // clear effect chain input buffer if an active track underruns to avoid sending
3217 // previous audio buffer again to effects
3218 chain = getEffectChain_l(track->sessionId());
3219 if (chain != 0) {
3220 chain->clearInputBuffer();
3221 }
3222
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003223 //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 -07003224 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3225 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 // We have consumed all the buffers of this track.
3227 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003228 // TODO: use actual buffer filling status instead of latency when available from
3229 // audio HAL
3230 size_t audioHALFrames =
3231 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3232 size_t framesWritten =
3233 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3234 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003235 if (track->isStopped()) {
3236 track->reset();
3237 }
Eric Laurenta011e352012-03-29 15:51:43 -07003238 tracksToRemove->add(track);
3239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003241 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 // No buffers for this track. Give it a few chances to
3243 // fill a buffer, then remove it from active list.
3244 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003245 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003247 // indicate to client process that the track was disabled because of underrun;
3248 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003249 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003250 // If one track is not ready, mark the mixer also not ready if:
3251 // - the mixer was ready during previous round OR
3252 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003253 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003254 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 mixerStatus = MIXER_TRACKS_ENABLED;
3256 }
3257 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003258 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 }
Glenn Kasten58912562012-04-03 10:45:00 -07003260
3261 } // local variable scope to avoid goto warning
3262track_is_ready: ;
3263
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 }
3265
Glenn Kasten288ed212012-04-25 17:52:27 -07003266 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003267 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003268 if (didModify) {
3269 state->mFastTracksGen++;
3270 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3271 if (kUseFastMixer == FastMixer_Dynamic &&
3272 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3273 state->mCommand = FastMixerState::COLD_IDLE;
3274 state->mColdFutexAddr = &mFastMixerFutex;
3275 state->mColdGen++;
3276 mFastMixerFutex = 0;
3277 if (kUseFastMixer == FastMixer_Dynamic) {
3278 mNormalSink = mOutputSink;
3279 }
3280 // If we go into cold idle, need to wait for acknowledgement
3281 // so that fast mixer stops doing I/O.
3282 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003283 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003284 }
3285 sq->end();
3286 }
3287 if (sq != NULL) {
3288 sq->end(didModify);
3289 sq->push(block);
3290 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003291 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3292 mAudioWatchdog->pause();
3293 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003294
3295 // Now perform the deferred reset on fast tracks that have stopped
3296 while (resetMask != 0) {
3297 size_t i = __builtin_ctz(resetMask);
3298 ALOG_ASSERT(i < count);
3299 resetMask &= ~(1 << i);
3300 sp<Track> t = mActiveTracks[i].promote();
3301 if (t == 0) continue;
3302 Track* track = t.get();
3303 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3304 track->reset();
3305 }
Glenn Kasten58912562012-04-03 10:45:00 -07003306
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 // remove all the tracks that need to be...
3308 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003309 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 for (size_t i=0 ; i<count ; i++) {
3311 const sp<Track>& track = tracksToRemove->itemAt(i);
3312 mActiveTracks.remove(track);
3313 if (track->mainBuffer() != mMixBuffer) {
3314 chain = getEffectChain_l(track->sessionId());
3315 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003316 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003317 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 }
3319 }
3320 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003321 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 }
3323 }
3324 }
3325
3326 // mix buffer must be cleared if all tracks are connected to an
3327 // effect chain as in this case the mixer will not write to
3328 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003329 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3330 // FIXME as a performance optimization, should remember previous zero status
3331 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 }
3333
Glenn Kasten58912562012-04-03 10:45:00 -07003334 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003335 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003336 if (fastTracks > 0) {
3337 mixerStatus = MIXER_TRACKS_READY;
3338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 return mixerStatus;
3340}
3341
Glenn Kasten66fcab92012-02-24 14:59:21 -08003342/*
3343The derived values that are cached:
3344 - mixBufferSize from frame count * frame size
3345 - activeSleepTime from activeSleepTimeUs()
3346 - idleSleepTime from idleSleepTimeUs()
3347 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3348 - maxPeriod from frame count and sample rate (MIXER only)
3349
3350The parameters that affect these derived values are:
3351 - frame count
3352 - frame size
3353 - sample rate
3354 - device type: A2DP or not
3355 - device latency
3356 - format: PCM or not
3357 - active sleep time
3358 - idle sleep time
3359*/
3360
3361void AudioFlinger::PlaybackThread::cacheParameters_l()
3362{
Glenn Kasten58912562012-04-03 10:45:00 -07003363 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003364 activeSleepTime = activeSleepTimeUs();
3365 idleSleepTime = idleSleepTimeUs();
3366}
3367
Eric Laurent22167852012-06-20 12:26:32 -07003368void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369{
Steve Block3856b092011-10-20 11:56:00 +01003370 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003371 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003373
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 size_t size = mTracks.size();
3375 for (size_t i = 0; i < size; i++) {
3376 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003377 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003378 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 }
3381 }
3382}
3383
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003385int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003387 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388}
3389
3390// deleteTrackName_l() must be called with ThreadBase::mLock held
3391void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3392{
Steve Block3856b092011-10-20 11:56:00 +01003393 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 mAudioMixer->deleteTrackName(name);
3395}
3396
3397// checkForNewParameters_l() must be called with ThreadBase::mLock held
3398bool AudioFlinger::MixerThread::checkForNewParameters_l()
3399{
Glenn Kasten58912562012-04-03 10:45:00 -07003400 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3401 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 bool reconfig = false;
3403
3404 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003405
3406 if (mFastMixer != NULL) {
3407 FastMixerStateQueue *sq = mFastMixer->sq();
3408 FastMixerState *state = sq->begin();
3409 if (!(state->mCommand & FastMixerState::IDLE)) {
3410 previousCommand = state->mCommand;
3411 state->mCommand = FastMixerState::HOT_IDLE;
3412 sq->end();
3413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3414 } else {
3415 sq->end(false /*didModify*/);
3416 }
3417 }
3418
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 status_t status = NO_ERROR;
3420 String8 keyValuePair = mNewParameters[0];
3421 AudioParameter param = AudioParameter(keyValuePair);
3422 int value;
3423
3424 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3425 reconfig = true;
3426 }
3427 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003428 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 status = BAD_VALUE;
3430 } else {
3431 reconfig = true;
3432 }
3433 }
3434 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003435 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 status = BAD_VALUE;
3437 } else {
3438 reconfig = true;
3439 }
3440 }
3441 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3442 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003443 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 // if frame count is changed after track creation
3445 if (!mTracks.isEmpty()) {
3446 status = INVALID_OPERATION;
3447 } else {
3448 reconfig = true;
3449 }
3450 }
3451 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003452#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003453 // when changing the audio output device, call addBatteryData to notify
3454 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003455 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003456 uint32_t params = 0;
3457 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003458 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003459 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3460 }
3461
3462 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003463 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003464 // check if any other device (except speaker) is on
3465 if (value & deviceWithoutSpeaker ) {
3466 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3467 }
3468
3469 if (params != 0) {
3470 addBatteryData(params);
3471 }
3472 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003473#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003474
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 // forward device change to effects that have requested to be
3476 // aware of attached audio device.
3477 mDevice = (uint32_t)value;
3478 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003479 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 }
3481 }
3482
3483 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003484 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003485 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003487 mOutput->stream->common.standby(&mOutput->stream->common);
3488 mStandby = true;
3489 mBytesWritten = 0;
3490 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003491 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 }
3493 if (status == NO_ERROR && reconfig) {
3494 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003495 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3496 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003498 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003500 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 if (name < 0) break;
3502 mTracks[i]->mName = name;
3503 // limit track sample rate to 2 x new output sample rate
3504 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3505 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3506 }
3507 }
3508 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3509 }
3510 }
3511
3512 mNewParameters.removeAt(0);
3513
3514 mParamStatus = status;
3515 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003516 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3517 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003518 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 }
Glenn Kasten58912562012-04-03 10:45:00 -07003520
3521 if (!(previousCommand & FastMixerState::IDLE)) {
3522 ALOG_ASSERT(mFastMixer != NULL);
3523 FastMixerStateQueue *sq = mFastMixer->sq();
3524 FastMixerState *state = sq->begin();
3525 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3526 state->mCommand = previousCommand;
3527 sq->end();
3528 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3529 }
3530
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 return reconfig;
3532}
3533
3534status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3535{
3536 const size_t SIZE = 256;
3537 char buffer[SIZE];
3538 String8 result;
3539
3540 PlaybackThread::dumpInternals(fd, args);
3541
3542 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3543 result.append(buffer);
3544 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003545
3546 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3547 FastMixerDumpState copy = mFastMixerDumpState;
3548 copy.dump(fd);
3549
Glenn Kasten39993082012-05-31 13:40:27 -07003550#ifdef STATE_QUEUE_DUMP
3551 // Similar for state queue
3552 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3553 observerCopy.dump(fd);
3554 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3555 mutatorCopy.dump(fd);
3556#endif
3557
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003558 // Write the tee output to a .wav file
3559 NBAIO_Source *teeSource = mTeeSource.get();
3560 if (teeSource != NULL) {
3561 char teePath[64];
3562 struct timeval tv;
3563 gettimeofday(&tv, NULL);
3564 struct tm tm;
3565 localtime_r(&tv.tv_sec, &tm);
3566 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3567 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3568 if (teeFd >= 0) {
3569 char wavHeader[44];
3570 memcpy(wavHeader,
3571 "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",
3572 sizeof(wavHeader));
3573 NBAIO_Format format = teeSource->format();
3574 unsigned channelCount = Format_channelCount(format);
3575 ALOG_ASSERT(channelCount <= FCC_2);
3576 unsigned sampleRate = Format_sampleRate(format);
3577 wavHeader[22] = channelCount; // number of channels
3578 wavHeader[24] = sampleRate; // sample rate
3579 wavHeader[25] = sampleRate >> 8;
3580 wavHeader[32] = channelCount * 2; // block alignment
3581 write(teeFd, wavHeader, sizeof(wavHeader));
3582 size_t total = 0;
3583 bool firstRead = true;
3584 for (;;) {
3585#define TEE_SINK_READ 1024
3586 short buffer[TEE_SINK_READ * FCC_2];
3587 size_t count = TEE_SINK_READ;
3588 ssize_t actual = teeSource->read(buffer, count);
3589 bool wasFirstRead = firstRead;
3590 firstRead = false;
3591 if (actual <= 0) {
3592 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3593 continue;
3594 }
3595 break;
3596 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003597 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003598 write(teeFd, buffer, actual * channelCount * sizeof(short));
3599 total += actual;
3600 }
3601 lseek(teeFd, (off_t) 4, SEEK_SET);
3602 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3603 write(teeFd, &temp, sizeof(temp));
3604 lseek(teeFd, (off_t) 40, SEEK_SET);
3605 temp = total * channelCount * sizeof(short);
3606 write(teeFd, &temp, sizeof(temp));
3607 close(teeFd);
3608 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3609 } else {
3610 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3611 }
3612 }
3613
Glenn Kastenc15d6652012-05-30 14:52:57 -07003614 if (mAudioWatchdog != 0) {
3615 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3616 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3617 wdCopy.dump(fd);
3618 }
3619
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 return NO_ERROR;
3621}
3622
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003623uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624{
Glenn Kasten58912562012-04-03 10:45:00 -07003625 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626}
3627
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003628uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003629{
Glenn Kasten58912562012-04-03 10:45:00 -07003630 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003631}
3632
Glenn Kasten66fcab92012-02-24 14:59:21 -08003633void AudioFlinger::MixerThread::cacheParameters_l()
3634{
3635 PlaybackThread::cacheParameters_l();
3636
3637 // FIXME: Relaxed timing because of a certain device that can't meet latency
3638 // Should be reduced to 2x after the vendor fixes the driver issue
3639 // increase threshold again due to low power audio mode. The way this warning
3640 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003641 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003642}
3643
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003645AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3646 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003647 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003648 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650}
3651
3652AudioFlinger::DirectOutputThread::~DirectOutputThread()
3653{
3654}
3655
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003656AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3657 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003658)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003660 sp<Track> trackToRemove;
3661
Glenn Kastenfec279f2012-03-08 07:47:15 -08003662 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 // find out which tracks need to be processed
3665 if (mActiveTracks.size() != 0) {
3666 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003667 // The track died recently
3668 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669
Glenn Kasten952eeb22012-03-06 11:30:57 -08003670 Track* const track = t.get();
3671 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672
Glenn Kasten952eeb22012-03-06 11:30:57 -08003673 // The first time a track is added we wait
3674 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003675 uint32_t minFrames;
3676 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3677 minFrames = mNormalFrameCount;
3678 } else {
3679 minFrames = 1;
3680 }
3681 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003682 !track->isPaused() && !track->isTerminated())
3683 {
3684 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 if (track->mFillingUpStatus == Track::FS_FILLED) {
3687 track->mFillingUpStatus = Track::FS_ACTIVE;
3688 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 if (track->mState == TrackBase::RESUMING) {
3690 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 // compute volume for this track
3695 float left, right;
3696 if (track->isMuted() || mMasterMute || track->isPausing() ||
3697 mStreamTypes[track->streamType()].mute) {
3698 left = right = 0;
3699 if (track->isPausing()) {
3700 track->setPaused();
3701 }
3702 } else {
3703 float typeVolume = mStreamTypes[track->streamType()].volume;
3704 float v = mMasterVolume * typeVolume;
3705 uint32_t vlr = cblk->getVolumeLR();
3706 float v_clamped = v * (vlr & 0xFFFF);
3707 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3708 left = v_clamped/MAX_GAIN;
3709 v_clamped = v * (vlr >> 16);
3710 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3711 right = v_clamped/MAX_GAIN;
3712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 if (left != mLeftVolFloat || right != mRightVolFloat) {
3715 mLeftVolFloat = left;
3716 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717
Glenn Kasten952eeb22012-03-06 11:30:57 -08003718 // Convert volumes from float to 8.24
3719 uint32_t vl = (uint32_t)(left * (1 << 24));
3720 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 // Delegate volume control to effect in track effect chain if needed
3723 // only one effect chain can be present on DirectOutputThread, so if
3724 // there is one, the track is connected to it
3725 if (!mEffectChains.isEmpty()) {
3726 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003727 mEffectChains[0]->setVolume_l(&vl, &vr);
3728 left = (float)vl / (1 << 24);
3729 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003731 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003732 }
3733
3734 // reset retry count
3735 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003736 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003737 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003738 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003739 // clear effect chain input buffer if an active track underruns to avoid sending
3740 // previous audio buffer again to effects
3741 if (!mEffectChains.isEmpty()) {
3742 mEffectChains[0]->clearInputBuffer();
3743 }
3744
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003746 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3747 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 // We have consumed all the buffers of this track.
3749 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003750 // TODO: implement behavior for compressed audio
3751 size_t audioHALFrames =
3752 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3753 size_t framesWritten =
3754 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3755 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003756 if (track->isStopped()) {
3757 track->reset();
3758 }
Eric Laurenta011e352012-03-29 15:51:43 -07003759 trackToRemove = track;
3760 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003761 } else {
3762 // No buffers for this track. Give it a few chances to
3763 // fill a buffer, then remove it from active list.
3764 if (--(track->mRetryCount) <= 0) {
3765 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3766 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003768 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 }
3770 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003771 }
3772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003774 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 // remove all the tracks that need to be...
3776 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003777 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 mActiveTracks.remove(trackToRemove);
3779 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003780 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 trackToRemove->sessionId());
3782 mEffectChains[0]->decActiveTrackCnt();
3783 }
3784 if (trackToRemove->isTerminated()) {
3785 removeTrack_l(trackToRemove);
3786 }
3787 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788
Glenn Kastenfec279f2012-03-08 07:47:15 -08003789 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003790}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791
Glenn Kasten000f0e32012-03-01 17:10:56 -08003792void AudioFlinger::DirectOutputThread::threadLoop_mix()
3793{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 AudioBufferProvider::Buffer buffer;
3795 size_t frameCount = mFrameCount;
3796 int8_t *curBuf = (int8_t *)mMixBuffer;
3797 // output audio to hardware
3798 while (frameCount) {
3799 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003800 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003801 if (CC_UNLIKELY(buffer.raw == NULL)) {
3802 memset(curBuf, 0, frameCount * mFrameSize);
3803 break;
3804 }
3805 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3806 frameCount -= buffer.frameCount;
3807 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003808 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003809 }
3810 sleepTime = 0;
3811 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003812 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003813
Glenn Kasten000f0e32012-03-01 17:10:56 -08003814}
3815
3816void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3817{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003819 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 sleepTime = activeSleepTime;
3821 } else {
3822 sleepTime = idleSleepTime;
3823 }
3824 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003825 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 sleepTime = 0;
3827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828}
3829
3830// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003831int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832{
3833 return 0;
3834}
3835
3836// deleteTrackName_l() must be called with ThreadBase::mLock held
3837void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3838{
3839}
3840
3841// checkForNewParameters_l() must be called with ThreadBase::mLock held
3842bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3843{
3844 bool reconfig = false;
3845
3846 while (!mNewParameters.isEmpty()) {
3847 status_t status = NO_ERROR;
3848 String8 keyValuePair = mNewParameters[0];
3849 AudioParameter param = AudioParameter(keyValuePair);
3850 int value;
3851
3852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3853 // do not accept frame count changes if tracks are open as the track buffer
3854 // size depends on frame count and correct behavior would not be garantied
3855 // if frame count is changed after track creation
3856 if (!mTracks.isEmpty()) {
3857 status = INVALID_OPERATION;
3858 } else {
3859 reconfig = true;
3860 }
3861 }
3862 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003863 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003864 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003866 mOutput->stream->common.standby(&mOutput->stream->common);
3867 mStandby = true;
3868 mBytesWritten = 0;
3869 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003870 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003871 }
3872 if (status == NO_ERROR && reconfig) {
3873 readOutputParameters();
3874 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3875 }
3876 }
3877
3878 mNewParameters.removeAt(0);
3879
3880 mParamStatus = status;
3881 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003882 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3883 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003884 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 }
3886 return reconfig;
3887}
3888
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003889uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890{
3891 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003892 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003893 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 } else {
3895 time = 10000;
3896 }
3897 return time;
3898}
3899
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003900uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003901{
3902 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003903 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003904 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 } else {
3906 time = 10000;
3907 }
3908 return time;
3909}
3910
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003911uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003912{
3913 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003914 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003915 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3916 } else {
3917 time = 10000;
3918 }
3919 return time;
3920}
3921
Glenn Kasten66fcab92012-02-24 14:59:21 -08003922void AudioFlinger::DirectOutputThread::cacheParameters_l()
3923{
3924 PlaybackThread::cacheParameters_l();
3925
3926 // use shorter standby delay as on normal output to release
3927 // hardware resources as soon as possible
3928 standbyDelay = microseconds(activeSleepTime*2);
3929}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003930
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931// ----------------------------------------------------------------------------
3932
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003933AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003934 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003935 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3936 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 addOutputTrack(mainThread);
3939}
3940
3941AudioFlinger::DuplicatingThread::~DuplicatingThread()
3942{
3943 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3944 mOutputTracks[i]->destroy();
3945 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946}
3947
Glenn Kasten000f0e32012-03-01 17:10:56 -08003948void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003950 // mix buffers...
3951 if (outputsReady(outputTracks)) {
3952 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3953 } else {
3954 memset(mMixBuffer, 0, mixBufferSize);
3955 }
3956 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003957 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003958 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003959}
3960
3961void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3962{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003963 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003964 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003965 sleepTime = activeSleepTime;
3966 } else {
3967 sleepTime = idleSleepTime;
3968 }
3969 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003970 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3971 writeFrames = mNormalFrameCount;
3972 memset(mMixBuffer, 0, mixBufferSize);
3973 } else {
3974 // flush remaining overflow buffers in output tracks
3975 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003976 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003977 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003978 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003979}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980
Glenn Kasten000f0e32012-03-01 17:10:56 -08003981void AudioFlinger::DuplicatingThread::threadLoop_write()
3982{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003983 for (size_t i = 0; i < outputTracks.size(); i++) {
3984 outputTracks[i]->write(mMixBuffer, writeFrames);
3985 }
3986 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003987}
Glenn Kasten688a6402012-02-29 07:57:06 -08003988
Glenn Kasten000f0e32012-03-01 17:10:56 -08003989void AudioFlinger::DuplicatingThread::threadLoop_standby()
3990{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003991 // DuplicatingThread implements standby by stopping all tracks
3992 for (size_t i = 0; i < outputTracks.size(); i++) {
3993 outputTracks[i]->stop();
3994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995}
3996
Glenn Kastenfa26a852012-03-06 11:28:04 -08003997void AudioFlinger::DuplicatingThread::saveOutputTracks()
3998{
3999 outputTracks = mOutputTracks;
4000}
4001
4002void AudioFlinger::DuplicatingThread::clearOutputTracks()
4003{
4004 outputTracks.clear();
4005}
4006
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4008{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004009 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004010 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004011 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004012 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 this,
4014 mSampleRate,
4015 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004016 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 frameCount);
4018 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004019 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004021 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004022 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023 }
4024}
4025
4026void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4027{
4028 Mutex::Autolock _l(mLock);
4029 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004030 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 mOutputTracks[i]->destroy();
4032 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004033 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 return;
4035 }
4036 }
Steve Block3856b092011-10-20 11:56:00 +01004037 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038}
4039
Glenn Kasten438b0362012-03-06 11:24:48 -08004040// caller must hold mLock
4041void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042{
4043 mWaitTimeMs = UINT_MAX;
4044 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4045 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004046 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4048 if (waitTimeMs < mWaitTimeMs) {
4049 mWaitTimeMs = waitTimeMs;
4050 }
4051 }
4052 }
4053}
4054
4055
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004056bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057{
4058 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004059 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004061 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062 return false;
4063 }
4064 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4065 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004066 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 return false;
4068 }
4069 }
4070 return true;
4071}
4072
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004073uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074{
4075 return (mWaitTimeMs * 1000) / 2;
4076}
4077
Glenn Kasten66fcab92012-02-24 14:59:21 -08004078void AudioFlinger::DuplicatingThread::cacheParameters_l()
4079{
4080 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4081 updateWaitTime_l();
4082
4083 MixerThread::cacheParameters_l();
4084}
4085
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086// ----------------------------------------------------------------------------
4087
4088// TrackBase constructor must be called with AudioFlinger::mLock held
4089AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004090 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091 const sp<Client>& client,
4092 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004093 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004094 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 const sp<IMemory>& sharedBuffer,
4097 int sessionId)
4098 : RefBase(),
4099 mThread(thread),
4100 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004101 mCblk(NULL),
4102 // mBuffer
4103 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 mFrameCount(0),
4105 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004106 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004108 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004110 // mChannelCount
4111 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112{
Steve Block3856b092011-10-20 11:56:00 +01004113 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114
Steve Blockb8a80522011-12-20 16:23:08 +00004115 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004116 size_t size = sizeof(audio_track_cblk_t);
4117 uint8_t channelCount = popcount(channelMask);
4118 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4119 if (sharedBuffer == 0) {
4120 size += bufferSize;
4121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004123 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004124 mCblkMemory = client->heap()->allocate(size);
4125 if (mCblkMemory != 0) {
4126 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004127 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 new(mCblk) audio_track_cblk_t();
4129 // clear all buffers
4130 mCblk->frameCount = frameCount;
4131 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004132// uncomment the following lines to quickly test 32-bit wraparound
4133// mCblk->user = 0xffff0000;
4134// mCblk->server = 0xffff0000;
4135// mCblk->userBase = 0xffff0000;
4136// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004137 mChannelCount = channelCount;
4138 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 if (sharedBuffer == 0) {
4140 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4141 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4142 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004143 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144 mCblk->flags = CBLK_UNDERRUN_ON;
4145 } else {
4146 mBuffer = sharedBuffer->pointer();
4147 }
4148 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4149 }
4150 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004151 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 client->heap()->dump("AudioTrack");
4153 return;
4154 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004155 } else {
4156 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004157 // construct the shared structure in-place.
4158 new(mCblk) audio_track_cblk_t();
4159 // clear all buffers
4160 mCblk->frameCount = frameCount;
4161 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004162// uncomment the following lines to quickly test 32-bit wraparound
4163// mCblk->user = 0xffff0000;
4164// mCblk->server = 0xffff0000;
4165// mCblk->userBase = 0xffff0000;
4166// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004167 mChannelCount = channelCount;
4168 mChannelMask = channelMask;
4169 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4170 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4171 // Force underrun condition to avoid false underrun callback until first data is
4172 // written to buffer (other flags are cleared)
4173 mCblk->flags = CBLK_UNDERRUN_ON;
4174 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004175 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176}
4177
4178AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4179{
Glenn Kastena0d68332012-01-27 16:47:15 -08004180 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004181 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004182 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004183 } else {
4184 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 }
4186 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004187 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004188 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004189 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004191 // If the client's reference count drops to zero, the associated destructor
4192 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4193 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 mClient.clear();
4195 }
4196}
4197
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004198// AudioBufferProvider interface
4199// getNextBuffer() = 0;
4200// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4202{
Glenn Kastene0feee32011-12-13 11:53:26 -08004203 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004205 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004206 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 buffer->frameCount = 0;
4208}
4209
4210bool AudioFlinger::ThreadBase::TrackBase::step() {
4211 bool result;
4212 audio_track_cblk_t* cblk = this->cblk();
4213
4214 result = cblk->stepServer(mFrameCount);
4215 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004216 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004217 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 }
4219 return result;
4220}
4221
4222void AudioFlinger::ThreadBase::TrackBase::reset() {
4223 audio_track_cblk_t* cblk = this->cblk();
4224
4225 cblk->user = 0;
4226 cblk->server = 0;
4227 cblk->userBase = 0;
4228 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004229 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004230 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231}
4232
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4234 return (int)mCblk->sampleRate;
4235}
4236
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4238 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004239 size_t frameSize = cblk->frameSize;
4240 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4241 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242
4243 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004244 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4245 "TrackBase::getBuffer buffer out of range:\n"
4246 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4247 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004249 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250
4251 return bufferStart;
4252}
4253
Eric Laurenta011e352012-03-29 15:51:43 -07004254status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4255{
4256 mSyncEvents.add(event);
4257 return NO_ERROR;
4258}
4259
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260// ----------------------------------------------------------------------------
4261
4262// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4263AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004264 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004266 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004268 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004269 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 int frameCount,
4271 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004272 int sessionId,
4273 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004274 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004275 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004276 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004277 // mRetryCount initialized later when needed
4278 mSharedBuffer(sharedBuffer),
4279 mStreamType(streamType),
4280 mName(-1), // see note below
4281 mMainBuffer(thread->mixBuffer()),
4282 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004283 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004284 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004285 mFlags(flags),
4286 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004287 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004288 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289{
4290 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4292 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004293 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004294 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4295 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004296 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004297 if (mName < 0) {
4298 ALOGE("no more track names available");
4299 return;
4300 }
4301 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004302 if (flags & IAudioFlinger::TRACK_FAST) {
4303 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4304 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4305 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004306 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004307 // FIXME This is too eager. We allocate a fast track index before the
4308 // fast track becomes active. Since fast tracks are a scarce resource,
4309 // this means we are potentially denying other more important fast tracks from
4310 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004311 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004312 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004313 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004314 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004315 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004318 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319}
4320
4321AudioFlinger::PlaybackThread::Track::~Track()
4322{
Steve Block3856b092011-10-20 11:56:00 +01004323 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 sp<ThreadBase> thread = mThread.promote();
4325 if (thread != 0) {
4326 Mutex::Autolock _l(thread->mLock);
4327 mState = TERMINATED;
4328 }
4329}
4330
4331void AudioFlinger::PlaybackThread::Track::destroy()
4332{
4333 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4334 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004335 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 // we must acquire a strong reference on this Track before locking mLock
4337 // here so that the destructor is called only when exiting this function.
4338 // On the other hand, as long as Track::destroy() is only called by
4339 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4340 // this Track with its member mTrack.
4341 sp<Track> keep(this);
4342 { // scope for mLock
4343 sp<ThreadBase> thread = mThread.promote();
4344 if (thread != 0) {
4345 if (!isOutputTrack()) {
4346 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004347 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004348
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004349#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004350 // to track the speaker usage
4351 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004352#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 }
4354 AudioSystem::releaseOutput(thread->id());
4355 }
4356 Mutex::Autolock _l(thread->mLock);
4357 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4358 playbackThread->destroyTrack_l(this);
4359 }
4360 }
4361}
4362
Glenn Kasten288ed212012-04-25 17:52:27 -07004363/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4364{
Glenn Kastene213c862012-04-25 13:46:15 -07004365 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 -07004366 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004367}
4368
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4370{
Glenn Kasten83d86532012-01-17 14:39:34 -08004371 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004372 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004373 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004374 } else {
4375 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4376 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004377 track_state state = mState;
4378 char stateChar;
4379 switch (state) {
4380 case IDLE:
4381 stateChar = 'I';
4382 break;
4383 case TERMINATED:
4384 stateChar = 'T';
4385 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004386 case STOPPING_1:
4387 stateChar = 's';
4388 break;
4389 case STOPPING_2:
4390 stateChar = '5';
4391 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004392 case STOPPED:
4393 stateChar = 'S';
4394 break;
4395 case RESUMING:
4396 stateChar = 'R';
4397 break;
4398 case ACTIVE:
4399 stateChar = 'A';
4400 break;
4401 case PAUSING:
4402 stateChar = 'p';
4403 break;
4404 case PAUSED:
4405 stateChar = 'P';
4406 break;
Eric Laurent29864602012-05-08 18:57:51 -07004407 case FLUSHED:
4408 stateChar = 'F';
4409 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004410 default:
4411 stateChar = '?';
4412 break;
4413 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004414 char nowInUnderrun;
4415 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4416 case UNDERRUN_FULL:
4417 nowInUnderrun = ' ';
4418 break;
4419 case UNDERRUN_PARTIAL:
4420 nowInUnderrun = '<';
4421 break;
4422 case UNDERRUN_EMPTY:
4423 nowInUnderrun = '*';
4424 break;
4425 default:
4426 nowInUnderrun = '?';
4427 break;
4428 }
Glenn Kastene213c862012-04-25 13:46:15 -07004429 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4430 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004431 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 mStreamType,
4433 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004434 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 mSessionId,
4436 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004437 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004438 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 mMute,
4440 mFillingUpStatus,
4441 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004442 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4443 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 mCblk->server,
4445 mCblk->user,
4446 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004447 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004448 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004449 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004450 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451}
4452
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004453// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004454status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004455 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004456{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004457 audio_track_cblk_t* cblk = this->cblk();
4458 uint32_t framesReady;
4459 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004461 // Check if last stepServer failed, try to step now
4462 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004463 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4464 // Since the fast mixer is higher priority than client callback thread,
4465 // it does not result in priority inversion for client.
4466 // But a non-blocking solution would be preferable to avoid
4467 // fast mixer being unable to tryLock(), and
4468 // to avoid the extra context switches if the client wakes up,
4469 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004470 if (!step()) goto getNextBuffer_exit;
4471 ALOGV("stepServer recovered");
4472 mStepServerFailed = false;
4473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474
Glenn Kasten288ed212012-04-25 17:52:27 -07004475 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004476 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004478 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 uint32_t s = cblk->server;
4480 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4481
4482 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4483 if (framesReq > framesReady) {
4484 framesReq = framesReady;
4485 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004486 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 framesReq = bufferEnd - s;
4488 }
4489
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004490 buffer->raw = getBuffer(s, framesReq);
4491 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004493 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496
4497getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004498 buffer->raw = NULL;
4499 buffer->frameCount = 0;
4500 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4501 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502}
4503
Glenn Kasten288ed212012-04-25 17:52:27 -07004504// Note that framesReady() takes a mutex on the control block using tryLock().
4505// This could result in priority inversion if framesReady() is called by the normal mixer,
4506// as the normal mixer thread runs at lower
4507// priority than the client's callback thread: there is a short window within framesReady()
4508// during which the normal mixer could be preempted, and the client callback would block.
4509// Another problem can occur if framesReady() is called by the fast mixer:
4510// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4511// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4512size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004513 return mCblk->framesReady();
4514}
4515
Glenn Kasten288ed212012-04-25 17:52:27 -07004516// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004518 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519
John Grossman4ff14ba2012-02-08 16:37:41 -08004520 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4522 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004523 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 return true;
4525 }
4526 return false;
4527}
4528
Glenn Kasten3acbd052012-02-28 10:39:56 -08004529status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004530 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531{
4532 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004533 ALOGV("start(%d), calling pid %d session %d",
4534 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004535
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 sp<ThreadBase> thread = mThread.promote();
4537 if (thread != 0) {
4538 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004539 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 // here the track could be either new, or restarted
4541 // in both cases "unstop" the track
4542 if (mState == PAUSED) {
4543 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004544 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 } else {
4546 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004547 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 }
4549
4550 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4551 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004552 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004554
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004555#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004556 // to track the speaker usage
4557 if (status == NO_ERROR) {
4558 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4559 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004560#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 }
4562 if (status == NO_ERROR) {
4563 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4564 playbackThread->addTrack_l(this);
4565 } else {
4566 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004567 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
4569 } else {
4570 status = BAD_VALUE;
4571 }
4572 return status;
4573}
4574
4575void AudioFlinger::PlaybackThread::Track::stop()
4576{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004577 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 sp<ThreadBase> thread = mThread.promote();
4579 if (thread != 0) {
4580 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004581 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004582 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 // If the track is not active (PAUSED and buffers full), flush buffers
4584 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4585 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4586 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004587 mState = STOPPED;
4588 } else if (!isFastTrack()) {
4589 mState = STOPPED;
4590 } else {
4591 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4592 // and then to STOPPED and reset() when presentation is complete
4593 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004595 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 }
4597 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4598 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004599 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004601
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004602#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004603 // to track the speaker usage
4604 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004605#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 }
4607 }
4608}
4609
4610void AudioFlinger::PlaybackThread::Track::pause()
4611{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004612 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 sp<ThreadBase> thread = mThread.promote();
4614 if (thread != 0) {
4615 Mutex::Autolock _l(thread->mLock);
4616 if (mState == ACTIVE || mState == RESUMING) {
4617 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004618 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 if (!isOutputTrack()) {
4620 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004621 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004623
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004624#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004625 // to track the speaker usage
4626 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004627#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 }
4629 }
4630 }
4631}
4632
4633void AudioFlinger::PlaybackThread::Track::flush()
4634{
Steve Block3856b092011-10-20 11:56:00 +01004635 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 sp<ThreadBase> thread = mThread.promote();
4637 if (thread != 0) {
4638 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004639 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4640 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 return;
4642 }
4643 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004644 // FLUSHED state
4645 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004646 // do not reset the track if it is still in the process of being stopped or paused.
4647 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004648 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004649 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004650 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4651 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4652 reset();
4653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 }
4655}
4656
4657void AudioFlinger::PlaybackThread::Track::reset()
4658{
4659 // Do not reset twice to avoid discarding data written just after a flush and before
4660 // the audioflinger thread detects the track is stopped.
4661 if (!mResetDone) {
4662 TrackBase::reset();
4663 // Force underrun condition to avoid false underrun callback until first data is
4664 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004665 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4666 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 mFillingUpStatus = FS_FILLING;
4668 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004669 if (mState == FLUSHED) {
4670 mState = IDLE;
4671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672 }
4673}
4674
4675void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4676{
4677 mMute = muted;
4678}
4679
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4681{
4682 status_t status = DEAD_OBJECT;
4683 sp<ThreadBase> thread = mThread.promote();
4684 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004685 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004686 sp<AudioFlinger> af = mClient->audioFlinger();
4687
4688 Mutex::Autolock _l(af->mLock);
4689
4690 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004691
Eric Laurent109347d2012-07-02 12:31:03 -07004692 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004693 Mutex::Autolock _dl(playbackThread->mLock);
4694 Mutex::Autolock _sl(srcThread->mLock);
4695 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4696 if (chain == 0) {
4697 return INVALID_OPERATION;
4698 }
4699
4700 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4701 if (effect == 0) {
4702 return INVALID_OPERATION;
4703 }
4704 srcThread->removeEffect_l(effect);
4705 playbackThread->addEffect_l(effect);
4706 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4707 if (effect->state() == EffectModule::ACTIVE ||
4708 effect->state() == EffectModule::STOPPING) {
4709 effect->start();
4710 }
4711
4712 sp<EffectChain> dstChain = effect->chain().promote();
4713 if (dstChain == 0) {
4714 srcThread->addEffect_l(effect);
4715 return INVALID_OPERATION;
4716 }
4717 AudioSystem::unregisterEffect(effect->id());
4718 AudioSystem::registerEffect(&effect->desc(),
4719 srcThread->id(),
4720 dstChain->strategy(),
4721 AUDIO_SESSION_OUTPUT_MIX,
4722 effect->id());
4723 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004724 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004725 }
4726 return status;
4727}
4728
4729void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4730{
4731 mAuxEffectId = EffectId;
4732 mAuxBuffer = buffer;
4733}
4734
Eric Laurenta011e352012-03-29 15:51:43 -07004735bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4736 size_t audioHalFrames)
4737{
4738 // a track is considered presented when the total number of frames written to audio HAL
4739 // corresponds to the number of frames written when presentationComplete() is called for the
4740 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4741 if (mPresentationCompleteFrames == 0) {
4742 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4743 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4744 mPresentationCompleteFrames, audioHalFrames);
4745 }
4746 if (framesWritten >= mPresentationCompleteFrames) {
4747 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4748 mSessionId, framesWritten);
4749 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004750 return true;
4751 }
4752 return false;
4753}
4754
4755void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4756{
4757 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4758 if (mSyncEvents[i]->type() == type) {
4759 mSyncEvents[i]->trigger();
4760 mSyncEvents.removeAt(i);
4761 i--;
4762 }
4763 }
4764}
4765
Glenn Kasten58912562012-04-03 10:45:00 -07004766// implement VolumeBufferProvider interface
4767
4768uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4769{
4770 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4771 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4772 uint32_t vlr = mCblk->getVolumeLR();
4773 uint32_t vl = vlr & 0xFFFF;
4774 uint32_t vr = vlr >> 16;
4775 // track volumes come from shared memory, so can't be trusted and must be clamped
4776 if (vl > MAX_GAIN_INT) {
4777 vl = MAX_GAIN_INT;
4778 }
4779 if (vr > MAX_GAIN_INT) {
4780 vr = MAX_GAIN_INT;
4781 }
4782 // now apply the cached master volume and stream type volume;
4783 // this is trusted but lacks any synchronization or barrier so may be stale
4784 float v = mCachedVolume;
4785 vl *= v;
4786 vr *= v;
4787 // re-combine into U4.16
4788 vlr = (vr << 16) | (vl & 0xFFFF);
4789 // FIXME look at mute, pause, and stop flags
4790 return vlr;
4791}
Eric Laurenta011e352012-03-29 15:51:43 -07004792
Eric Laurent29864602012-05-08 18:57:51 -07004793status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4794{
4795 if (mState == TERMINATED || mState == PAUSED ||
4796 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4797 (mState == STOPPED)))) {
4798 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4799 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4800 event->cancel();
4801 return INVALID_OPERATION;
4802 }
4803 TrackBase::setSyncEvent(event);
4804 return NO_ERROR;
4805}
4806
John Grossman4ff14ba2012-02-08 16:37:41 -08004807// timed audio tracks
4808
4809sp<AudioFlinger::PlaybackThread::TimedTrack>
4810AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004811 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004812 const sp<Client>& client,
4813 audio_stream_type_t streamType,
4814 uint32_t sampleRate,
4815 audio_format_t format,
4816 uint32_t channelMask,
4817 int frameCount,
4818 const sp<IMemory>& sharedBuffer,
4819 int sessionId) {
4820 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004821 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004822
Glenn Kastena0356762012-03-19 10:38:51 -07004823 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004824 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4825 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004826}
4827
4828AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004829 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004830 const sp<Client>& client,
4831 audio_stream_type_t streamType,
4832 uint32_t sampleRate,
4833 audio_format_t format,
4834 uint32_t channelMask,
4835 int frameCount,
4836 const sp<IMemory>& sharedBuffer,
4837 int sessionId)
4838 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004839 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004840 mQueueHeadInFlight(false),
4841 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004842 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004843 mTimedSilenceBuffer(NULL),
4844 mTimedSilenceBufferSize(0),
4845 mTimedAudioOutputOnTime(false),
4846 mMediaTimeTransformValid(false)
4847{
4848 LocalClock lc;
4849 mLocalTimeFreq = lc.getLocalFreq();
4850
4851 mLocalTimeToSampleTransform.a_zero = 0;
4852 mLocalTimeToSampleTransform.b_zero = 0;
4853 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4854 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4855 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4856 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004857
4858 mMediaTimeToSampleTransform.a_zero = 0;
4859 mMediaTimeToSampleTransform.b_zero = 0;
4860 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4861 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4862 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4863 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004864}
4865
4866AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4867 mClient->releaseTimedTrack();
4868 delete [] mTimedSilenceBuffer;
4869}
4870
4871status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4872 size_t size, sp<IMemory>* buffer) {
4873
4874 Mutex::Autolock _l(mTimedBufferQueueLock);
4875
4876 trimTimedBufferQueue_l();
4877
4878 // lazily initialize the shared memory heap for timed buffers
4879 if (mTimedMemoryDealer == NULL) {
4880 const int kTimedBufferHeapSize = 512 << 10;
4881
4882 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4883 "AudioFlingerTimed");
4884 if (mTimedMemoryDealer == NULL)
4885 return NO_MEMORY;
4886 }
4887
4888 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4889 if (newBuffer == NULL) {
4890 newBuffer = mTimedMemoryDealer->allocate(size);
4891 if (newBuffer == NULL)
4892 return NO_MEMORY;
4893 }
4894
4895 *buffer = newBuffer;
4896 return NO_ERROR;
4897}
4898
4899// caller must hold mTimedBufferQueueLock
4900void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4901 int64_t mediaTimeNow;
4902 {
4903 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4904 if (!mMediaTimeTransformValid)
4905 return;
4906
4907 int64_t targetTimeNow;
4908 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4909 ? mCCHelper.getCommonTime(&targetTimeNow)
4910 : mCCHelper.getLocalTime(&targetTimeNow);
4911
4912 if (OK != res)
4913 return;
4914
4915 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4916 &mediaTimeNow)) {
4917 return;
4918 }
4919 }
4920
John Grossman1c345192012-03-27 14:00:17 -07004921 size_t trimEnd;
4922 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004923 int64_t bufEnd;
4924
John Grossmanc95cfbb2012-04-12 11:53:11 -07004925 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4926 // We have a next buffer. Just use its PTS as the PTS of the frame
4927 // following the last frame in this buffer. If the stream is sparse
4928 // (ie, there are deliberate gaps left in the stream which should be
4929 // filled with silence by the TimedAudioTrack), then this can result
4930 // in one extra buffer being left un-trimmed when it could have
4931 // been. In general, this is not typical, and we would rather
4932 // optimized away the TS calculation below for the more common case
4933 // where PTSes are contiguous.
4934 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4935 } else {
4936 // We have no next buffer. Compute the PTS of the frame following
4937 // the last frame in this buffer by computing the duration of of
4938 // this frame in media time units and adding it to the PTS of the
4939 // buffer.
4940 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4941 / mCblk->frameSize;
4942
4943 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4944 &bufEnd)) {
4945 ALOGE("Failed to convert frame count of %lld to media time"
4946 " duration" " (scale factor %d/%u) in %s",
4947 frameCount,
4948 mMediaTimeToSampleTransform.a_to_b_numer,
4949 mMediaTimeToSampleTransform.a_to_b_denom,
4950 __PRETTY_FUNCTION__);
4951 break;
4952 }
4953 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004954 }
John Grossman9fbdee12012-03-26 17:51:46 -07004955
4956 if (bufEnd > mediaTimeNow)
4957 break;
4958
4959 // Is the buffer we want to use in the middle of a mix operation right
4960 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4961 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004962 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004963 mTrimQueueHeadOnRelease = true;
4964 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004965 }
4966
John Grossman9fbdee12012-03-26 17:51:46 -07004967 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004968 if (trimStart < trimEnd) {
4969 // Update the bookkeeping for framesReady()
4970 for (size_t i = trimStart; i < trimEnd; ++i) {
4971 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4972 }
4973
4974 // Now actually remove the buffers from the queue.
4975 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 }
4977}
4978
John Grossman1c345192012-03-27 14:00:17 -07004979void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4980 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004981 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4982 "%s called (reason \"%s\"), but timed buffer queue has no"
4983 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004984
4985 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4986 mTimedBufferQueue.removeAt(0);
4987}
4988
4989void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4990 const TimedBuffer& buf,
4991 const char* logTag) {
4992 uint32_t bufBytes = buf.buffer()->size();
4993 uint32_t consumedAlready = buf.position();
4994
Eric Laurentb388e532012-04-14 13:32:48 -07004995 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004996 "Bad bookkeeping while updating frames pending. Timed buffer is"
4997 " only %u bytes long, but claims to have consumed %u"
4998 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004999 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005000
5001 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005002 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5003 "Bad bookkeeping while updating frames pending. Should have at"
5004 " least %u queued frames, but we think we have only %u. (update"
5005 " reason: \"%s\")",
5006 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005007
5008 mFramesPendingInQueue -= bufFrames;
5009}
5010
John Grossman4ff14ba2012-02-08 16:37:41 -08005011status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5012 const sp<IMemory>& buffer, int64_t pts) {
5013
5014 {
5015 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5016 if (!mMediaTimeTransformValid)
5017 return INVALID_OPERATION;
5018 }
5019
5020 Mutex::Autolock _l(mTimedBufferQueueLock);
5021
John Grossman1c345192012-03-27 14:00:17 -07005022 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5023 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005024 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5025
5026 return NO_ERROR;
5027}
5028
5029status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5030 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5031
John Grossman1c345192012-03-27 14:00:17 -07005032 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5033 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5034 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005035
5036 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5037 target == TimedAudioTrack::COMMON_TIME)) {
5038 return BAD_VALUE;
5039 }
5040
5041 Mutex::Autolock lock(mMediaTimeTransformLock);
5042 mMediaTimeTransform = xform;
5043 mMediaTimeTransformTarget = target;
5044 mMediaTimeTransformValid = true;
5045
5046 return NO_ERROR;
5047}
5048
5049#define min(a, b) ((a) < (b) ? (a) : (b))
5050
5051// implementation of getNextBuffer for tracks whose buffers have timestamps
5052status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5053 AudioBufferProvider::Buffer* buffer, int64_t pts)
5054{
5055 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005056 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005057 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005058 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005059 return INVALID_OPERATION;
5060 }
5061
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 Mutex::Autolock _l(mTimedBufferQueueLock);
5063
John Grossman9fbdee12012-03-26 17:51:46 -07005064 ALOG_ASSERT(!mQueueHeadInFlight,
5065 "getNextBuffer called without releaseBuffer!");
5066
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 while (true) {
5068
5069 // if we have no timed buffers, then fail
5070 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005071 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005072 buffer->frameCount = 0;
5073 return NOT_ENOUGH_DATA;
5074 }
5075
5076 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5077
5078 // calculate the PTS of the head of the timed buffer queue expressed in
5079 // local time
5080 int64_t headLocalPTS;
5081 {
5082 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5083
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005084 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005085
5086 if (mMediaTimeTransform.a_to_b_denom == 0) {
5087 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005088 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005089 return NO_ERROR;
5090 }
5091
5092 int64_t transformedPTS;
5093 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5094 &transformedPTS)) {
5095 // the transform failed. this shouldn't happen, but if it does
5096 // then just drop this buffer
5097 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005098 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005099 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005100 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 return NO_ERROR;
5102 }
5103
5104 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5105 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5106 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005107 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005108 buffer->frameCount = 0;
5109 return INVALID_OPERATION;
5110 }
5111 } else {
5112 headLocalPTS = transformedPTS;
5113 }
5114 }
5115
5116 // adjust the head buffer's PTS to reflect the portion of the head buffer
5117 // that has already been consumed
5118 int64_t effectivePTS = headLocalPTS +
5119 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5120
5121 // Calculate the delta in samples between the head of the input buffer
5122 // queue and the start of the next output buffer that will be written.
5123 // If the transformation fails because of over or underflow, it means
5124 // that the sample's position in the output stream is so far out of
5125 // whack that it should just be dropped.
5126 int64_t sampleDelta;
5127 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5128 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005129 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5130 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005131 continue;
5132 }
5133 if (!mLocalTimeToSampleTransform.doForwardTransform(
5134 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005135 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005136 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005137 continue;
5138 }
5139
John Grossman1c345192012-03-27 14:00:17 -07005140 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5141 " sampleDelta=[%d.%08x]",
5142 head.pts(), head.position(), pts,
5143 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5144 + (sampleDelta >> 32)),
5145 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005146
5147 // if the delta between the ideal placement for the next input sample and
5148 // the current output position is within this threshold, then we will
5149 // concatenate the next input samples to the previous output
5150 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005151 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005152
5153 // if this is the first buffer of audio that we're emitting from this track
5154 // then it should be almost exactly on time.
5155 const int64_t kSampleStartupThreshold = 1LL << 32;
5156
5157 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005158 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005159 // the next input is close enough to being on time, so concatenate it
5160 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005161 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005162
John Grossman1c345192012-03-27 14:00:17 -07005163 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5164 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005166 }
5167
5168 // Looks like our output is not on time. Reset our on timed status.
5169 // Next time we mix samples from our input queue, then should be within
5170 // the StartupThreshold.
5171 mTimedAudioOutputOnTime = false;
5172 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005173 // the gap between the current output position and the proper start of
5174 // the next input sample is too big, so fill it with silence
5175 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5176
John Grossman9fbdee12012-03-26 17:51:46 -07005177 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005178 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5179 return NO_ERROR;
5180 } else {
5181 // the next input sample is late
5182 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5183 size_t onTimeSamplePosition =
5184 head.position() + lateFrames * mCblk->frameSize;
5185
5186 if (onTimeSamplePosition > head.buffer()->size()) {
5187 // all the remaining samples in the head are too late, so
5188 // drop it and move on
5189 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005190 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005191 continue;
5192 } else {
5193 // skip over the late samples
5194 head.setPosition(onTimeSamplePosition);
5195
5196 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005197 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005198
5199 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5200 return NO_ERROR;
5201 }
5202 }
5203 }
5204}
5205
5206// Yield samples from the timed buffer queue head up to the given output
5207// buffer's capacity.
5208//
5209// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005210void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005211 AudioBufferProvider::Buffer* buffer) {
5212
5213 const TimedBuffer& head = mTimedBufferQueue[0];
5214
5215 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5216 head.position());
5217
5218 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5219 mCblk->frameSize);
5220 size_t framesRequested = buffer->frameCount;
5221 buffer->frameCount = min(framesLeftInHead, framesRequested);
5222
John Grossman9fbdee12012-03-26 17:51:46 -07005223 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005224 mTimedAudioOutputOnTime = true;
5225}
5226
5227// Yield samples of silence up to the given output buffer's capacity
5228//
5229// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005230void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005231 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5232
5233 // lazily allocate a buffer filled with silence
5234 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5235 delete [] mTimedSilenceBuffer;
5236 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5237 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5238 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5239 }
5240
5241 buffer->raw = mTimedSilenceBuffer;
5242 size_t framesRequested = buffer->frameCount;
5243 buffer->frameCount = min(numFrames, framesRequested);
5244
5245 mTimedAudioOutputOnTime = false;
5246}
5247
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005248// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005249void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5250 AudioBufferProvider::Buffer* buffer) {
5251
5252 Mutex::Autolock _l(mTimedBufferQueueLock);
5253
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005254 // If the buffer which was just released is part of the buffer at the head
5255 // of the queue, be sure to update the amt of the buffer which has been
5256 // consumed. If the buffer being returned is not part of the head of the
5257 // queue, its either because the buffer is part of the silence buffer, or
5258 // because the head of the timed queue was trimmed after the mixer called
5259 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005260 if (buffer->raw == mTimedSilenceBuffer) {
5261 ALOG_ASSERT(!mQueueHeadInFlight,
5262 "Queue head in flight during release of silence buffer!");
5263 goto done;
5264 }
5265
5266 ALOG_ASSERT(mQueueHeadInFlight,
5267 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5268 " head in flight.");
5269
5270 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005271 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005272
5273 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005274 void* end = reinterpret_cast<void*>(
5275 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5276 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005277
John Grossman9fbdee12012-03-26 17:51:46 -07005278 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5279 "released buffer not within the head of the timed buffer"
5280 " queue; qHead = [%p, %p], released buffer = %p",
5281 start, end, buffer->raw);
5282
5283 head.setPosition(head.position() +
5284 (buffer->frameCount * mCblk->frameSize));
5285 mQueueHeadInFlight = false;
5286
John Grossman1c345192012-03-27 14:00:17 -07005287 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5288 "Bad bookkeeping during releaseBuffer! Should have at"
5289 " least %u queued frames, but we think we have only %u",
5290 buffer->frameCount, mFramesPendingInQueue);
5291
5292 mFramesPendingInQueue -= buffer->frameCount;
5293
John Grossman9fbdee12012-03-26 17:51:46 -07005294 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5295 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005296 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005297 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005298 }
John Grossman9fbdee12012-03-26 17:51:46 -07005299 } else {
5300 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5301 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005302 }
5303
John Grossman9fbdee12012-03-26 17:51:46 -07005304done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005305 buffer->raw = 0;
5306 buffer->frameCount = 0;
5307}
5308
Glenn Kasten288ed212012-04-25 17:52:27 -07005309size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005310 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005311 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005312}
5313
5314AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5315 : mPTS(0), mPosition(0) {}
5316
5317AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5318 const sp<IMemory>& buffer, int64_t pts)
5319 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5320
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321// ----------------------------------------------------------------------------
5322
5323// RecordTrack constructor must be called with AudioFlinger::mLock held
5324AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005325 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 const sp<Client>& client,
5327 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005328 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005329 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 int sessionId)
5332 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005333 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 mOverflow(false)
5335{
5336 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005337 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5338 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5339 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5340 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5341 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5342 } else {
5343 mCblk->frameSize = sizeof(int8_t);
5344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 }
5346}
5347
5348AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5349{
5350 sp<ThreadBase> thread = mThread.promote();
5351 if (thread != 0) {
5352 AudioSystem::releaseInput(thread->id());
5353 }
5354}
5355
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005356// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005357status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358{
5359 audio_track_cblk_t* cblk = this->cblk();
5360 uint32_t framesAvail;
5361 uint32_t framesReq = buffer->frameCount;
5362
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005363 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005364 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005366 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005367 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 }
5369
5370 framesAvail = cblk->framesAvailable_l();
5371
Glenn Kastenf6b16782011-12-15 09:51:17 -08005372 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 uint32_t s = cblk->server;
5374 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5375
5376 if (framesReq > framesAvail) {
5377 framesReq = framesAvail;
5378 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005379 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 framesReq = bufferEnd - s;
5381 }
5382
5383 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005384 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385
5386 buffer->frameCount = framesReq;
5387 return NO_ERROR;
5388 }
5389
5390getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005391 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 buffer->frameCount = 0;
5393 return NOT_ENOUGH_DATA;
5394}
5395
Glenn Kasten3acbd052012-02-28 10:39:56 -08005396status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005397 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398{
5399 sp<ThreadBase> thread = mThread.promote();
5400 if (thread != 0) {
5401 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005402 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 } else {
5404 return BAD_VALUE;
5405 }
5406}
5407
5408void AudioFlinger::RecordThread::RecordTrack::stop()
5409{
5410 sp<ThreadBase> thread = mThread.promote();
5411 if (thread != 0) {
5412 RecordThread *recordThread = (RecordThread *)thread.get();
5413 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005414 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005415 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005416 // read from buffer
5417 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 }
5419}
5420
5421void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5422{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005423 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005424 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005426 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 mSessionId,
5428 mFrameCount,
5429 mState,
5430 mCblk->sampleRate,
5431 mCblk->server,
5432 mCblk->user);
5433}
5434
5435
5436// ----------------------------------------------------------------------------
5437
5438AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005439 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 DuplicatingThread *sourceThread,
5441 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005442 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005443 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005445 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5446 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 mActive(false), mSourceThread(sourceThread)
5448{
5449
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 if (mCblk != NULL) {
5451 mCblk->flags |= CBLK_DIRECTION_OUT;
5452 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 mOutBuffer.frameCount = 0;
5454 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005455 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005456 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5457 mCblk, mBuffer, mCblk->buffers,
5458 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005460 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 }
5462}
5463
5464AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5465{
5466 clearBufferQueue();
5467}
5468
Glenn Kasten3acbd052012-02-28 10:39:56 -08005469status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005470 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005472 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 if (status != NO_ERROR) {
5474 return status;
5475 }
5476
5477 mActive = true;
5478 mRetryCount = 127;
5479 return status;
5480}
5481
5482void AudioFlinger::PlaybackThread::OutputTrack::stop()
5483{
5484 Track::stop();
5485 clearBufferQueue();
5486 mOutBuffer.frameCount = 0;
5487 mActive = false;
5488}
5489
5490bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5491{
5492 Buffer *pInBuffer;
5493 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005494 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 bool outputBufferFull = false;
5496 inBuffer.frameCount = frames;
5497 inBuffer.i16 = data;
5498
5499 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5500
5501 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005502 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 sp<ThreadBase> thread = mThread.promote();
5504 if (thread != 0) {
5505 MixerThread *mixerThread = (MixerThread *)thread.get();
5506 if (mCblk->frameCount > frames){
5507 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5508 uint32_t startFrames = (mCblk->frameCount - frames);
5509 pInBuffer = new Buffer;
5510 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5511 pInBuffer->frameCount = startFrames;
5512 pInBuffer->i16 = pInBuffer->mBuffer;
5513 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5514 mBufferQueue.add(pInBuffer);
5515 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005516 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 }
5518 }
5519 }
5520 }
5521
5522 while (waitTimeLeftMs) {
5523 // First write pending buffers, then new data
5524 if (mBufferQueue.size()) {
5525 pInBuffer = mBufferQueue.itemAt(0);
5526 } else {
5527 pInBuffer = &inBuffer;
5528 }
5529
5530 if (pInBuffer->frameCount == 0) {
5531 break;
5532 }
5533
5534 if (mOutBuffer.frameCount == 0) {
5535 mOutBuffer.frameCount = pInBuffer->frameCount;
5536 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005537 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005538 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 outputBufferFull = true;
5540 break;
5541 }
5542 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5543 if (waitTimeLeftMs >= waitTimeMs) {
5544 waitTimeLeftMs -= waitTimeMs;
5545 } else {
5546 waitTimeLeftMs = 0;
5547 }
5548 }
5549
5550 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5551 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5552 mCblk->stepUser(outFrames);
5553 pInBuffer->frameCount -= outFrames;
5554 pInBuffer->i16 += outFrames * channelCount;
5555 mOutBuffer.frameCount -= outFrames;
5556 mOutBuffer.i16 += outFrames * channelCount;
5557
5558 if (pInBuffer->frameCount == 0) {
5559 if (mBufferQueue.size()) {
5560 mBufferQueue.removeAt(0);
5561 delete [] pInBuffer->mBuffer;
5562 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005563 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 } else {
5565 break;
5566 }
5567 }
5568 }
5569
5570 // If we could not write all frames, allocate a buffer and queue it for next time.
5571 if (inBuffer.frameCount) {
5572 sp<ThreadBase> thread = mThread.promote();
5573 if (thread != 0 && !thread->standby()) {
5574 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5575 pInBuffer = new Buffer;
5576 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5577 pInBuffer->frameCount = inBuffer.frameCount;
5578 pInBuffer->i16 = pInBuffer->mBuffer;
5579 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5580 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005581 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005583 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 }
5585 }
5586 }
5587
5588 // Calling write() with a 0 length buffer, means that no more data will be written:
5589 // If no more buffers are pending, fill output track buffer to make sure it is started
5590 // by output mixer.
5591 if (frames == 0 && mBufferQueue.size() == 0) {
5592 if (mCblk->user < mCblk->frameCount) {
5593 frames = mCblk->frameCount - mCblk->user;
5594 pInBuffer = new Buffer;
5595 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5596 pInBuffer->frameCount = frames;
5597 pInBuffer->i16 = pInBuffer->mBuffer;
5598 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5599 mBufferQueue.add(pInBuffer);
5600 } else if (mActive) {
5601 stop();
5602 }
5603 }
5604
5605 return outputBufferFull;
5606}
5607
5608status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5609{
5610 int active;
5611 status_t result;
5612 audio_track_cblk_t* cblk = mCblk;
5613 uint32_t framesReq = buffer->frameCount;
5614
Steve Block3856b092011-10-20 11:56:00 +01005615// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 buffer->frameCount = 0;
5617
5618 uint32_t framesAvail = cblk->framesAvailable();
5619
5620
5621 if (framesAvail == 0) {
5622 Mutex::Autolock _l(cblk->lock);
5623 goto start_loop_here;
5624 while (framesAvail == 0) {
5625 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005626 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005627 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005628 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 }
5630 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5631 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005632 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 }
5634 // read the server count again
5635 start_loop_here:
5636 framesAvail = cblk->framesAvailable_l();
5637 }
5638 }
5639
5640// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005641// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642// }
5643
5644 if (framesReq > framesAvail) {
5645 framesReq = framesAvail;
5646 }
5647
5648 uint32_t u = cblk->user;
5649 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5650
Marco Nelissena1472d92012-03-30 14:36:54 -07005651 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 framesReq = bufferEnd - u;
5653 }
5654
5655 buffer->frameCount = framesReq;
5656 buffer->raw = (void *)cblk->buffer(u);
5657 return NO_ERROR;
5658}
5659
5660
5661void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5662{
5663 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664
5665 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005666 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 delete [] pBuffer->mBuffer;
5668 delete pBuffer;
5669 }
5670 mBufferQueue.clear();
5671}
5672
5673// ----------------------------------------------------------------------------
5674
5675AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5676 : RefBase(),
5677 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005678 // 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 -07005679 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005680 mPid(pid),
5681 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682{
5683 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5684}
5685
5686// Client destructor must be called with AudioFlinger::mLock held
5687AudioFlinger::Client::~Client()
5688{
5689 mAudioFlinger->removeClient_l(mPid);
5690}
5691
Glenn Kasten435dbe62012-01-30 10:15:48 -08005692sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693{
5694 return mMemoryDealer;
5695}
5696
John Grossman4ff14ba2012-02-08 16:37:41 -08005697// Reserve one of the limited slots for a timed audio track associated
5698// with this client
5699bool AudioFlinger::Client::reserveTimedTrack()
5700{
5701 const int kMaxTimedTracksPerClient = 4;
5702
5703 Mutex::Autolock _l(mTimedTrackLock);
5704
5705 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5706 ALOGW("can not create timed track - pid %d has exceeded the limit",
5707 mPid);
5708 return false;
5709 }
5710
5711 mTimedTrackCount++;
5712 return true;
5713}
5714
5715// Release a slot for a timed audio track
5716void AudioFlinger::Client::releaseTimedTrack()
5717{
5718 Mutex::Autolock _l(mTimedTrackLock);
5719 mTimedTrackCount--;
5720}
5721
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722// ----------------------------------------------------------------------------
5723
5724AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5725 const sp<IAudioFlingerClient>& client,
5726 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005727 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728{
5729}
5730
5731AudioFlinger::NotificationClient::~NotificationClient()
5732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733}
5734
5735void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5736{
5737 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005738 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739}
5740
5741// ----------------------------------------------------------------------------
5742
5743AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5744 : BnAudioTrack(),
5745 mTrack(track)
5746{
5747}
5748
5749AudioFlinger::TrackHandle::~TrackHandle() {
5750 // just stop the track on deletion, associated resources
5751 // will be freed from the main thread once all pending buffers have
5752 // been played. Unless it's not in the active track list, in which
5753 // case we free everything now...
5754 mTrack->destroy();
5755}
5756
Glenn Kasten90716c52012-01-26 13:40:12 -08005757sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5758 return mTrack->getCblk();
5759}
5760
Glenn Kasten3acbd052012-02-28 10:39:56 -08005761status_t AudioFlinger::TrackHandle::start() {
5762 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763}
5764
5765void AudioFlinger::TrackHandle::stop() {
5766 mTrack->stop();
5767}
5768
5769void AudioFlinger::TrackHandle::flush() {
5770 mTrack->flush();
5771}
5772
5773void AudioFlinger::TrackHandle::mute(bool e) {
5774 mTrack->mute(e);
5775}
5776
5777void AudioFlinger::TrackHandle::pause() {
5778 mTrack->pause();
5779}
5780
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5782{
5783 return mTrack->attachAuxEffect(EffectId);
5784}
5785
John Grossman4ff14ba2012-02-08 16:37:41 -08005786status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5787 sp<IMemory>* buffer) {
5788 if (!mTrack->isTimedTrack())
5789 return INVALID_OPERATION;
5790
5791 PlaybackThread::TimedTrack* tt =
5792 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5793 return tt->allocateTimedBuffer(size, buffer);
5794}
5795
5796status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5797 int64_t pts) {
5798 if (!mTrack->isTimedTrack())
5799 return INVALID_OPERATION;
5800
5801 PlaybackThread::TimedTrack* tt =
5802 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5803 return tt->queueTimedBuffer(buffer, pts);
5804}
5805
5806status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5807 const LinearTransform& xform, int target) {
5808
5809 if (!mTrack->isTimedTrack())
5810 return INVALID_OPERATION;
5811
5812 PlaybackThread::TimedTrack* tt =
5813 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5814 return tt->setMediaTimeTransform(
5815 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5816}
5817
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818status_t AudioFlinger::TrackHandle::onTransact(
5819 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5820{
5821 return BnAudioTrack::onTransact(code, data, reply, flags);
5822}
5823
5824// ----------------------------------------------------------------------------
5825
5826sp<IAudioRecord> AudioFlinger::openRecord(
5827 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005828 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005830 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005831 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005833 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 int *sessionId,
5835 status_t *status)
5836{
5837 sp<RecordThread::RecordTrack> recordTrack;
5838 sp<RecordHandle> recordHandle;
5839 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 status_t lStatus;
5841 RecordThread *thread;
5842 size_t inFrameCount;
5843 int lSessionId;
5844
5845 // check calling permissions
5846 if (!recordingAllowed()) {
5847 lStatus = PERMISSION_DENIED;
5848 goto Exit;
5849 }
5850
5851 // add client to list
5852 { // scope for mLock
5853 Mutex::Autolock _l(mLock);
5854 thread = checkRecordThread_l(input);
5855 if (thread == NULL) {
5856 lStatus = BAD_VALUE;
5857 goto Exit;
5858 }
5859
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005860 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861
5862 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005863 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 lSessionId = *sessionId;
5865 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 if (sessionId != NULL) {
5868 *sessionId = lSessionId;
5869 }
5870 }
5871 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872 recordTrack = thread->createRecordTrack_l(client,
5873 sampleRate,
5874 format,
5875 channelMask,
5876 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005877 lSessionId,
5878 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5882 // destructor is called by the TrackBase destructor with mLock held
5883 client.clear();
5884 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885 goto Exit;
5886 }
5887
5888 // return to handle to client
5889 recordHandle = new RecordHandle(recordTrack);
5890 lStatus = NO_ERROR;
5891
5892Exit:
5893 if (status) {
5894 *status = lStatus;
5895 }
5896 return recordHandle;
5897}
5898
5899// ----------------------------------------------------------------------------
5900
5901AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5902 : BnAudioRecord(),
5903 mRecordTrack(recordTrack)
5904{
5905}
5906
5907AudioFlinger::RecordHandle::~RecordHandle() {
5908 stop();
5909}
5910
Glenn Kasten90716c52012-01-26 13:40:12 -08005911sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5912 return mRecordTrack->getCblk();
5913}
5914
Glenn Kasten3acbd052012-02-28 10:39:56 -08005915status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005916 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005917 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918}
5919
5920void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005921 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922 mRecordTrack->stop();
5923}
5924
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925status_t AudioFlinger::RecordHandle::onTransact(
5926 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5927{
5928 return BnAudioRecord::onTransact(code, data, reply, flags);
5929}
5930
5931// ----------------------------------------------------------------------------
5932
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005933AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5934 AudioStreamIn *input,
5935 uint32_t sampleRate,
5936 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005937 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005938 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005939 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005940 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5941 // mRsmpInIndex and mInputBytes set by readInputParameters()
5942 mReqChannelCount(popcount(channels)),
5943 mReqSampleRate(sampleRate)
5944 // mBytesRead is only meaningful while active, and so is cleared in start()
5945 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946{
Glenn Kasten480b4682012-02-28 12:30:08 -08005947 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005948
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 readInputParameters();
5950}
5951
5952
5953AudioFlinger::RecordThread::~RecordThread()
5954{
5955 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005956 delete mResampler;
5957 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958}
5959
5960void AudioFlinger::RecordThread::onFirstRef()
5961{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005962 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963}
5964
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005965status_t AudioFlinger::RecordThread::readyToRun()
5966{
5967 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005968 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005969 return status;
5970}
5971
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972bool AudioFlinger::RecordThread::threadLoop()
5973{
5974 AudioBufferProvider::Buffer buffer;
5975 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005976 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977
Eric Laurent44d98482010-09-30 16:12:31 -07005978 nsecs_t lastWarning = 0;
5979
Eric Laurentfeb0db62011-07-22 09:04:31 -07005980 acquireWakeLock();
5981
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 // start recording
5983 while (!exitPending()) {
5984
5985 processConfigEvents();
5986
5987 { // scope for mLock
5988 Mutex::Autolock _l(mLock);
5989 checkForNewParameters_l();
5990 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5991 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005992 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 mStandby = true;
5994 }
5995
5996 if (exitPending()) break;
5997
Eric Laurentfeb0db62011-07-22 09:04:31 -07005998 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 // go to sleep
6001 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006002 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006003 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 continue;
6005 }
6006 if (mActiveTrack != 0) {
6007 if (mActiveTrack->mState == TrackBase::PAUSING) {
6008 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006009 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 mStandby = true;
6011 }
6012 mActiveTrack.clear();
6013 mStartStopCond.broadcast();
6014 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6015 if (mReqChannelCount != mActiveTrack->channelCount()) {
6016 mActiveTrack.clear();
6017 mStartStopCond.broadcast();
6018 } else if (mBytesRead != 0) {
6019 // record start succeeds only if first read from audio input
6020 // succeeds
6021 if (mBytesRead > 0) {
6022 mActiveTrack->mState = TrackBase::ACTIVE;
6023 } else {
6024 mActiveTrack.clear();
6025 }
6026 mStartStopCond.broadcast();
6027 }
6028 mStandby = false;
6029 }
6030 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006031 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 }
6033
6034 if (mActiveTrack != 0) {
6035 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6036 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006037 unlockEffectChains(effectChains);
6038 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 continue;
6040 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 for (size_t i = 0; i < effectChains.size(); i ++) {
6042 effectChains[i]->process_l();
6043 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006046 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006048 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 // no resampling
6050 while (framesOut) {
6051 size_t framesIn = mFrameCount - mRsmpInIndex;
6052 if (framesIn) {
6053 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6054 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6055 if (framesIn > framesOut)
6056 framesIn = framesOut;
6057 mRsmpInIndex += framesIn;
6058 framesOut -= framesIn;
6059 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006060 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061 memcpy(dst, src, framesIn * mFrameSize);
6062 } else {
6063 int16_t *src16 = (int16_t *)src;
6064 int16_t *dst16 = (int16_t *)dst;
6065 if (mChannelCount == 1) {
6066 while (framesIn--) {
6067 *dst16++ = *src16;
6068 *dst16++ = *src16++;
6069 }
6070 } else {
6071 while (framesIn--) {
6072 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6073 src16 += 2;
6074 }
6075 }
6076 }
6077 }
6078 if (framesOut && mFrameCount == mRsmpInIndex) {
6079 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006080 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006081 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 framesOut = 0;
6083 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006084 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 mRsmpInIndex = 0;
6086 }
6087 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006088 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6090 // Force input into standby so that it tries to
6091 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006092 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006094 }
6095 mRsmpInIndex = mFrameCount;
6096 framesOut = 0;
6097 buffer.frameCount = 0;
6098 }
6099 }
6100 }
6101 } else {
6102 // resampling
6103
6104 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6105 // alter output frame count as if we were expecting stereo samples
6106 if (mChannelCount == 1 && mReqChannelCount == 1) {
6107 framesOut >>= 1;
6108 }
6109 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6110 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6111 // are 32 bit aligned which should be always true.
6112 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006113 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 // the resampler always outputs stereo samples: do post stereo to mono conversion
6115 int16_t *src = (int16_t *)mRsmpOutBuffer;
6116 int16_t *dst = buffer.i16;
6117 while (framesOut--) {
6118 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6119 src += 2;
6120 }
6121 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006122 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 }
6124
6125 }
Eric Laurenta011e352012-03-29 15:51:43 -07006126 if (mFramestoDrop == 0) {
6127 mActiveTrack->releaseBuffer(&buffer);
6128 } else {
6129 if (mFramestoDrop > 0) {
6130 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006131 if (mFramestoDrop <= 0) {
6132 clearSyncStartEvent();
6133 }
6134 } else {
6135 mFramestoDrop += buffer.frameCount;
6136 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6137 mSyncStartEvent->isCancelled()) {
6138 ALOGW("Synced record %s, session %d, trigger session %d",
6139 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6140 mActiveTrack->sessionId(),
6141 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6142 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006143 }
6144 }
6145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 mActiveTrack->overflow();
6147 }
6148 // client isn't retrieving buffers fast enough
6149 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006150 if (!mActiveTrack->setOverflow()) {
6151 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006152 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006153 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006154 lastWarning = now;
6155 }
6156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 // Release the processor for a while before asking for a new buffer.
6158 // This will give the application more chance to read from the buffer and
6159 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006160 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 }
6162 }
Eric Laurentec437d82011-07-26 20:54:46 -07006163 // enable changes in effect chain
6164 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006165 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 }
6167
6168 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006169 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 }
6171 mActiveTrack.clear();
6172
6173 mStartStopCond.broadcast();
6174
Eric Laurentfeb0db62011-07-22 09:04:31 -07006175 releaseWakeLock();
6176
Steve Block3856b092011-10-20 11:56:00 +01006177 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 return false;
6179}
6180
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006181
6182sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6183 const sp<AudioFlinger::Client>& client,
6184 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006185 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 int channelMask,
6187 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006188 int sessionId,
6189 status_t *status)
6190{
6191 sp<RecordTrack> track;
6192 status_t lStatus;
6193
6194 lStatus = initCheck();
6195 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006196 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006197 goto Exit;
6198 }
6199
6200 { // scope for mLock
6201 Mutex::Autolock _l(mLock);
6202
6203 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006204 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006205
Glenn Kasten7378ca52012-01-20 13:44:40 -08006206 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006207 lStatus = NO_MEMORY;
6208 goto Exit;
6209 }
6210
6211 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006212 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6213 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006214 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006215 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6216 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006217 }
6218 lStatus = NO_ERROR;
6219
6220Exit:
6221 if (status) {
6222 *status = lStatus;
6223 }
6224 return track;
6225}
6226
Eric Laurenta011e352012-03-29 15:51:43 -07006227status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006228 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006229 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230{
Glenn Kasten58912562012-04-03 10:45:00 -07006231 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006232 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006234
6235 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006236 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006237 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6238 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6239 triggerSession,
6240 recordTrack->sessionId(),
6241 syncStartEventCallback,
6242 this);
Eric Laurent29864602012-05-08 18:57:51 -07006243 // Sync event can be cancelled by the trigger session if the track is not in a
6244 // compatible state in which case we start record immediately
6245 if (mSyncStartEvent->isCancelled()) {
6246 clearSyncStartEvent();
6247 } else {
6248 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6249 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6250 }
Eric Laurenta011e352012-03-29 15:51:43 -07006251 }
6252
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006254 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 if (mActiveTrack != 0) {
6256 if (recordTrack != mActiveTrack.get()) {
6257 status = -EBUSY;
6258 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6259 mActiveTrack->mState = TrackBase::ACTIVE;
6260 }
6261 return status;
6262 }
6263
6264 recordTrack->mState = TrackBase::IDLE;
6265 mActiveTrack = recordTrack;
6266 mLock.unlock();
6267 status_t status = AudioSystem::startInput(mId);
6268 mLock.lock();
6269 if (status != NO_ERROR) {
6270 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006271 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 return status;
6273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 mRsmpInIndex = mFrameCount;
6275 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006276 if (mResampler != NULL) {
6277 mResampler->reset();
6278 }
6279 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006281 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 mWaitWorkCV.signal();
6283 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006284 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 mActiveTrack.clear();
6286 status = INVALID_OPERATION;
6287 goto startError;
6288 }
6289 mStartStopCond.wait(mLock);
6290 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006291 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 status = BAD_VALUE;
6293 goto startError;
6294 }
Steve Block3856b092011-10-20 11:56:00 +01006295 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 return status;
6297 }
6298startError:
6299 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006300 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 return status;
6302}
6303
Eric Laurenta011e352012-03-29 15:51:43 -07006304void AudioFlinger::RecordThread::clearSyncStartEvent()
6305{
6306 if (mSyncStartEvent != 0) {
6307 mSyncStartEvent->cancel();
6308 }
6309 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006310 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006311}
6312
6313void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6314{
6315 sp<SyncEvent> strongEvent = event.promote();
6316
6317 if (strongEvent != 0) {
6318 RecordThread *me = (RecordThread *)strongEvent->cookie();
6319 me->handleSyncStartEvent(strongEvent);
6320 }
6321}
6322
6323void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6324{
Eric Laurent29864602012-05-08 18:57:51 -07006325 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006326 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6327 // from audio HAL
6328 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006329 }
6330}
6331
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006333 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006334 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006336 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6338 mActiveTrack->mState = TrackBase::PAUSING;
6339 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006340 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 return;
6342 }
6343 mStartStopCond.wait(mLock);
6344 // if we have been restarted, recordTrack == mActiveTrack.get() here
6345 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6346 mLock.unlock();
6347 AudioSystem::stopInput(mId);
6348 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006349 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 }
6351 }
6352 }
6353}
6354
Eric Laurenta011e352012-03-29 15:51:43 -07006355bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6356{
6357 return false;
6358}
6359
6360status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6361{
6362 if (!isValidSyncEvent(event)) {
6363 return BAD_VALUE;
6364 }
6365
6366 Mutex::Autolock _l(mLock);
6367
6368 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6369 mTrack->setSyncEvent(event);
6370 return NO_ERROR;
6371 }
6372 return NAME_NOT_FOUND;
6373}
6374
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6376{
6377 const size_t SIZE = 256;
6378 char buffer[SIZE];
6379 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380
6381 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6382 result.append(buffer);
6383
6384 if (mActiveTrack != 0) {
6385 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006386 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 mActiveTrack->dump(buffer, SIZE);
6388 result.append(buffer);
6389
6390 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6391 result.append(buffer);
6392 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6393 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006394 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 result.append(buffer);
6396 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6397 result.append(buffer);
6398 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6399 result.append(buffer);
6400
6401
6402 } else {
6403 result.append("No record client\n");
6404 }
6405 write(fd, result.string(), result.size());
6406
6407 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006408 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409
6410 return NO_ERROR;
6411}
6412
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006413// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006414status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415{
6416 size_t framesReq = buffer->frameCount;
6417 size_t framesReady = mFrameCount - mRsmpInIndex;
6418 int channelCount;
6419
6420 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006421 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006423 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6425 // Force input into standby so that it tries to
6426 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006427 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006428 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006430 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 buffer->frameCount = 0;
6432 return NOT_ENOUGH_DATA;
6433 }
6434 mRsmpInIndex = 0;
6435 framesReady = mFrameCount;
6436 }
6437
6438 if (framesReq > framesReady) {
6439 framesReq = framesReady;
6440 }
6441
6442 if (mChannelCount == 1 && mReqChannelCount == 2) {
6443 channelCount = 1;
6444 } else {
6445 channelCount = 2;
6446 }
6447 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6448 buffer->frameCount = framesReq;
6449 return NO_ERROR;
6450}
6451
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006452// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6454{
6455 mRsmpInIndex += buffer->frameCount;
6456 buffer->frameCount = 0;
6457}
6458
6459bool AudioFlinger::RecordThread::checkForNewParameters_l()
6460{
6461 bool reconfig = false;
6462
6463 while (!mNewParameters.isEmpty()) {
6464 status_t status = NO_ERROR;
6465 String8 keyValuePair = mNewParameters[0];
6466 AudioParameter param = AudioParameter(keyValuePair);
6467 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006468 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469 int reqSamplingRate = mReqSampleRate;
6470 int reqChannelCount = mReqChannelCount;
6471
6472 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6473 reqSamplingRate = value;
6474 reconfig = true;
6475 }
6476 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006477 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006478 reconfig = true;
6479 }
6480 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006481 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006482 reconfig = true;
6483 }
6484 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6485 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006486 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 // if frame count is changed after track creation
6488 if (mActiveTrack != 0) {
6489 status = INVALID_OPERATION;
6490 } else {
6491 reconfig = true;
6492 }
6493 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006494 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6495 // forward device change to effects that have requested to be
6496 // aware of attached audio device.
6497 for (size_t i = 0; i < mEffectChains.size(); i++) {
6498 mEffectChains[i]->setDevice_l(value);
6499 }
6500 // store input device and output device but do not forward output device to audio HAL.
6501 // Note that status is ignored by the caller for output device
6502 // (see AudioFlinger::setParameters()
6503 if (value & AUDIO_DEVICE_OUT_ALL) {
6504 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6505 status = BAD_VALUE;
6506 } else {
6507 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006508 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6509 if (mTrack != NULL) {
6510 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006511 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006512 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6513 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6514 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006515 }
6516 mDevice |= (uint32_t)value;
6517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006519 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006521 mInput->stream->common.standby(&mInput->stream->common);
6522 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6523 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 }
6525 if (reconfig) {
6526 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006527 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006528 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006529 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006530 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6531 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 status = NO_ERROR;
6533 }
6534 if (status == NO_ERROR) {
6535 readInputParameters();
6536 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6537 }
6538 }
6539 }
6540
6541 mNewParameters.removeAt(0);
6542
6543 mParamStatus = status;
6544 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006545 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6546 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006547 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 }
6549 return reconfig;
6550}
6551
6552String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6553{
Dima Zavinfce7a472011-04-19 22:30:36 -07006554 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006555 String8 out_s8 = String8();
6556
6557 Mutex::Autolock _l(mLock);
6558 if (initCheck() != NO_ERROR) {
6559 return out_s8;
6560 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006561
Dima Zavin799a70e2011-04-18 16:57:27 -07006562 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006563 out_s8 = String8(s);
6564 free(s);
6565 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566}
6567
6568void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6569 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006570 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571
6572 switch (event) {
6573 case AudioSystem::INPUT_OPENED:
6574 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006575 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 desc.samplingRate = mSampleRate;
6577 desc.format = mFormat;
6578 desc.frameCount = mFrameCount;
6579 desc.latency = 0;
6580 param2 = &desc;
6581 break;
6582
6583 case AudioSystem::INPUT_CLOSED:
6584 default:
6585 break;
6586 }
6587 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6588}
6589
6590void AudioFlinger::RecordThread::readInputParameters()
6591{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006592 delete mRsmpInBuffer;
6593 // mRsmpInBuffer is always assigned a new[] below
6594 delete mRsmpOutBuffer;
6595 mRsmpOutBuffer = NULL;
6596 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006597 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598
Dima Zavin799a70e2011-04-18 16:57:27 -07006599 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006600 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6601 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006602 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006603 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006604 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006606 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6608
Glenn Kasten53d76db2012-03-08 12:32:47 -08006609 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 {
6611 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006612 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6613 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 if (mChannelCount == 1 && mReqChannelCount == 2) {
6615 channelCount = 1;
6616 } else {
6617 channelCount = 2;
6618 }
6619 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6620 mResampler->setSampleRate(mSampleRate);
6621 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6622 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6623
6624 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6625 if (mChannelCount == 1 && mReqChannelCount == 1) {
6626 mFrameCount >>= 1;
6627 }
6628
6629 }
6630 mRsmpInIndex = mFrameCount;
6631}
6632
6633unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6634{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006635 Mutex::Autolock _l(mLock);
6636 if (initCheck() != NO_ERROR) {
6637 return 0;
6638 }
6639
Dima Zavin799a70e2011-04-18 16:57:27 -07006640 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641}
6642
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006643uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6644{
6645 Mutex::Autolock _l(mLock);
6646 uint32_t result = 0;
6647 if (getEffectChain_l(sessionId) != 0) {
6648 result = EFFECT_SESSION;
6649 }
6650
6651 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6652 result |= TRACK_SESSION;
6653 }
6654
6655 return result;
6656}
6657
Eric Laurent59bd0da2011-08-01 09:52:20 -07006658AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6659{
6660 Mutex::Autolock _l(mLock);
6661 return mTrack;
6662}
6663
Glenn Kastenaed850d2012-01-26 09:46:34 -08006664AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006665{
6666 Mutex::Autolock _l(mLock);
6667 return mInput;
6668}
6669
6670AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6671{
6672 Mutex::Autolock _l(mLock);
6673 AudioStreamIn *input = mInput;
6674 mInput = NULL;
6675 return input;
6676}
6677
6678// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006679audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006680{
6681 if (mInput == NULL) {
6682 return NULL;
6683 }
6684 return &mInput->stream->common;
6685}
6686
6687
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688// ----------------------------------------------------------------------------
6689
Eric Laurenta4c5a552012-03-29 10:12:40 -07006690audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6691{
6692 if (!settingsAllowed()) {
6693 return 0;
6694 }
6695 Mutex::Autolock _l(mLock);
6696 return loadHwModule_l(name);
6697}
6698
6699// loadHwModule_l() must be called with AudioFlinger::mLock held
6700audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6701{
6702 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6703 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6704 ALOGW("loadHwModule() module %s already loaded", name);
6705 return mAudioHwDevs.keyAt(i);
6706 }
6707 }
6708
Eric Laurenta4c5a552012-03-29 10:12:40 -07006709 audio_hw_device_t *dev;
6710
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006711 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006712 if (rc) {
6713 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6714 return 0;
6715 }
6716
6717 mHardwareStatus = AUDIO_HW_INIT;
6718 rc = dev->init_check(dev);
6719 mHardwareStatus = AUDIO_HW_IDLE;
6720 if (rc) {
6721 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6722 return 0;
6723 }
6724
6725 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6726 (NULL != dev->set_master_volume)) {
6727 AutoMutex lock(mHardwareLock);
6728 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6729 dev->set_master_volume(dev, mMasterVolume);
6730 mHardwareStatus = AUDIO_HW_IDLE;
6731 }
6732
6733 audio_module_handle_t handle = nextUniqueId();
6734 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6735
6736 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006737 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006738
6739 return handle;
6740
6741}
6742
6743audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6744 audio_devices_t *pDevices,
6745 uint32_t *pSamplingRate,
6746 audio_format_t *pFormat,
6747 audio_channel_mask_t *pChannelMask,
6748 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006749 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750{
6751 status_t status;
6752 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006753 struct audio_config config = {
6754 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6755 channel_mask: pChannelMask ? *pChannelMask : 0,
6756 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6757 };
6758 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006759 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760
Eric Laurenta4c5a552012-03-29 10:12:40 -07006761 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6762 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006763 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006764 config.sample_rate,
6765 config.format,
6766 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006767 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768
6769 if (pDevices == NULL || *pDevices == 0) {
6770 return 0;
6771 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006772
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773 Mutex::Autolock _l(mLock);
6774
Eric Laurenta4c5a552012-03-29 10:12:40 -07006775 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006776 if (outHwDev == NULL)
6777 return 0;
6778
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006779 audio_io_handle_t id = nextUniqueId();
6780
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006781 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006782
6783 status = outHwDev->open_output_stream(outHwDev,
6784 id,
6785 *pDevices,
6786 (audio_output_flags_t)flags,
6787 &config,
6788 &outStream);
6789
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006790 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006791 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006792 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006793 config.sample_rate,
6794 config.format,
6795 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 status);
6797
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006798 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006799 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006800
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006801 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006802 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6803 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006805 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 } else {
6807 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006808 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 }
6810 mPlaybackThreads.add(id, thread);
6811
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006812 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6813 if (pFormat != NULL) *pFormat = config.format;
6814 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006815 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006816
6817 // notify client processes of the new output creation
6818 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006819
6820 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006821 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006822 ALOGI("Using module %d has the primary audio interface", module);
6823 mPrimaryHardwareDev = outHwDev;
6824
6825 AutoMutex lock(mHardwareLock);
6826 mHardwareStatus = AUDIO_HW_SET_MODE;
6827 outHwDev->set_mode(outHwDev, mMode);
6828
6829 // Determine the level of master volume support the primary audio HAL has,
6830 // and set the initial master volume at the same time.
6831 float initialVolume = 1.0;
6832 mMasterVolumeSupportLvl = MVS_NONE;
6833
6834 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6835 if ((NULL != outHwDev->get_master_volume) &&
6836 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6837 mMasterVolumeSupportLvl = MVS_FULL;
6838 } else {
6839 mMasterVolumeSupportLvl = MVS_SETONLY;
6840 initialVolume = 1.0;
6841 }
6842
6843 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6844 if ((NULL == outHwDev->set_master_volume) ||
6845 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6846 mMasterVolumeSupportLvl = MVS_NONE;
6847 }
6848 // now that we have a primary device, initialize master volume on other devices
6849 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6850 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6851
6852 if ((dev != mPrimaryHardwareDev) &&
6853 (NULL != dev->set_master_volume)) {
6854 dev->set_master_volume(dev, initialVolume);
6855 }
6856 }
6857 mHardwareStatus = AUDIO_HW_IDLE;
6858 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6859 ? initialVolume
6860 : 1.0;
6861 mMasterVolume = initialVolume;
6862 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 return id;
6864 }
6865
6866 return 0;
6867}
6868
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006869audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6870 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871{
6872 Mutex::Autolock _l(mLock);
6873 MixerThread *thread1 = checkMixerThread_l(output1);
6874 MixerThread *thread2 = checkMixerThread_l(output2);
6875
6876 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006877 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 return 0;
6879 }
6880
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006881 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6883 thread->addOutputTrack(thread2);
6884 mPlaybackThreads.add(id, thread);
6885 // notify client processes of the new output creation
6886 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6887 return id;
6888}
6889
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006890status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891{
6892 // keep strong reference on the playback thread so that
6893 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006894 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895 {
6896 Mutex::Autolock _l(mLock);
6897 thread = checkPlaybackThread_l(output);
6898 if (thread == NULL) {
6899 return BAD_VALUE;
6900 }
6901
Steve Block3856b092011-10-20 11:56:00 +01006902 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006904 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006905 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006906 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6908 dupThread->removeOutputTrack((MixerThread *)thread.get());
6909 }
6910 }
6911 }
Glenn Kastena1117922012-01-26 10:53:32 -08006912 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 mPlaybackThreads.removeItem(output);
6914 }
6915 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006916 // The thread entity (active unit of execution) is no longer running here,
6917 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006919 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006920 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006921 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006922 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006923 out->hwDev->close_output_stream(out->hwDev, out->stream);
6924 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 }
6926 return NO_ERROR;
6927}
6928
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006929status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930{
6931 Mutex::Autolock _l(mLock);
6932 PlaybackThread *thread = checkPlaybackThread_l(output);
6933
6934 if (thread == NULL) {
6935 return BAD_VALUE;
6936 }
6937
Steve Block3856b092011-10-20 11:56:00 +01006938 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939 thread->suspend();
6940
6941 return NO_ERROR;
6942}
6943
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006944status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945{
6946 Mutex::Autolock _l(mLock);
6947 PlaybackThread *thread = checkPlaybackThread_l(output);
6948
6949 if (thread == NULL) {
6950 return BAD_VALUE;
6951 }
6952
Steve Block3856b092011-10-20 11:56:00 +01006953 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954
6955 thread->restore();
6956
6957 return NO_ERROR;
6958}
6959
Eric Laurenta4c5a552012-03-29 10:12:40 -07006960audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6961 audio_devices_t *pDevices,
6962 uint32_t *pSamplingRate,
6963 audio_format_t *pFormat,
6964 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965{
6966 status_t status;
6967 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006968 struct audio_config config = {
6969 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6970 channel_mask: pChannelMask ? *pChannelMask : 0,
6971 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6972 };
6973 uint32_t reqSamplingRate = config.sample_rate;
6974 audio_format_t reqFormat = config.format;
6975 audio_channel_mask_t reqChannels = config.channel_mask;
6976 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006977 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978
6979 if (pDevices == NULL || *pDevices == 0) {
6980 return 0;
6981 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006982
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 Mutex::Autolock _l(mLock);
6984
Eric Laurenta4c5a552012-03-29 10:12:40 -07006985 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006986 if (inHwDev == NULL)
6987 return 0;
6988
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006989 audio_io_handle_t id = nextUniqueId();
6990
6991 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006992 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006993 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006994 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006995 config.sample_rate,
6996 config.format,
6997 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 status);
6999
7000 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7001 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7002 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007003 if (status == BAD_VALUE &&
7004 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7005 (config.sample_rate <= 2 * reqSamplingRate) &&
7006 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01007007 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007008 inStream = NULL;
7009 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 }
7011
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007012 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007013 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7014
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007015 // Start record thread
7016 // RecorThread require both input and output device indication to forward to audio
7017 // pre processing modules
7018 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7019 thread = new RecordThread(this,
7020 input,
7021 reqSamplingRate,
7022 reqChannels,
7023 id,
7024 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007026 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007027 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007028 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007029 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030
Dima Zavin799a70e2011-04-18 16:57:27 -07007031 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032
7033 // notify client processes of the new input creation
7034 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7035 return id;
7036 }
7037
7038 return 0;
7039}
7040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007041status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042{
7043 // keep strong reference on the record thread so that
7044 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007045 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 {
7047 Mutex::Autolock _l(mLock);
7048 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007049 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 return BAD_VALUE;
7051 }
7052
Steve Block3856b092011-10-20 11:56:00 +01007053 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007054 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 mRecordThreads.removeItem(input);
7056 }
7057 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007058 // The thread entity (active unit of execution) is no longer running here,
7059 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007061 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007062 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007063 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007064 in->hwDev->close_input_stream(in->hwDev, in->stream);
7065 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066
7067 return NO_ERROR;
7068}
7069
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007070status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071{
7072 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007073 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074
7075 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7076 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007077 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079
7080 return NO_ERROR;
7081}
7082
7083
7084int AudioFlinger::newAudioSessionId()
7085{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007086 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087}
7088
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007089void AudioFlinger::acquireAudioSessionId(int audioSession)
7090{
7091 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007092 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007093 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007094 size_t num = mAudioSessionRefs.size();
7095 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007096 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007097 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7098 ref->mCnt++;
7099 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007100 return;
7101 }
7102 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007103 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7104 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007105}
7106
7107void AudioFlinger::releaseAudioSessionId(int audioSession)
7108{
7109 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007110 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007111 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007112 size_t num = mAudioSessionRefs.size();
7113 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007114 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007115 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7116 ref->mCnt--;
7117 ALOGV(" decremented refcount to %d", ref->mCnt);
7118 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007119 mAudioSessionRefs.removeAt(i);
7120 delete ref;
7121 purgeStaleEffects_l();
7122 }
7123 return;
7124 }
7125 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007126 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007127}
7128
7129void AudioFlinger::purgeStaleEffects_l() {
7130
Steve Block3856b092011-10-20 11:56:00 +01007131 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007132
7133 Vector< sp<EffectChain> > chains;
7134
7135 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7136 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7137 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7138 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007139 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7140 chains.push(ec);
7141 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007142 }
7143 }
7144 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7145 sp<RecordThread> t = mRecordThreads.valueAt(i);
7146 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7147 sp<EffectChain> ec = t->mEffectChains[j];
7148 chains.push(ec);
7149 }
7150 }
7151
7152 for (size_t i = 0; i < chains.size(); i++) {
7153 sp<EffectChain> ec = chains[i];
7154 int sessionid = ec->sessionId();
7155 sp<ThreadBase> t = ec->mThread.promote();
7156 if (t == 0) {
7157 continue;
7158 }
7159 size_t numsessionrefs = mAudioSessionRefs.size();
7160 bool found = false;
7161 for (size_t k = 0; k < numsessionrefs; k++) {
7162 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007163 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007164 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007165 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007166 found = true;
7167 break;
7168 }
7169 }
7170 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007171 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007172 // remove all effects from the chain
7173 while (ec->mEffects.size()) {
7174 sp<EffectModule> effect = ec->mEffects[0];
7175 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007176 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007177 if (effect->purgeHandles()) {
7178 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007179 }
7180 AudioSystem::unregisterEffect(effect->id());
7181 }
7182 }
7183 }
7184 return;
7185}
7186
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007188AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189{
Glenn Kastena1117922012-01-26 10:53:32 -08007190 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007191}
7192
7193// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007194AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195{
7196 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007197 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198}
7199
7200// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007201AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202{
Glenn Kastena1117922012-01-26 10:53:32 -08007203 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204}
7205
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007206uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007208 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209}
7210
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007211AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007212{
7213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7214 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007215 AudioStreamOut *output = thread->getOutput();
7216 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007217 return thread;
7218 }
7219 }
7220 return NULL;
7221}
7222
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007223uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007224{
7225 PlaybackThread *thread = primaryPlaybackThread_l();
7226
7227 if (thread == NULL) {
7228 return 0;
7229 }
7230
7231 return thread->device();
7232}
7233
Eric Laurenta011e352012-03-29 15:51:43 -07007234sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7235 int triggerSession,
7236 int listenerSession,
7237 sync_event_callback_t callBack,
7238 void *cookie)
7239{
7240 Mutex::Autolock _l(mLock);
7241
7242 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7243 status_t playStatus = NAME_NOT_FOUND;
7244 status_t recStatus = NAME_NOT_FOUND;
7245 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7246 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7247 if (playStatus == NO_ERROR) {
7248 return event;
7249 }
7250 }
7251 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7252 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7253 if (recStatus == NO_ERROR) {
7254 return event;
7255 }
7256 }
7257 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7258 mPendingSyncEvents.add(event);
7259 } else {
7260 ALOGV("createSyncEvent() invalid event %d", event->type());
7261 event.clear();
7262 }
7263 return event;
7264}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007265
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266// ----------------------------------------------------------------------------
7267// Effect management
7268// ----------------------------------------------------------------------------
7269
7270
Glenn Kastenf587ba52012-01-26 16:25:10 -08007271status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272{
7273 Mutex::Autolock _l(mLock);
7274 return EffectQueryNumberEffects(numEffects);
7275}
7276
Glenn Kastenf587ba52012-01-26 16:25:10 -08007277status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278{
7279 Mutex::Autolock _l(mLock);
7280 return EffectQueryEffect(index, descriptor);
7281}
7282
Glenn Kasten5e92a782012-01-30 07:40:52 -08007283status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007284 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285{
7286 Mutex::Autolock _l(mLock);
7287 return EffectGetDescriptor(pUuid, descriptor);
7288}
7289
7290
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7292 effect_descriptor_t *pDesc,
7293 const sp<IEffectClient>& effectClient,
7294 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007295 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 int sessionId,
7297 status_t *status,
7298 int *id,
7299 int *enabled)
7300{
7301 status_t lStatus = NO_ERROR;
7302 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007303 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007305 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307
7308 if (pDesc == NULL) {
7309 lStatus = BAD_VALUE;
7310 goto Exit;
7311 }
7312
Eric Laurent84e9a102010-09-23 16:10:16 -07007313 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007314 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007315 lStatus = PERMISSION_DENIED;
7316 goto Exit;
7317 }
7318
Dima Zavinfce7a472011-04-19 22:30:36 -07007319 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007320 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007321 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007322 lStatus = PERMISSION_DENIED;
7323 goto Exit;
7324 }
7325
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007326 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007327 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007328 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007329 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007330 lStatus = BAD_VALUE;
7331 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007332 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007333 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007334 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007335 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007336 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007337 }
7338 }
7339
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340 {
7341 Mutex::Autolock _l(mLock);
7342
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343
7344 if (!EffectIsNullUuid(&pDesc->uuid)) {
7345 // if uuid is specified, request effect descriptor
7346 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7347 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007348 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 goto Exit;
7350 }
7351 } else {
7352 // if uuid is not specified, look for an available implementation
7353 // of the required type in effect factory
7354 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007355 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 lStatus = BAD_VALUE;
7357 goto Exit;
7358 }
7359 uint32_t numEffects = 0;
7360 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007361 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 bool found = false;
7363
7364 lStatus = EffectQueryNumberEffects(&numEffects);
7365 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007366 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 goto Exit;
7368 }
7369 for (uint32_t i = 0; i < numEffects; i++) {
7370 lStatus = EffectQueryEffect(i, &desc);
7371 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007372 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 continue;
7374 }
7375 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7376 // If matching type found save effect descriptor. If the session is
7377 // 0 and the effect is not auxiliary, continue enumeration in case
7378 // an auxiliary version of this effect type is available
7379 found = true;
7380 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007381 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7383 break;
7384 }
7385 }
7386 }
7387 if (!found) {
7388 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007389 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 goto Exit;
7391 }
7392 // For same effect type, chose auxiliary version over insert version if
7393 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007394 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7396 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7397 }
7398 }
7399
7400 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007401 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7403 lStatus = INVALID_OPERATION;
7404 goto Exit;
7405 }
7406
Eric Laurent59255e42011-07-27 19:49:51 -07007407 // check recording permission for visualizer
7408 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7409 !recordingAllowed()) {
7410 lStatus = PERMISSION_DENIED;
7411 goto Exit;
7412 }
7413
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 // return effect descriptor
7415 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7416
7417 // If output is not specified try to find a matching audio session ID in one of the
7418 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007419 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7420 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007421 // Note: io is never 0 when creating an effect on an input
7422 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007423 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7425 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007427 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007430 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007431 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7432 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7433 io = mRecordThreads.keyAt(i);
7434 break;
7435 }
7436 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007437 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007438 // If no output thread contains the requested session ID, default to
7439 // first output. The effect chain will be moved to the correct output
7440 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007441 if (io == 0 && mPlaybackThreads.size()) {
7442 io = mPlaybackThreads.keyAt(0);
7443 }
Steve Block3856b092011-10-20 11:56:00 +01007444 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007445 }
7446 ThreadBase *thread = checkRecordThread_l(io);
7447 if (thread == NULL) {
7448 thread = checkPlaybackThread_l(io);
7449 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007450 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007451 lStatus = BAD_VALUE;
7452 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007455
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007456 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007458 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007459 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7460 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 if (handle != 0 && id != NULL) {
7462 *id = handle->id();
7463 }
7464 }
7465
7466Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007467 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 *status = lStatus;
7469 }
7470 return handle;
7471}
7472
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007473status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7474 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007475{
Steve Block3856b092011-10-20 11:56:00 +01007476 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007477 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007478 Mutex::Autolock _l(mLock);
7479 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007480 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007481 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007482 }
Eric Laurentde070132010-07-13 04:45:46 -07007483 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7484 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007485 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007486 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487 }
Eric Laurentde070132010-07-13 04:45:46 -07007488 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7489 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007490 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007491 return BAD_VALUE;
7492 }
7493
7494 Mutex::Autolock _dl(dstThread->mLock);
7495 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007496 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007497
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 return NO_ERROR;
7499}
7500
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007501// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007502status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007503 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007504 AudioFlinger::PlaybackThread *dstThread,
7505 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007506{
Steve Block3856b092011-10-20 11:56:00 +01007507 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007508 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007509
Eric Laurent59255e42011-07-27 19:49:51 -07007510 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007511 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007512 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007513 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007514 return INVALID_OPERATION;
7515 }
7516
Eric Laurent39e94f82010-07-28 01:32:47 -07007517 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007518 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007519 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007520 // removed.
7521 srcThread->removeEffectChain_l(chain);
7522
7523 // transfer all effects one by one so that new effect chain is created on new thread with
7524 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007525 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007526 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007527 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007528 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7529 while (effect != 0) {
7530 srcThread->removeEffect_l(effect);
7531 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007532 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7533 if (effect->state() == EffectModule::ACTIVE ||
7534 effect->state() == EffectModule::STOPPING) {
7535 effect->start();
7536 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007537 // if the move request is not received from audio policy manager, the effect must be
7538 // re-registered with the new strategy and output
7539 if (dstChain == 0) {
7540 dstChain = effect->chain().promote();
7541 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007542 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007543 srcThread->addEffect_l(effect);
7544 return NO_INIT;
7545 }
7546 strategy = dstChain->strategy();
7547 }
7548 if (reRegister) {
7549 AudioSystem::unregisterEffect(effect->id());
7550 AudioSystem::registerEffect(&effect->desc(),
7551 dstOutput,
7552 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007553 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007554 effect->id());
7555 }
Eric Laurentde070132010-07-13 04:45:46 -07007556 effect = chain->getEffectFromId_l(0);
7557 }
7558
7559 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560}
7561
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007562
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007564sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565 const sp<AudioFlinger::Client>& client,
7566 const sp<IEffectClient>& effectClient,
7567 int32_t priority,
7568 int sessionId,
7569 effect_descriptor_t *desc,
7570 int *enabled,
7571 status_t *status
7572 )
7573{
7574 sp<EffectModule> effect;
7575 sp<EffectHandle> handle;
7576 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007578 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007579 bool effectCreated = false;
7580 bool effectRegistered = false;
7581
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007582 lStatus = initCheck();
7583 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007584 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 goto Exit;
7586 }
7587
7588 // Do not allow effects with session ID 0 on direct output or duplicating threads
7589 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007590 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007591 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007592 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593 lStatus = BAD_VALUE;
7594 goto Exit;
7595 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007596 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007597 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007598 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007599 desc->name, desc->flags, mType);
7600 lStatus = BAD_VALUE;
7601 goto Exit;
7602 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603
Steve Block3856b092011-10-20 11:56:00 +01007604 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605
7606 { // scope for mLock
7607 Mutex::Autolock _l(mLock);
7608
7609 // check for existing effect chain with the requested audio session
7610 chain = getEffectChain_l(sessionId);
7611 if (chain == 0) {
7612 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007613 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614 chain = new EffectChain(this, sessionId);
7615 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007616 chain->setStrategy(getStrategyForSession_l(sessionId));
7617 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007619 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 }
7621
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007622 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623
7624 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007625 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007627 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 if (lStatus != NO_ERROR) {
7629 goto Exit;
7630 }
7631 effectRegistered = true;
7632 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007633 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634 lStatus = effect->status();
7635 if (lStatus != NO_ERROR) {
7636 goto Exit;
7637 }
Eric Laurentcab11242010-07-15 12:50:15 -07007638 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 if (lStatus != NO_ERROR) {
7640 goto Exit;
7641 }
7642 effectCreated = true;
7643
7644 effect->setDevice(mDevice);
7645 effect->setMode(mAudioFlinger->getMode());
7646 }
7647 // create effect handle and connect it to effect module
7648 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007649 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007650 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651 *enabled = (int)effect->isEnabled();
7652 }
7653 }
7654
7655Exit:
7656 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007657 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007659 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660 }
7661 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007662 AudioSystem::unregisterEffect(effect->id());
7663 }
7664 if (chainCreated) {
7665 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666 }
7667 handle.clear();
7668 }
7669
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007670 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007671 *status = lStatus;
7672 }
7673 return handle;
7674}
7675
Eric Laurent717e1282012-06-29 16:36:52 -07007676sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7677{
7678 Mutex::Autolock _l(mLock);
7679 return getEffect_l(sessionId, effectId);
7680}
7681
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007682sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7683{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007684 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007685 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007686}
7687
Eric Laurentde070132010-07-13 04:45:46 -07007688// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7689// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007690status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007691{
7692 // check for existing effect chain with the requested audio session
7693 int sessionId = effect->sessionId();
7694 sp<EffectChain> chain = getEffectChain_l(sessionId);
7695 bool chainCreated = false;
7696
7697 if (chain == 0) {
7698 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007699 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007700 chain = new EffectChain(this, sessionId);
7701 addEffectChain_l(chain);
7702 chain->setStrategy(getStrategyForSession_l(sessionId));
7703 chainCreated = true;
7704 }
Steve Block3856b092011-10-20 11:56:00 +01007705 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007706
7707 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007708 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007709 this, effect->desc().name, chain.get());
7710 return BAD_VALUE;
7711 }
7712
7713 status_t status = chain->addEffect_l(effect);
7714 if (status != NO_ERROR) {
7715 if (chainCreated) {
7716 removeEffectChain_l(chain);
7717 }
7718 return status;
7719 }
7720
7721 effect->setDevice(mDevice);
7722 effect->setMode(mAudioFlinger->getMode());
7723 return NO_ERROR;
7724}
7725
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007726void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007727
Steve Block3856b092011-10-20 11:56:00 +01007728 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007730 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7731 detachAuxEffect_l(effect->id());
7732 }
7733
7734 sp<EffectChain> chain = effect->chain().promote();
7735 if (chain != 0) {
7736 // remove effect chain if removing last effect
7737 if (chain->removeEffect_l(effect) == 0) {
7738 removeEffectChain_l(chain);
7739 }
7740 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007741 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007742 }
7743}
7744
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007746 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007747{
7748 effectChains = mEffectChains;
7749 for (size_t i = 0; i < mEffectChains.size(); i++) {
7750 mEffectChains[i]->lock();
7751 }
7752}
7753
7754void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007755 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007756{
7757 for (size_t i = 0; i < effectChains.size(); i++) {
7758 effectChains[i]->unlock();
7759 }
7760}
7761
7762sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7763{
7764 Mutex::Autolock _l(mLock);
7765 return getEffectChain_l(sessionId);
7766}
7767
7768sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7769{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007770 size_t size = mEffectChains.size();
7771 for (size_t i = 0; i < size; i++) {
7772 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007773 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007774 }
7775 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007776 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007777}
7778
Glenn Kastenf78aee72012-01-04 11:00:47 -08007779void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007780{
7781 Mutex::Autolock _l(mLock);
7782 size_t size = mEffectChains.size();
7783 for (size_t i = 0; i < size; i++) {
7784 mEffectChains[i]->setMode_l(mode);
7785 }
7786}
7787
7788void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007789 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007790 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007791
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007793 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 // delete the effect module if removing last handle on it
7795 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007796 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007797 removeEffect_l(effect);
7798 AudioSystem::unregisterEffect(effect->id());
7799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800 }
7801}
7802
7803status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7804{
7805 int session = chain->sessionId();
7806 int16_t *buffer = mMixBuffer;
7807 bool ownsBuffer = false;
7808
Steve Block3856b092011-10-20 11:56:00 +01007809 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 if (session > 0) {
7811 // Only one effect chain can be present in direct output thread and it uses
7812 // the mix buffer as input
7813 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007814 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815 buffer = new int16_t[numSamples];
7816 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007817 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 ownsBuffer = true;
7819 }
7820
7821 // Attach all tracks with same session ID to this chain.
7822 for (size_t i = 0; i < mTracks.size(); ++i) {
7823 sp<Track> track = mTracks[i];
7824 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007825 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007827 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828 }
7829 }
7830
7831 // indicate all active tracks in the chain
7832 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7833 sp<Track> track = mActiveTracks[i].promote();
7834 if (track == 0) continue;
7835 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007836 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007837 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 }
7839 }
7840 }
7841
7842 chain->setInBuffer(buffer, ownsBuffer);
7843 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007844 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007845 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007846 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7847 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007848 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007849 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7850 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007851 // Effect chain for other sessions are inserted at beginning of effect
7852 // chains list to be processed before output mix effects. Relative order between other
7853 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007854 size_t size = mEffectChains.size();
7855 size_t i = 0;
7856 for (i = 0; i < size; i++) {
7857 if (mEffectChains[i]->sessionId() < session) break;
7858 }
7859 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007860 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861
7862 return NO_ERROR;
7863}
7864
7865size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7866{
7867 int session = chain->sessionId();
7868
Steve Block3856b092011-10-20 11:56:00 +01007869 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870
7871 for (size_t i = 0; i < mEffectChains.size(); i++) {
7872 if (chain == mEffectChains[i]) {
7873 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007874 // detach all active tracks from the chain
7875 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7876 sp<Track> track = mActiveTracks[i].promote();
7877 if (track == 0) continue;
7878 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007879 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007880 chain.get(), session);
7881 chain->decActiveTrackCnt();
7882 }
7883 }
7884
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 // detach all tracks with same session ID from this chain
7886 for (size_t i = 0; i < mTracks.size(); ++i) {
7887 sp<Track> track = mTracks[i];
7888 if (session == track->sessionId()) {
7889 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007890 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 }
7892 }
Eric Laurentde070132010-07-13 04:45:46 -07007893 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 }
7895 }
7896 return mEffectChains.size();
7897}
7898
Eric Laurentde070132010-07-13 04:45:46 -07007899status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7900 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901{
7902 Mutex::Autolock _l(mLock);
7903 return attachAuxEffect_l(track, EffectId);
7904}
7905
Eric Laurentde070132010-07-13 04:45:46 -07007906status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7907 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908{
7909 status_t status = NO_ERROR;
7910
7911 if (EffectId == 0) {
7912 track->setAuxBuffer(0, NULL);
7913 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007914 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7915 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 if (effect != 0) {
7917 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7918 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7919 } else {
7920 status = INVALID_OPERATION;
7921 }
7922 } else {
7923 status = BAD_VALUE;
7924 }
7925 }
7926 return status;
7927}
7928
7929void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7930{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007931 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 sp<Track> track = mTracks[i];
7933 if (track->auxEffectId() == effectId) {
7934 attachAuxEffect_l(track, 0);
7935 }
7936 }
7937}
7938
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007939status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7940{
7941 // only one chain per input thread
7942 if (mEffectChains.size() != 0) {
7943 return INVALID_OPERATION;
7944 }
Steve Block3856b092011-10-20 11:56:00 +01007945 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007946
7947 chain->setInBuffer(NULL);
7948 chain->setOutBuffer(NULL);
7949
Eric Laurent59255e42011-07-27 19:49:51 -07007950 checkSuspendOnAddEffectChain_l(chain);
7951
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007952 mEffectChains.add(chain);
7953
7954 return NO_ERROR;
7955}
7956
7957size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7958{
Steve Block3856b092011-10-20 11:56:00 +01007959 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007960 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007961 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7962 chain.get(), mEffectChains.size(), this);
7963 if (mEffectChains.size() == 1) {
7964 mEffectChains.removeAt(0);
7965 }
7966 return 0;
7967}
7968
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969// ----------------------------------------------------------------------------
7970// EffectModule implementation
7971// ----------------------------------------------------------------------------
7972
7973#undef LOG_TAG
7974#define LOG_TAG "AudioFlinger::EffectModule"
7975
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007976AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977 const wp<AudioFlinger::EffectChain>& chain,
7978 effect_descriptor_t *desc,
7979 int id,
7980 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007981 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7982 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7983 // mDescriptor is set below
7984 // mConfig is set by configure() and not used before then
7985 mEffectInterface(NULL),
7986 mStatus(NO_INIT), mState(IDLE),
7987 // mMaxDisableWaitCnt is set by configure() and not used before then
7988 // mDisableWaitCnt is set by process() and updateState() and not used before then
7989 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990{
Steve Block3856b092011-10-20 11:56:00 +01007991 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007993 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994 return;
7995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996
7997 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7998
7999 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008000 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001
8002 if (mStatus != NO_ERROR) {
8003 return;
8004 }
8005 lStatus = init();
8006 if (lStatus < 0) {
8007 mStatus = lStatus;
8008 goto Error;
8009 }
8010
Steve Block3856b092011-10-20 11:56:00 +01008011 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012 return;
8013Error:
8014 EffectRelease(mEffectInterface);
8015 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008016 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017}
8018
8019AudioFlinger::EffectModule::~EffectModule()
8020{
Steve Block3856b092011-10-20 11:56:00 +01008021 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008023 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8024 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8025 sp<ThreadBase> thread = mThread.promote();
8026 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008027 audio_stream_t *stream = thread->stream();
8028 if (stream != NULL) {
8029 stream->remove_audio_effect(stream, mEffectInterface);
8030 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008031 }
8032 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008033 // release effect engine
8034 EffectRelease(mEffectInterface);
8035 }
8036}
8037
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008038status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039{
8040 status_t status;
8041
8042 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043 int priority = handle->priority();
8044 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008045 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 size_t i;
8047 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008048 EffectHandle *h = mHandles[i];
8049 if (h == NULL || h->destroyed_l()) continue;
8050 // first non destroyed handle is considered in control
8051 if (controlHandle == NULL)
8052 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 if (h->priority() <= priority) break;
8054 }
8055 // if inserted in first place, move effect control from previous owner to this handle
8056 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008057 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008058 if (controlHandle != NULL) {
8059 enabled = controlHandle->enabled();
8060 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 }
Eric Laurent59255e42011-07-27 19:49:51 -07008062 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 status = NO_ERROR;
8064 } else {
8065 status = ALREADY_EXISTS;
8066 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008067 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068 mHandles.insertAt(handle, i);
8069 return status;
8070}
8071
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008072size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073{
8074 Mutex::Autolock _l(mLock);
8075 size_t size = mHandles.size();
8076 size_t i;
8077 for (i = 0; i < size; i++) {
8078 if (mHandles[i] == handle) break;
8079 }
8080 if (i == size) {
8081 return size;
8082 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008083 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008084
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008087 if (i == 0) {
8088 EffectHandle *h = controlHandle_l();
8089 if (h != NULL) {
8090 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 }
8092 }
8093
Eric Laurentec437d82011-07-26 20:54:46 -07008094 // Prevent calls to process() and other functions on effect interface from now on.
8095 // The effect engine will be released by the destructor when the last strong reference on
8096 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008097 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008098 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008099 }
8100
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101 return size;
8102}
8103
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008104// must be called with EffectModule::mLock held
8105AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008106{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008107 // the first valid handle in the list has control over the module
8108 for (size_t i = 0; i < mHandles.size(); i++) {
8109 EffectHandle *h = mHandles[i];
8110 if (h != NULL && !h->destroyed_l()) {
8111 return h;
8112 }
8113 }
8114
8115 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008116}
8117
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008118size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008119{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008120 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121 // keep a strong reference on this EffectModule to avoid calling the
8122 // destructor before we exit
8123 sp<EffectModule> keep(this);
8124 {
8125 sp<ThreadBase> thread = mThread.promote();
8126 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008127 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128 }
8129 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008130 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131}
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++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008440 EffectHandle *h = mHandles[i];
8441 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008442 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8443 }
8444 }
8445 }
8446 return status;
8447}
8448
8449status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8450{
8451 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008452 return setEnabled_l(enabled);
8453}
8454
8455// must be called with EffectModule::mLock held
8456status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8457{
8458
Steve Block3856b092011-10-20 11:56:00 +01008459 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008460
8461 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008462 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8463 if (enabled && status != NO_ERROR) {
8464 return status;
8465 }
8466
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467 switch (mState) {
8468 // going from disabled to enabled
8469 case IDLE:
8470 mState = STARTING;
8471 break;
8472 case STOPPED:
8473 mState = RESTART;
8474 break;
8475 case STOPPING:
8476 mState = ACTIVE;
8477 break;
8478
8479 // going from enabled to disabled
8480 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008481 mState = STOPPED;
8482 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483 case STARTING:
8484 mState = IDLE;
8485 break;
8486 case ACTIVE:
8487 mState = STOPPING;
8488 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008489 case DESTROYED:
8490 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008491 }
8492 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008493 EffectHandle *h = mHandles[i];
8494 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 h->setEnabled(enabled);
8496 }
8497 }
8498 }
8499 return NO_ERROR;
8500}
8501
Glenn Kastenc59c0042012-02-02 14:06:11 -08008502bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503{
8504 switch (mState) {
8505 case RESTART:
8506 case STARTING:
8507 case ACTIVE:
8508 return true;
8509 case IDLE:
8510 case STOPPING:
8511 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008512 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 default:
8514 return false;
8515 }
8516}
8517
Glenn Kastenc59c0042012-02-02 14:06:11 -08008518bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008519{
8520 switch (mState) {
8521 case RESTART:
8522 case ACTIVE:
8523 case STOPPING:
8524 case STOPPED:
8525 return true;
8526 case IDLE:
8527 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008528 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008529 default:
8530 return false;
8531 }
8532}
8533
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8535{
8536 Mutex::Autolock _l(mLock);
8537 status_t status = NO_ERROR;
8538
8539 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8540 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008541 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008542 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8543 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008544 status_t cmdStatus;
8545 uint32_t volume[2];
8546 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008547 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008548 volume[0] = *left;
8549 volume[1] = *right;
8550 if (controller) {
8551 pVolume = volume;
8552 }
Eric Laurent25f43952010-07-28 05:40:18 -07008553 status = (*mEffectInterface)->command(mEffectInterface,
8554 EFFECT_CMD_SET_VOLUME,
8555 size,
8556 volume,
8557 &size,
8558 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008559 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8560 *left = volume[0];
8561 *right = volume[1];
8562 }
8563 }
8564 return status;
8565}
8566
8567status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8568{
8569 Mutex::Autolock _l(mLock);
8570 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008571 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8572 // audio pre processing modules on RecordThread can receive both output and
8573 // input device indication in the same call
8574 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8575 if (dev) {
8576 status_t cmdStatus;
8577 uint32_t size = sizeof(status_t);
8578
8579 status = (*mEffectInterface)->command(mEffectInterface,
8580 EFFECT_CMD_SET_DEVICE,
8581 sizeof(uint32_t),
8582 &dev,
8583 &size,
8584 &cmdStatus);
8585 if (status == NO_ERROR) {
8586 status = cmdStatus;
8587 }
8588 }
8589 dev = device & AUDIO_DEVICE_IN_ALL;
8590 if (dev) {
8591 status_t cmdStatus;
8592 uint32_t size = sizeof(status_t);
8593
8594 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8595 EFFECT_CMD_SET_INPUT_DEVICE,
8596 sizeof(uint32_t),
8597 &dev,
8598 &size,
8599 &cmdStatus);
8600 if (status2 == NO_ERROR) {
8601 status2 = cmdStatus;
8602 }
8603 if (status == NO_ERROR) {
8604 status = status2;
8605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 }
8607 }
8608 return status;
8609}
8610
Glenn Kastenf78aee72012-01-04 11:00:47 -08008611status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612{
8613 Mutex::Autolock _l(mLock);
8614 status_t status = NO_ERROR;
8615 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008616 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008617 uint32_t size = sizeof(status_t);
8618 status = (*mEffectInterface)->command(mEffectInterface,
8619 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008620 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008621 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008622 &size,
8623 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008624 if (status == NO_ERROR) {
8625 status = cmdStatus;
8626 }
8627 }
8628 return status;
8629}
8630
Eric Laurent59255e42011-07-27 19:49:51 -07008631void AudioFlinger::EffectModule::setSuspended(bool suspended)
8632{
8633 Mutex::Autolock _l(mLock);
8634 mSuspended = suspended;
8635}
Glenn Kastena3a85482012-01-04 11:01:11 -08008636
8637bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008638{
8639 Mutex::Autolock _l(mLock);
8640 return mSuspended;
8641}
8642
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008643bool AudioFlinger::EffectModule::purgeHandles()
8644{
8645 bool enabled = false;
8646 Mutex::Autolock _l(mLock);
8647 for (size_t i = 0; i < mHandles.size(); i++) {
8648 EffectHandle *handle = mHandles[i];
8649 if (handle != NULL && !handle->destroyed_l()) {
8650 handle->effect().clear();
8651 if (handle->hasControl()) {
8652 enabled = handle->enabled();
8653 }
8654 }
8655 }
8656 return enabled;
8657}
8658
Mathias Agopian65ab4712010-07-14 17:59:35 -07008659status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8660{
8661 const size_t SIZE = 256;
8662 char buffer[SIZE];
8663 String8 result;
8664
8665 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8666 result.append(buffer);
8667
8668 bool locked = tryLock(mLock);
8669 // failed to lock - AudioFlinger is probably deadlocked
8670 if (!locked) {
8671 result.append("\t\tCould not lock Fx mutex:\n");
8672 }
8673
8674 result.append("\t\tSession Status State Engine:\n");
8675 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8676 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8677 result.append(buffer);
8678
8679 result.append("\t\tDescriptor:\n");
8680 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8681 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8682 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8683 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8684 result.append(buffer);
8685 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8686 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8687 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8688 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8689 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008690 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008691 mDescriptor.apiVersion,
8692 mDescriptor.flags);
8693 result.append(buffer);
8694 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8695 mDescriptor.name);
8696 result.append(buffer);
8697 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8698 mDescriptor.implementor);
8699 result.append(buffer);
8700
8701 result.append("\t\t- Input configuration:\n");
8702 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8703 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8704 (uint32_t)mConfig.inputCfg.buffer.raw,
8705 mConfig.inputCfg.buffer.frameCount,
8706 mConfig.inputCfg.samplingRate,
8707 mConfig.inputCfg.channels,
8708 mConfig.inputCfg.format);
8709 result.append(buffer);
8710
8711 result.append("\t\t- Output configuration:\n");
8712 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8713 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8714 (uint32_t)mConfig.outputCfg.buffer.raw,
8715 mConfig.outputCfg.buffer.frameCount,
8716 mConfig.outputCfg.samplingRate,
8717 mConfig.outputCfg.channels,
8718 mConfig.outputCfg.format);
8719 result.append(buffer);
8720
8721 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8722 result.append(buffer);
8723 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8724 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008725 EffectHandle *handle = mHandles[i];
8726 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008727 handle->dump(buffer, SIZE);
8728 result.append(buffer);
8729 }
8730 }
8731
8732 result.append("\n");
8733
8734 write(fd, result.string(), result.length());
8735
8736 if (locked) {
8737 mLock.unlock();
8738 }
8739
8740 return NO_ERROR;
8741}
8742
8743// ----------------------------------------------------------------------------
8744// EffectHandle implementation
8745// ----------------------------------------------------------------------------
8746
8747#undef LOG_TAG
8748#define LOG_TAG "AudioFlinger::EffectHandle"
8749
8750AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8751 const sp<AudioFlinger::Client>& client,
8752 const sp<IEffectClient>& effectClient,
8753 int32_t priority)
8754 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008755 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008756 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757{
Steve Block3856b092011-10-20 11:56:00 +01008758 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008760 if (client == 0) {
8761 return;
8762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008763 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8764 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8765 if (mCblkMemory != 0) {
8766 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8767
Glenn Kastena0d68332012-01-27 16:47:15 -08008768 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008769 new(mCblk) effect_param_cblk_t();
8770 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008773 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774 return;
8775 }
8776}
8777
8778AudioFlinger::EffectHandle::~EffectHandle()
8779{
Steve Block3856b092011-10-20 11:56:00 +01008780 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008781
8782 if (mEffect == 0) {
8783 mDestroyed = true;
8784 return;
8785 }
8786 mEffect->lock();
8787 mDestroyed = true;
8788 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008789 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790}
8791
8792status_t AudioFlinger::EffectHandle::enable()
8793{
Steve Block3856b092011-10-20 11:56:00 +01008794 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008795 if (!mHasControl) return INVALID_OPERATION;
8796 if (mEffect == 0) return DEAD_OBJECT;
8797
Eric Laurentdb7c0792011-08-10 10:37:50 -07008798 if (mEnabled) {
8799 return NO_ERROR;
8800 }
8801
Eric Laurent59255e42011-07-27 19:49:51 -07008802 mEnabled = true;
8803
8804 sp<ThreadBase> thread = mEffect->thread().promote();
8805 if (thread != 0) {
8806 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8807 }
8808
8809 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8810 if (mEffect->suspended()) {
8811 return NO_ERROR;
8812 }
8813
Eric Laurentdb7c0792011-08-10 10:37:50 -07008814 status_t status = mEffect->setEnabled(true);
8815 if (status != NO_ERROR) {
8816 if (thread != 0) {
8817 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8818 }
8819 mEnabled = false;
8820 }
8821 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822}
8823
8824status_t AudioFlinger::EffectHandle::disable()
8825{
Steve Block3856b092011-10-20 11:56:00 +01008826 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008827 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008828 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829
Eric Laurentdb7c0792011-08-10 10:37:50 -07008830 if (!mEnabled) {
8831 return NO_ERROR;
8832 }
Eric Laurent59255e42011-07-27 19:49:51 -07008833 mEnabled = false;
8834
8835 if (mEffect->suspended()) {
8836 return NO_ERROR;
8837 }
8838
8839 status_t status = mEffect->setEnabled(false);
8840
8841 sp<ThreadBase> thread = mEffect->thread().promote();
8842 if (thread != 0) {
8843 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8844 }
8845
8846 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008847}
8848
8849void AudioFlinger::EffectHandle::disconnect()
8850{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008851 disconnect(true);
8852}
8853
Glenn Kasten58123c32012-02-03 10:32:24 -08008854void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008855{
Glenn Kasten58123c32012-02-03 10:32:24 -08008856 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857 if (mEffect == 0) {
8858 return;
8859 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008860 // restore suspended effects if the disconnected handle was enabled and the last one.
8861 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008862 sp<ThreadBase> thread = mEffect->thread().promote();
8863 if (thread != 0) {
8864 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8865 }
Eric Laurent59255e42011-07-27 19:49:51 -07008866 }
8867
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868 // release sp on module => module destructor can be called now
8869 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008870 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008871 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008872 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008873 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8874 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008875 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008876 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8878 mClient.clear();
8879 }
8880}
8881
Eric Laurent25f43952010-07-28 05:40:18 -07008882status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8883 uint32_t cmdSize,
8884 void *pCmdData,
8885 uint32_t *replySize,
8886 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887{
Steve Block3856b092011-10-20 11:56:00 +01008888// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008889// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890
8891 // only get parameter command is permitted for applications not controlling the effect
8892 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8893 return INVALID_OPERATION;
8894 }
8895 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008896 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008897
8898 // handle commands that are not forwarded transparently to effect engine
8899 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8900 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8901 // no risk to block the whole media server process or mixer threads is we are stuck here
8902 Mutex::Autolock _l(mCblk->lock);
8903 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8904 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8905 mCblk->serverIndex = 0;
8906 mCblk->clientIndex = 0;
8907 return BAD_VALUE;
8908 }
8909 status_t status = NO_ERROR;
8910 while (mCblk->serverIndex < mCblk->clientIndex) {
8911 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008912 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008913 int *p = (int *)(mBuffer + mCblk->serverIndex);
8914 int size = *p++;
8915 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008916 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917 break;
8918 }
8919 effect_param_t *param = (effect_param_t *)p;
8920 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008921 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922 mCblk->serverIndex += size;
8923 continue;
8924 }
Eric Laurent25f43952010-07-28 05:40:18 -07008925 uint32_t psize = sizeof(effect_param_t) +
8926 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8927 param->vsize;
8928 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8929 psize,
8930 p,
8931 &rsize,
8932 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008933 // stop at first error encountered
8934 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008936 *(int *)pReplyData = reply;
8937 break;
8938 } else if (reply != NO_ERROR) {
8939 *(int *)pReplyData = reply;
8940 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008941 }
8942 mCblk->serverIndex += size;
8943 }
8944 mCblk->serverIndex = 0;
8945 mCblk->clientIndex = 0;
8946 return status;
8947 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008948 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949 return enable();
8950 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008951 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952 return disable();
8953 }
8954
8955 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8956}
8957
Eric Laurent59255e42011-07-27 19:49:51 -07008958void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959{
Steve Block3856b092011-10-20 11:56:00 +01008960 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008961
8962 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008963 mEnabled = enabled;
8964
Mathias Agopian65ab4712010-07-14 17:59:35 -07008965 if (signal && mEffectClient != 0) {
8966 mEffectClient->controlStatusChanged(hasControl);
8967 }
8968}
8969
Eric Laurent25f43952010-07-28 05:40:18 -07008970void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8971 uint32_t cmdSize,
8972 void *pCmdData,
8973 uint32_t replySize,
8974 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975{
8976 if (mEffectClient != 0) {
8977 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8978 }
8979}
8980
8981
8982
8983void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8984{
8985 if (mEffectClient != 0) {
8986 mEffectClient->enableStatusChanged(enabled);
8987 }
8988}
8989
8990status_t AudioFlinger::EffectHandle::onTransact(
8991 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8992{
8993 return BnEffect::onTransact(code, data, reply, flags);
8994}
8995
8996
8997void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8998{
Glenn Kastena0d68332012-01-27 16:47:15 -08008999 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009000
9001 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009002 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003 mPriority,
9004 mHasControl,
9005 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009006 mCblk ? mCblk->clientIndex : 0,
9007 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 );
9009
9010 if (locked) {
9011 mCblk->lock.unlock();
9012 }
9013}
9014
9015#undef LOG_TAG
9016#define LOG_TAG "AudioFlinger::EffectChain"
9017
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009018AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009020 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009021 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9022 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023{
Dima Zavinfce7a472011-04-19 22:30:36 -07009024 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009025 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009026 return;
9027 }
9028 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9029 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030}
9031
9032AudioFlinger::EffectChain::~EffectChain()
9033{
9034 if (mOwnInBuffer) {
9035 delete mInBuffer;
9036 }
9037
9038}
9039
Eric Laurent59255e42011-07-27 19:49:51 -07009040// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009041sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009043 size_t size = mEffects.size();
9044
9045 for (size_t i = 0; i < size; i++) {
9046 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009047 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009048 }
9049 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009050 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051}
9052
Eric Laurent59255e42011-07-27 19:49:51 -07009053// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009054sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056 size_t size = mEffects.size();
9057
9058 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009059 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9060 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009061 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 }
9063 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009064 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009065}
9066
Eric Laurent59255e42011-07-27 19:49:51 -07009067// getEffectFromType_l() must be called with ThreadBase::mLock held
9068sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9069 const effect_uuid_t *type)
9070{
Eric Laurent59255e42011-07-27 19:49:51 -07009071 size_t size = mEffects.size();
9072
9073 for (size_t i = 0; i < size; i++) {
9074 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009075 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009076 }
9077 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009078 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009079}
9080
Eric Laurent91b14c42012-05-30 12:30:29 -07009081void AudioFlinger::EffectChain::clearInputBuffer()
9082{
9083 Mutex::Autolock _l(mLock);
9084 sp<ThreadBase> thread = mThread.promote();
9085 if (thread == 0) {
9086 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9087 return;
9088 }
9089 clearInputBuffer_l(thread);
9090}
9091
9092// Must be called with EffectChain::mLock locked
9093void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9094{
9095 size_t numSamples = thread->frameCount() * thread->channelCount();
9096 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9097
9098}
9099
Mathias Agopian65ab4712010-07-14 17:59:35 -07009100// Must be called with EffectChain::mLock locked
9101void AudioFlinger::EffectChain::process_l()
9102{
Eric Laurentdac69112010-09-28 14:09:57 -07009103 sp<ThreadBase> thread = mThread.promote();
9104 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009105 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009106 return;
9107 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009108 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9109 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009110 // always process effects unless no more tracks are on the session and the effect tail
9111 // has been rendered
9112 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009113 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009114 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009115
Eric Laurent544fe9b2011-11-11 15:42:52 -08009116 if (!tracksOnSession && mTailBufferCount == 0) {
9117 doProcess = false;
9118 }
9119
9120 if (activeTrackCnt() == 0) {
9121 // if no track is active and the effect tail has not been rendered,
9122 // the input buffer must be cleared here as the mixer process will not do it
9123 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009124 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009125 if (mTailBufferCount > 0) {
9126 mTailBufferCount--;
9127 }
9128 }
9129 }
Eric Laurentdac69112010-09-28 14:09:57 -07009130 }
9131
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009133 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009134 for (size_t i = 0; i < size; i++) {
9135 mEffects[i]->process();
9136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009137 }
9138 for (size_t i = 0; i < size; i++) {
9139 mEffects[i]->updateState();
9140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009141}
9142
Eric Laurentcab11242010-07-15 12:50:15 -07009143// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009144status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009145{
9146 effect_descriptor_t desc = effect->desc();
9147 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9148
9149 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009150 effect->setChain(this);
9151 sp<ThreadBase> thread = mThread.promote();
9152 if (thread == 0) {
9153 return NO_INIT;
9154 }
9155 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009156
9157 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9158 // Auxiliary effects are inserted at the beginning of mEffects vector as
9159 // they are processed first and accumulated in chain input buffer
9160 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009161
Mathias Agopian65ab4712010-07-14 17:59:35 -07009162 // the input buffer for auxiliary effect contains mono samples in
9163 // 32 bit format. This is to avoid saturation in AudoMixer
9164 // accumulation stage. Saturation is done in EffectModule::process() before
9165 // calling the process in effect engine
9166 size_t numSamples = thread->frameCount();
9167 int32_t *buffer = new int32_t[numSamples];
9168 memset(buffer, 0, numSamples * sizeof(int32_t));
9169 effect->setInBuffer((int16_t *)buffer);
9170 // auxiliary effects output samples to chain input buffer for further processing
9171 // by insert effects
9172 effect->setOutBuffer(mInBuffer);
9173 } else {
9174 // Insert effects are inserted at the end of mEffects vector as they are processed
9175 // after track and auxiliary effects.
9176 // Insert effect order as a function of indicated preference:
9177 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9178 // another effect is present
9179 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9180 // last effect claiming first position
9181 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9182 // first effect claiming last position
9183 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9184 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9185 // already present
9186
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009187 size_t size = mEffects.size();
9188 size_t idx_insert = size;
9189 ssize_t idx_insert_first = -1;
9190 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009191
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009192 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009193 effect_descriptor_t d = mEffects[i]->desc();
9194 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9195 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9196 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9197 // check invalid effect chaining combinations
9198 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9199 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009200 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201 return INVALID_OPERATION;
9202 }
9203 // remember position of first insert effect and by default
9204 // select this as insert position for new effect
9205 if (idx_insert == size) {
9206 idx_insert = i;
9207 }
9208 // remember position of last insert effect claiming
9209 // first position
9210 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9211 idx_insert_first = i;
9212 }
9213 // remember position of first insert effect claiming
9214 // last position
9215 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9216 idx_insert_last == -1) {
9217 idx_insert_last = i;
9218 }
9219 }
9220 }
9221
9222 // modify idx_insert from first position if needed
9223 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9224 if (idx_insert_last != -1) {
9225 idx_insert = idx_insert_last;
9226 } else {
9227 idx_insert = size;
9228 }
9229 } else {
9230 if (idx_insert_first != -1) {
9231 idx_insert = idx_insert_first + 1;
9232 }
9233 }
9234
9235 // always read samples from chain input buffer
9236 effect->setInBuffer(mInBuffer);
9237
9238 // if last effect in the chain, output samples to chain
9239 // output buffer, otherwise to chain input buffer
9240 if (idx_insert == size) {
9241 if (idx_insert != 0) {
9242 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9243 mEffects[idx_insert-1]->configure();
9244 }
9245 effect->setOutBuffer(mOutBuffer);
9246 } else {
9247 effect->setOutBuffer(mInBuffer);
9248 }
9249 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009250
Steve Block3856b092011-10-20 11:56:00 +01009251 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 }
9253 effect->configure();
9254 return NO_ERROR;
9255}
9256
Eric Laurentcab11242010-07-15 12:50:15 -07009257// removeEffect_l() must be called with PlaybackThread::mLock held
9258size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009259{
9260 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009261 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009262 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9263
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009264 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009265 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009266 // calling stop here will remove pre-processing effect from the audio HAL.
9267 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9268 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009269 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9270 mEffects[i]->state() == EffectModule::STOPPING) {
9271 mEffects[i]->stop();
9272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9274 delete[] effect->inBuffer();
9275 } else {
9276 if (i == size - 1 && i != 0) {
9277 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9278 mEffects[i - 1]->configure();
9279 }
9280 }
9281 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009282 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009283 break;
9284 }
9285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009286
9287 return mEffects.size();
9288}
9289
Eric Laurentcab11242010-07-15 12:50:15 -07009290// setDevice_l() must be called with PlaybackThread::mLock held
9291void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009292{
9293 size_t size = mEffects.size();
9294 for (size_t i = 0; i < size; i++) {
9295 mEffects[i]->setDevice(device);
9296 }
9297}
9298
Eric Laurentcab11242010-07-15 12:50:15 -07009299// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009300void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009301{
9302 size_t size = mEffects.size();
9303 for (size_t i = 0; i < size; i++) {
9304 mEffects[i]->setMode(mode);
9305 }
9306}
9307
Eric Laurentcab11242010-07-15 12:50:15 -07009308// setVolume_l() must be called with PlaybackThread::mLock held
9309bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009310{
9311 uint32_t newLeft = *left;
9312 uint32_t newRight = *right;
9313 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009314 int ctrlIdx = -1;
9315 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009316
Eric Laurentcab11242010-07-15 12:50:15 -07009317 // first update volume controller
9318 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009319 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009320 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9321 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009322 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009323 break;
9324 }
9325 }
9326
9327 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009328 if (hasControl) {
9329 *left = mNewLeftVolume;
9330 *right = mNewRightVolume;
9331 }
9332 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009333 }
9334
9335 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009336 mLeftVolume = newLeft;
9337 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009338
9339 // second get volume update from volume controller
9340 if (ctrlIdx >= 0) {
9341 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009342 mNewLeftVolume = newLeft;
9343 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009344 }
9345 // then indicate volume to all other effects in chain.
9346 // Pass altered volume to effects before volume controller
9347 // and requested volume to effects after controller
9348 uint32_t lVol = newLeft;
9349 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009350
Mathias Agopian65ab4712010-07-14 17:59:35 -07009351 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009352 if ((int)i == ctrlIdx) continue;
9353 // this also works for ctrlIdx == -1 when there is no volume controller
9354 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 lVol = *left;
9356 rVol = *right;
9357 }
9358 mEffects[i]->setVolume(&lVol, &rVol, false);
9359 }
9360 *left = newLeft;
9361 *right = newRight;
9362
9363 return hasControl;
9364}
9365
Mathias Agopian65ab4712010-07-14 17:59:35 -07009366status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9367{
9368 const size_t SIZE = 256;
9369 char buffer[SIZE];
9370 String8 result;
9371
9372 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9373 result.append(buffer);
9374
9375 bool locked = tryLock(mLock);
9376 // failed to lock - AudioFlinger is probably deadlocked
9377 if (!locked) {
9378 result.append("\tCould not lock mutex:\n");
9379 }
9380
Eric Laurentcab11242010-07-15 12:50:15 -07009381 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9382 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383 mEffects.size(),
9384 (uint32_t)mInBuffer,
9385 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009386 mActiveTrackCnt);
9387 result.append(buffer);
9388 write(fd, result.string(), result.size());
9389
9390 for (size_t i = 0; i < mEffects.size(); ++i) {
9391 sp<EffectModule> effect = mEffects[i];
9392 if (effect != 0) {
9393 effect->dump(fd, args);
9394 }
9395 }
9396
9397 if (locked) {
9398 mLock.unlock();
9399 }
9400
9401 return NO_ERROR;
9402}
9403
Eric Laurent59255e42011-07-27 19:49:51 -07009404// must be called with ThreadBase::mLock held
9405void AudioFlinger::EffectChain::setEffectSuspended_l(
9406 const effect_uuid_t *type, bool suspend)
9407{
9408 sp<SuspendedEffectDesc> desc;
9409 // use effect type UUID timelow as key as there is no real risk of identical
9410 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009411 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009412 if (suspend) {
9413 if (index >= 0) {
9414 desc = mSuspendedEffects.valueAt(index);
9415 } else {
9416 desc = new SuspendedEffectDesc();
9417 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9418 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009419 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009420 }
9421 if (desc->mRefCount++ == 0) {
9422 sp<EffectModule> effect = getEffectIfEnabled(type);
9423 if (effect != 0) {
9424 desc->mEffect = effect;
9425 effect->setSuspended(true);
9426 effect->setEnabled(false);
9427 }
9428 }
9429 } else {
9430 if (index < 0) {
9431 return;
9432 }
9433 desc = mSuspendedEffects.valueAt(index);
9434 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009435 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009436 desc->mRefCount = 1;
9437 }
9438 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009439 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009440 if (desc->mEffect != 0) {
9441 sp<EffectModule> effect = desc->mEffect.promote();
9442 if (effect != 0) {
9443 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009444 effect->lock();
9445 EffectHandle *handle = effect->controlHandle_l();
9446 if (handle != NULL && !handle->destroyed_l()) {
9447 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009448 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009449 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009450 }
9451 desc->mEffect.clear();
9452 }
9453 mSuspendedEffects.removeItemsAt(index);
9454 }
9455 }
9456}
9457
9458// must be called with ThreadBase::mLock held
9459void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9460{
9461 sp<SuspendedEffectDesc> desc;
9462
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009463 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009464 if (suspend) {
9465 if (index >= 0) {
9466 desc = mSuspendedEffects.valueAt(index);
9467 } else {
9468 desc = new SuspendedEffectDesc();
9469 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009470 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009471 }
9472 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009473 Vector< sp<EffectModule> > effects;
9474 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009475 for (size_t i = 0; i < effects.size(); i++) {
9476 setEffectSuspended_l(&effects[i]->desc().type, true);
9477 }
9478 }
9479 } else {
9480 if (index < 0) {
9481 return;
9482 }
9483 desc = mSuspendedEffects.valueAt(index);
9484 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009485 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009486 desc->mRefCount = 1;
9487 }
9488 if (--desc->mRefCount == 0) {
9489 Vector<const effect_uuid_t *> types;
9490 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9491 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9492 continue;
9493 }
9494 types.add(&mSuspendedEffects.valueAt(i)->mType);
9495 }
9496 for (size_t i = 0; i < types.size(); i++) {
9497 setEffectSuspended_l(types[i], false);
9498 }
Steve Block3856b092011-10-20 11:56:00 +01009499 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009500 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9501 }
9502 }
9503}
9504
Eric Laurent6bffdb82011-09-23 08:40:41 -07009505
9506// The volume effect is used for automated tests only
9507#ifndef OPENSL_ES_H_
9508static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9509 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9510const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9511#endif //OPENSL_ES_H_
9512
Eric Laurentdb7c0792011-08-10 10:37:50 -07009513bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9514{
9515 // auxiliary effects and visualizer are never suspended on output mix
9516 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9517 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009518 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9519 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009520 return false;
9521 }
9522 return true;
9523}
9524
Glenn Kastend0539712012-01-30 12:56:03 -08009525void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009526{
Glenn Kastend0539712012-01-30 12:56:03 -08009527 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009528 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009529 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9530 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009531 }
Eric Laurent59255e42011-07-27 19:49:51 -07009532 }
Eric Laurent59255e42011-07-27 19:49:51 -07009533}
9534
9535sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9536 const effect_uuid_t *type)
9537{
Glenn Kasten090f0192012-01-30 13:00:02 -08009538 sp<EffectModule> effect = getEffectFromType_l(type);
9539 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009540}
9541
9542void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9543 bool enabled)
9544{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009545 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009546 if (enabled) {
9547 if (index < 0) {
9548 // if the effect is not suspend check if all effects are suspended
9549 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9550 if (index < 0) {
9551 return;
9552 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009553 if (!isEffectEligibleForSuspend(effect->desc())) {
9554 return;
9555 }
Eric Laurent59255e42011-07-27 19:49:51 -07009556 setEffectSuspended_l(&effect->desc().type, enabled);
9557 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009558 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009559 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009560 return;
9561 }
Eric Laurent59255e42011-07-27 19:49:51 -07009562 }
Steve Block3856b092011-10-20 11:56:00 +01009563 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009564 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009565 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9566 // if effect is requested to suspended but was not yet enabled, supend it now.
9567 if (desc->mEffect == 0) {
9568 desc->mEffect = effect;
9569 effect->setEnabled(false);
9570 effect->setSuspended(true);
9571 }
9572 } else {
9573 if (index < 0) {
9574 return;
9575 }
Steve Block3856b092011-10-20 11:56:00 +01009576 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009577 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009578 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9579 desc->mEffect.clear();
9580 effect->setSuspended(false);
9581 }
9582}
9583
Mathias Agopian65ab4712010-07-14 17:59:35 -07009584#undef LOG_TAG
9585#define LOG_TAG "AudioFlinger"
9586
9587// ----------------------------------------------------------------------------
9588
9589status_t AudioFlinger::onTransact(
9590 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9591{
9592 return BnAudioFlinger::onTransact(code, data, reply, flags);
9593}
9594
Mathias Agopian65ab4712010-07-14 17:59:35 -07009595}; // namespace android