blob: aab998493cb5e2f26f84e0f07774e64b3209e9ec [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);
911 if (thread == NULL) {
912 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800913 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700914 // indicate output device change to all input threads for pre processing
915 AudioParameter param = AudioParameter(keyValuePairs);
916 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700917 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
918 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700919 for (size_t i = 0; i < mRecordThreads.size(); i++) {
920 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
921 }
922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923 }
924 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800925 if (thread != 0) {
926 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 }
928 return BAD_VALUE;
929}
930
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800931String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800933// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
935
Eric Laurenta4c5a552012-03-29 10:12:40 -0700936 Mutex::Autolock _l(mLock);
937
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700939 String8 out_s8;
940
Dima Zavin799a70e2011-04-18 16:57:27 -0700941 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800942 char *s;
943 {
944 AutoMutex lock(mHardwareLock);
945 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700946 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800947 s = dev->get_parameters(dev, keys.string());
948 mHardwareStatus = AUDIO_HW_IDLE;
949 }
John Grossmanef7740b2012-02-09 11:28:36 -0800950 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700951 free(s);
952 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700953 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 }
955
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
957 if (playbackThread != NULL) {
958 return playbackThread->getParameters(keys);
959 }
960 RecordThread *recordThread = checkRecordThread_l(ioHandle);
961 if (recordThread != NULL) {
962 return recordThread->getParameters(keys);
963 }
964 return String8("");
965}
966
Glenn Kastenf587ba52012-01-26 16:25:10 -0800967size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700968{
Eric Laurenta1884f92011-08-23 08:25:03 -0700969 status_t ret = initCheck();
970 if (ret != NO_ERROR) {
971 return 0;
972 }
973
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800974 AutoMutex lock(mHardwareLock);
975 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700976 struct audio_config config = {
977 sample_rate: sampleRate,
978 channel_mask: audio_channel_in_mask_from_count(channelCount),
979 format: format,
980 };
981 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800982 mHardwareStatus = AUDIO_HW_IDLE;
983 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984}
985
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800986unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
988 if (ioHandle == 0) {
989 return 0;
990 }
991
992 Mutex::Autolock _l(mLock);
993
994 RecordThread *recordThread = checkRecordThread_l(ioHandle);
995 if (recordThread != NULL) {
996 return recordThread->getInputFramesLost();
997 }
998 return 0;
999}
1000
1001status_t AudioFlinger::setVoiceVolume(float value)
1002{
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 status_t ret = initCheck();
1004 if (ret != NO_ERROR) {
1005 return ret;
1006 }
1007
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 // check calling permissions
1009 if (!settingsAllowed()) {
1010 return PERMISSION_DENIED;
1011 }
1012
1013 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001014 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001015 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 mHardwareStatus = AUDIO_HW_IDLE;
1017
1018 return ret;
1019}
1020
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001021status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1022 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023{
1024 status_t status;
1025
1026 Mutex::Autolock _l(mLock);
1027
1028 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1029 if (playbackThread != NULL) {
1030 return playbackThread->getRenderPosition(halFrames, dspFrames);
1031 }
1032
1033 return BAD_VALUE;
1034}
1035
1036void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1037{
1038
1039 Mutex::Autolock _l(mLock);
1040
Glenn Kastenbb001922012-02-03 11:10:26 -08001041 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 if (mNotificationClients.indexOfKey(pid) < 0) {
1043 sp<NotificationClient> notificationClient = new NotificationClient(this,
1044 client,
1045 pid);
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
1048 mNotificationClients.add(pid, notificationClient);
1049
1050 sp<IBinder> binder = client->asBinder();
1051 binder->linkToDeath(notificationClient);
1052
1053 // the config change is always sent from playback or record threads to avoid deadlock
1054 // with AudioSystem::gLock
1055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1056 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1057 }
1058
1059 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1060 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1061 }
1062 }
1063}
1064
1065void AudioFlinger::removeNotificationClient(pid_t pid)
1066{
1067 Mutex::Autolock _l(mLock);
1068
Glenn Kastena3b09252012-01-20 09:19:01 -08001069 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001072 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001074 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001076 ALOGV(" pid %d @ %d", ref->mPid, i);
1077 if (ref->mPid == pid) {
1078 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079 mAudioSessionRefs.removeAt(i);
1080 delete ref;
1081 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 } else {
1084 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001085 }
1086 }
1087 if (removed) {
1088 purgeStaleEffects_l();
1089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090}
1091
1092// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001093void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
1095 size_t size = mNotificationClients.size();
1096 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001097 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1098 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 }
1100}
1101
1102// removeClient_l() must be called with AudioFlinger::mLock held
1103void AudioFlinger::removeClient_l(pid_t pid)
1104{
Steve Block3856b092011-10-20 11:56:00 +01001105 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 mClients.removeItem(pid);
1107}
1108
Eric Laurent717e1282012-06-29 16:36:52 -07001109// getEffectThread_l() must be called with AudioFlinger::mLock held
1110sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1111{
1112 sp<PlaybackThread> thread;
1113
1114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1115 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1116 ALOG_ASSERT(thread == 0);
1117 thread = mPlaybackThreads.valueAt(i);
1118 }
1119 }
1120
1121 return thread;
1122}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123
1124// ----------------------------------------------------------------------------
1125
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001126AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1127 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001129 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001130 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001131 // mChannelMask
1132 mChannelCount(0),
1133 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1134 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001135 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001136 mDevice(device),
1137 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138{
1139}
1140
1141AudioFlinger::ThreadBase::~ThreadBase()
1142{
1143 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001144 // do not lock the mutex in destructor
1145 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001146 if (mPowerManager != 0) {
1147 sp<IBinder> binder = mPowerManager->asBinder();
1148 binder->unlinkToDeath(mDeathRecipient);
1149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150}
1151
1152void AudioFlinger::ThreadBase::exit()
1153{
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001156 // This lock prevents the following race in thread (uniprocessor for illustration):
1157 // if (!exitPending()) {
1158 // // context switch from here to exit()
1159 // // exit() calls requestExit(), what exitPending() observes
1160 // // exit() calls signal(), which is dropped since no waiters
1161 // // context switch back from exit() to here
1162 // mWaitWorkCV.wait(...);
1163 // // now thread is hung
1164 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001165 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 requestExit();
1167 mWaitWorkCV.signal();
1168 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001169 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1170 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 requestExitAndWait();
1172}
1173
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1175{
1176 status_t status;
1177
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 Mutex::Autolock _l(mLock);
1180
1181 mNewParameters.add(keyValuePairs);
1182 mWaitWorkCV.signal();
1183 // wait condition with timeout in case the thread loop has exited
1184 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001185 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 status = mParamStatus;
1187 mWaitWorkCV.signal();
1188 } else {
1189 status = TIMED_OUT;
1190 }
1191 return status;
1192}
1193
1194void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1195{
1196 Mutex::Autolock _l(mLock);
1197 sendConfigEvent_l(event, param);
1198}
1199
1200// sendConfigEvent_l() must be called with ThreadBase::mLock held
1201void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1202{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001203 ConfigEvent configEvent;
1204 configEvent.mEvent = event;
1205 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 mWaitWorkCV.signal();
1209}
1210
1211void AudioFlinger::ThreadBase::processConfigEvents()
1212{
1213 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001214 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001215 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001216 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mConfigEvents.removeAt(0);
1218 // release mLock before locking AudioFlinger mLock: lock order is always
1219 // AudioFlinger then ThreadBase to avoid cross deadlock
1220 mLock.unlock();
1221 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001222 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mLock.lock();
1225 }
1226 mLock.unlock();
1227}
1228
1229status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1230{
1231 const size_t SIZE = 256;
1232 char buffer[SIZE];
1233 String8 result;
1234
1235 bool locked = tryLock(mLock);
1236 if (!locked) {
1237 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1238 write(fd, buffer, strlen(buffer));
1239 }
1240
Eric Laurent612bbb52012-03-14 15:03:26 -07001241 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1244 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1248 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001249 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1250 result.append(buffer);
1251 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 result.append(buffer);
1253 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1254 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001255 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1256 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1258 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001259 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 result.append(buffer);
1261
1262 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1263 result.append(buffer);
1264 result.append(" Index Command");
1265 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1266 snprintf(buffer, SIZE, "\n %02d ", i);
1267 result.append(buffer);
1268 result.append(mNewParameters[i]);
1269 }
1270
1271 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1272 result.append(buffer);
1273 snprintf(buffer, SIZE, " Index event param\n");
1274 result.append(buffer);
1275 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001276 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277 result.append(buffer);
1278 }
1279 result.append("\n");
1280
1281 write(fd, result.string(), result.size());
1282
1283 if (locked) {
1284 mLock.unlock();
1285 }
1286 return NO_ERROR;
1287}
1288
Eric Laurent1d2bff02011-07-24 17:49:51 -07001289status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1290{
1291 const size_t SIZE = 256;
1292 char buffer[SIZE];
1293 String8 result;
1294
1295 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1296 write(fd, buffer, strlen(buffer));
1297
1298 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1299 sp<EffectChain> chain = mEffectChains[i];
1300 if (chain != 0) {
1301 chain->dump(fd, args);
1302 }
1303 }
1304 return NO_ERROR;
1305}
1306
Eric Laurentfeb0db62011-07-22 09:04:31 -07001307void AudioFlinger::ThreadBase::acquireWakeLock()
1308{
1309 Mutex::Autolock _l(mLock);
1310 acquireWakeLock_l();
1311}
1312
1313void AudioFlinger::ThreadBase::acquireWakeLock_l()
1314{
1315 if (mPowerManager == 0) {
1316 // use checkService() to avoid blocking if power service is not up yet
1317 sp<IBinder> binder =
1318 defaultServiceManager()->checkService(String16("power"));
1319 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001320 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001321 } else {
1322 mPowerManager = interface_cast<IPowerManager>(binder);
1323 binder->linkToDeath(mDeathRecipient);
1324 }
1325 }
1326 if (mPowerManager != 0) {
1327 sp<IBinder> binder = new BBinder();
1328 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1329 binder,
1330 String16(mName));
1331 if (status == NO_ERROR) {
1332 mWakeLockToken = binder;
1333 }
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001335 }
1336}
1337
1338void AudioFlinger::ThreadBase::releaseWakeLock()
1339{
1340 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001341 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001342}
1343
1344void AudioFlinger::ThreadBase::releaseWakeLock_l()
1345{
1346 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001347 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001348 if (mPowerManager != 0) {
1349 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1350 }
1351 mWakeLockToken.clear();
1352 }
1353}
1354
1355void AudioFlinger::ThreadBase::clearPowerManager()
1356{
1357 Mutex::Autolock _l(mLock);
1358 releaseWakeLock_l();
1359 mPowerManager.clear();
1360}
1361
1362void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1363{
1364 sp<ThreadBase> thread = mThread.promote();
1365 if (thread != 0) {
1366 thread->clearPowerManager();
1367 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001368 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001369}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001370
Eric Laurent59255e42011-07-27 19:49:51 -07001371void AudioFlinger::ThreadBase::setEffectSuspended(
1372 const effect_uuid_t *type, bool suspend, int sessionId)
1373{
1374 Mutex::Autolock _l(mLock);
1375 setEffectSuspended_l(type, suspend, sessionId);
1376}
1377
1378void AudioFlinger::ThreadBase::setEffectSuspended_l(
1379 const effect_uuid_t *type, bool suspend, int sessionId)
1380{
Glenn Kasten090f0192012-01-30 13:00:02 -08001381 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001382 if (chain != 0) {
1383 if (type != NULL) {
1384 chain->setEffectSuspended_l(type, suspend);
1385 } else {
1386 chain->setEffectSuspendedAll_l(suspend);
1387 }
1388 }
1389
1390 updateSuspendedSessions_l(type, suspend, sessionId);
1391}
1392
1393void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1394{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001395 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001396 if (index < 0) {
1397 return;
1398 }
1399
1400 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1401 mSuspendedSessions.editValueAt(index);
1402
1403 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001404 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001405 for (int j = 0; j < desc->mRefCount; j++) {
1406 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1407 chain->setEffectSuspendedAll_l(true);
1408 } else {
Steve Block3856b092011-10-20 11:56:00 +01001409 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001410 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001411 chain->setEffectSuspended_l(&desc->mType, true);
1412 }
1413 }
1414 }
1415}
1416
Eric Laurent59255e42011-07-27 19:49:51 -07001417void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1418 bool suspend,
1419 int sessionId)
1420{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001421 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001422
1423 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1424
1425 if (suspend) {
1426 if (index >= 0) {
1427 sessionEffects = mSuspendedSessions.editValueAt(index);
1428 } else {
1429 mSuspendedSessions.add(sessionId, sessionEffects);
1430 }
1431 } else {
1432 if (index < 0) {
1433 return;
1434 }
1435 sessionEffects = mSuspendedSessions.editValueAt(index);
1436 }
1437
1438
1439 int key = EffectChain::kKeyForSuspendAll;
1440 if (type != NULL) {
1441 key = type->timeLow;
1442 }
1443 index = sessionEffects.indexOfKey(key);
1444
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001445 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001446 if (suspend) {
1447 if (index >= 0) {
1448 desc = sessionEffects.valueAt(index);
1449 } else {
1450 desc = new SuspendedSessionDesc();
1451 if (type != NULL) {
1452 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1453 }
1454 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001455 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001456 }
1457 desc->mRefCount++;
1458 } else {
1459 if (index < 0) {
1460 return;
1461 }
1462 desc = sessionEffects.valueAt(index);
1463 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001464 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001465 sessionEffects.removeItemsAt(index);
1466 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001467 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001468 sessionId);
1469 mSuspendedSessions.removeItem(sessionId);
1470 }
1471 }
1472 }
1473 if (!sessionEffects.isEmpty()) {
1474 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1475 }
1476}
1477
1478void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1479 bool enabled,
1480 int sessionId)
1481{
1482 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001483 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1484}
Eric Laurent59255e42011-07-27 19:49:51 -07001485
Eric Laurenta85a74a2011-10-19 11:44:54 -07001486void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1487 bool enabled,
1488 int sessionId)
1489{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001490 if (mType != RECORD) {
1491 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1492 // another session. This gives the priority to well behaved effect control panels
1493 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001494 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1495 // global effects
1496 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001497 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1498 }
1499 }
Eric Laurent59255e42011-07-27 19:49:51 -07001500
1501 sp<EffectChain> chain = getEffectChain_l(sessionId);
1502 if (chain != 0) {
1503 chain->checkSuspendOnEffectEnabled(effect, enabled);
1504 }
1505}
1506
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507// ----------------------------------------------------------------------------
1508
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001509AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1510 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001511 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001512 uint32_t device,
1513 type_t type)
1514 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001515 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1516 // Assumes constructor is called by AudioFlinger with it's mLock held,
1517 // but it would be safer to explicitly pass initial masterMute as parameter
1518 mMasterMute(audioFlinger->masterMute_l()),
1519 // mStreamTypes[] initialized in constructor body
1520 mOutput(output),
1521 // Assumes constructor is called by AudioFlinger with it's mLock held,
1522 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001523 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001524 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001525 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001526 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001527 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001528 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001529 // index 0 is reserved for normal mixer's submix
1530 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531{
Glenn Kasten480b4682012-02-28 12:30:08 -08001532 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001533
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 readOutputParameters();
1535
Glenn Kasten263709e2012-01-06 08:40:01 -08001536 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001537 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1538 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1539 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001540 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1541 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001543 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1544 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545}
1546
1547AudioFlinger::PlaybackThread::~PlaybackThread()
1548{
1549 delete [] mMixBuffer;
1550}
1551
1552status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1553{
1554 dumpInternals(fd, args);
1555 dumpTracks(fd, args);
1556 dumpEffectChains(fd, args);
1557 return NO_ERROR;
1558}
1559
1560status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1561{
1562 const size_t SIZE = 256;
1563 char buffer[SIZE];
1564 String8 result;
1565
Glenn Kasten58912562012-04-03 10:45:00 -07001566 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1567 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1568 const stream_type_t *st = &mStreamTypes[i];
1569 if (i > 0) {
1570 result.appendFormat(", ");
1571 }
1572 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1573 if (st->mute) {
1574 result.append("M");
1575 }
1576 }
1577 result.append("\n");
1578 write(fd, result.string(), result.length());
1579 result.clear();
1580
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1582 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001583 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 for (size_t i = 0; i < mTracks.size(); ++i) {
1585 sp<Track> track = mTracks[i];
1586 if (track != 0) {
1587 track->dump(buffer, SIZE);
1588 result.append(buffer);
1589 }
1590 }
1591
1592 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1593 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001594 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001596 sp<Track> track = mActiveTracks[i].promote();
1597 if (track != 0) {
1598 track->dump(buffer, SIZE);
1599 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 }
1601 }
1602 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001603
1604 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1605 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1606 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1607 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1608
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 return NO_ERROR;
1610}
1611
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1613{
1614 const size_t SIZE = 256;
1615 char buffer[SIZE];
1616 String8 result;
1617
1618 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1623 result.append(buffer);
1624 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1625 result.append(buffer);
1626 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1627 result.append(buffer);
1628 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1629 result.append(buffer);
1630 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1631 result.append(buffer);
1632 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001633 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634
1635 dumpBase(fd, args);
1636
1637 return NO_ERROR;
1638}
1639
1640// Thread virtuals
1641status_t AudioFlinger::PlaybackThread::readyToRun()
1642{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001643 status_t status = initCheck();
1644 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001645 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001646 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001647 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001649 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650}
1651
1652void AudioFlinger::PlaybackThread::onFirstRef()
1653{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001654 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655}
1656
1657// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001658sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001660 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001662 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001663 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 int frameCount,
1665 const sp<IMemory>& sharedBuffer,
1666 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001668 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 status_t *status)
1670{
1671 sp<Track> track;
1672 status_t lStatus;
1673
Glenn Kasten73d22752012-03-19 13:38:30 -07001674 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1675
1676 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 if (flags & IAudioFlinger::TRACK_FAST) {
1678 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 // not timed
1680 (!isTimed) &&
1681 // either of these use cases:
1682 (
1683 // use case 1: shared buffer with any frame count
1684 (
1685 (sharedBuffer != 0)
1686 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001687 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001688 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001689 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001691 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001692 )
1693 ) &&
1694 // PCM data
1695 audio_is_linear_pcm(format) &&
1696 // mono or stereo
1697 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1698 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001699#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001700 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001701 (sampleRate == mSampleRate) &&
1702#endif
1703 // normal mixer has an associated fast mixer
1704 hasFastMixer() &&
1705 // there are sufficient fast track slots available
1706 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001707 // FIXME test that MixerThread for this fast track has a capable output HAL
1708 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001709 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1711 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001712 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001713 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001714 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001715 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001716 } else {
Glenn Kasten362ebcb2012-05-24 08:44:00 -07001717 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001718 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1719 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1720 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1721 audio_is_linear_pcm(format),
1722 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001723 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001724 // For compatibility with AudioTrack calculation, buffer depth is forced
1725 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1726 // This is probably too conservative, but legacy application code may depend on it.
1727 // If you change this calculation, also review the start threshold which is related.
1728 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1729 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1730 if (minBufCount < 2) {
1731 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001732 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001733 int minFrameCount = mNormalFrameCount * minBufCount;
1734 if (frameCount < minFrameCount) {
1735 frameCount = minFrameCount;
1736 }
1737 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001738 }
1739
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001741 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1742 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001743 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001744 "for output %p with format %d",
1745 sampleRate, format, channelMask, mOutput, mFormat);
1746 lStatus = BAD_VALUE;
1747 goto Exit;
1748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 }
1750 } else {
1751 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1752 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001753 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 lStatus = BAD_VALUE;
1755 goto Exit;
1756 }
1757 }
1758
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001759 lStatus = initCheck();
1760 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001761 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 goto Exit;
1763 }
1764
1765 { // scope for mLock
1766 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001767
1768 // all tracks in same audio session must share the same routing strategy otherwise
1769 // conflicts will happen when tracks are moved from one output to another by audio policy
1770 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001771 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001772 for (size_t i = 0; i < mTracks.size(); ++i) {
1773 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001774 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001775 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001776 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001777 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001778 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001779 lStatus = BAD_VALUE;
1780 goto Exit;
1781 }
1782 }
1783 }
1784
John Grossman4ff14ba2012-02-08 16:37:41 -08001785 if (!isTimed) {
1786 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001787 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001788 } else {
1789 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1790 channelMask, frameCount, sharedBuffer, sessionId);
1791 }
1792 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 lStatus = NO_MEMORY;
1794 goto Exit;
1795 }
1796 mTracks.add(track);
1797
1798 sp<EffectChain> chain = getEffectChain_l(sessionId);
1799 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001802 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001803 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 }
1805 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001806
1807#ifdef HAVE_REQUEST_PRIORITY
1808 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1809 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1810 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1811 // so ask activity manager to do this on our behalf
1812 int err = requestPriority(callingPid, tid, 1);
1813 if (err != 0) {
1814 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1815 1, callingPid, tid, err);
1816 }
1817 }
1818#endif
1819
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 lStatus = NO_ERROR;
1821
1822Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001823 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 *status = lStatus;
1825 }
1826 return track;
1827}
1828
Eric Laurente737cda2012-05-22 18:55:44 -07001829uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1830{
1831 if (mFastMixer != NULL) {
1832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1833 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1834 }
1835 return latency;
1836}
1837
1838uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1839{
1840 return latency;
1841}
1842
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843uint32_t AudioFlinger::PlaybackThread::latency() const
1844{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001845 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001846 return latency_l();
1847}
1848uint32_t AudioFlinger::PlaybackThread::latency_l() const
1849{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001850 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001851 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001852 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 return 0;
1854 }
1855}
1856
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001859 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861}
1862
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001865 Mutex::Autolock _l(mLock);
1866 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001871 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873}
1874
Glenn Kasten6637baa2012-01-09 09:40:36 -08001875void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001877 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879}
1880
Glenn Kastenfff6d712012-01-12 16:38:12 -08001881float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001883 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 return mStreamTypes[stream].volume;
1885}
1886
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887// addTrack_l() must be called with ThreadBase::mLock held
1888status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1889{
1890 status_t status = ALREADY_EXISTS;
1891
1892 // set retry count for buffer fill
1893 track->mRetryCount = kMaxTrackStartupRetries;
1894 if (mActiveTracks.indexOf(track) < 0) {
1895 // the track is newly added, make sure it fills up all its
1896 // buffers before playing. This is to ensure the client will
1897 // effectively get the latency it requested.
1898 track->mFillingUpStatus = Track::FS_FILLING;
1899 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001900 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 mActiveTracks.add(track);
1902 if (track->mainBuffer() != mMixBuffer) {
1903 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1904 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001905 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001906 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 }
1908 }
1909
1910 status = NO_ERROR;
1911 }
1912
Steve Block3856b092011-10-20 11:56:00 +01001913 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 mWaitWorkCV.broadcast();
1915
1916 return status;
1917}
1918
1919// destroyTrack_l() must be called with ThreadBase::mLock held
1920void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1921{
1922 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001923 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001925 removeTrack_l(track);
1926 }
1927}
1928
1929void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1930{
Eric Laurent29864602012-05-08 18:57:51 -07001931 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001932 mTracks.remove(track);
1933 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001934 // redundant as track is about to be destroyed, for dumpsys only
1935 track->mName = -1;
1936 if (track->isFastTrack()) {
1937 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001938 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1940 mFastTrackAvailMask |= 1 << index;
1941 // redundant as track is about to be destroyed, for dumpsys only
1942 track->mFastIndex = -1;
1943 }
Eric Laurentb469b942011-05-09 12:09:06 -07001944 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1945 if (chain != 0) {
1946 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 }
1948}
1949
1950String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1951{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001952 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001953 char *s;
1954
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001955 Mutex::Autolock _l(mLock);
1956 if (initCheck() != NO_ERROR) {
1957 return out_s8;
1958 }
1959
Dima Zavin799a70e2011-04-18 16:57:27 -07001960 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001961 out_s8 = String8(s);
1962 free(s);
1963 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964}
1965
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001966// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1968 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001969 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970
Steve Block3856b092011-10-20 11:56:00 +01001971 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972
1973 switch (event) {
1974 case AudioSystem::OUTPUT_OPENED:
1975 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001976 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 desc.samplingRate = mSampleRate;
1978 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001979 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 desc.latency = latency();
1981 param2 = &desc;
1982 break;
1983
1984 case AudioSystem::STREAM_CONFIG_CHANGED:
1985 param2 = &param;
1986 case AudioSystem::OUTPUT_CLOSED:
1987 default:
1988 break;
1989 }
1990 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1991}
1992
1993void AudioFlinger::PlaybackThread::readOutputParameters()
1994{
Dima Zavin799a70e2011-04-18 16:57:27 -07001995 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001996 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1997 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001998 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001999 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002000 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002001 if (mFrameCount & 15) {
2002 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2003 mFrameCount);
2004 }
2005
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002006 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002007 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002008 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002009 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002010 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2011 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2012 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2013 maxNormalFrameCount = maxNormalFrameCount & ~15;
2014 if (maxNormalFrameCount < minNormalFrameCount) {
2015 maxNormalFrameCount = minNormalFrameCount;
2016 }
2017 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2018 if (multiplier <= 1.0) {
2019 multiplier = 1.0;
2020 } else if (multiplier <= 2.0) {
2021 if (2 * mFrameCount <= maxNormalFrameCount) {
2022 multiplier = 2.0;
2023 } else {
2024 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2025 }
2026 } else {
2027 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2028 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2029 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2030 // FIXME this rounding up should not be done if no HAL SRC
2031 uint32_t truncMult = (uint32_t) multiplier;
2032 if ((truncMult & 1)) {
2033 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2034 ++truncMult;
2035 }
2036 }
2037 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002038 }
Glenn Kasten58912562012-04-03 10:45:00 -07002039 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002040 mNormalFrameCount = multiplier * mFrameCount;
2041 // round up to nearest 16 frames to satisfy AudioMixer
2042 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002043 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044
Glenn Kastene9dd0172012-01-27 18:08:45 -08002045 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002046 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2047 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048
Eric Laurentde070132010-07-13 04:45:46 -07002049 // force reconfiguration of effect chains and engines to take new buffer size and audio
2050 // parameters into account
2051 // Note that mLock is not held when readOutputParameters() is called from the constructor
2052 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2053 // matter.
2054 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2055 Vector< sp<EffectChain> > effectChains = mEffectChains;
2056 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002057 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059}
2060
Eric Laurente737cda2012-05-22 18:55:44 -07002061
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2063{
Glenn Kastena0d68332012-01-27 16:47:15 -08002064 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 return BAD_VALUE;
2066 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002067 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002068 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 return INVALID_OPERATION;
2070 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002071 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072
Dima Zavin799a70e2011-04-18 16:57:27 -07002073 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074}
2075
Eric Laurent39e94f82010-07-28 01:32:47 -07002076uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077{
2078 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002079 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002081 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 }
2083
2084 for (size_t i = 0; i < mTracks.size(); ++i) {
2085 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002086 if (sessionId == track->sessionId() &&
2087 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002088 result |= TRACK_SESSION;
2089 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 }
2091 }
2092
Eric Laurent39e94f82010-07-28 01:32:47 -07002093 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094}
2095
Eric Laurentde070132010-07-13 04:45:46 -07002096uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2097{
Dima Zavinfce7a472011-04-19 22:30:36 -07002098 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002099 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002100 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2101 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002102 }
2103 for (size_t i = 0; i < mTracks.size(); i++) {
2104 sp<Track> track = mTracks[i];
2105 if (sessionId == track->sessionId() &&
2106 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002107 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002108 }
2109 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002110 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002111}
2112
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113
Glenn Kastenaed850d2012-01-26 09:46:34 -08002114AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002115{
2116 Mutex::Autolock _l(mLock);
2117 return mOutput;
2118}
2119
2120AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2121{
2122 Mutex::Autolock _l(mLock);
2123 AudioStreamOut *output = mOutput;
2124 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002125 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2126 // must push a NULL and wait for ack
2127 mOutputSink.clear();
2128 mPipeSink.clear();
2129 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002130 return output;
2131}
2132
2133// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002134audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002135{
2136 if (mOutput == NULL) {
2137 return NULL;
2138 }
2139 return &mOutput->stream->common;
2140}
2141
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002142uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002143{
Eric Laurentab9071b2012-06-04 13:45:29 -07002144 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002145}
2146
Eric Laurenta011e352012-03-29 15:51:43 -07002147status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2148{
2149 if (!isValidSyncEvent(event)) {
2150 return BAD_VALUE;
2151 }
2152
2153 Mutex::Autolock _l(mLock);
2154
2155 for (size_t i = 0; i < mTracks.size(); ++i) {
2156 sp<Track> track = mTracks[i];
2157 if (event->triggerSession() == track->sessionId()) {
2158 track->setSyncEvent(event);
2159 return NO_ERROR;
2160 }
2161 }
2162
2163 return NAME_NOT_FOUND;
2164}
2165
2166bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2167{
2168 switch (event->type()) {
2169 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2170 return true;
2171 default:
2172 break;
2173 }
2174 return false;
2175}
2176
Eric Laurent44a957f2012-05-15 15:26:05 -07002177void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2178{
2179 size_t count = tracksToRemove.size();
2180 if (CC_UNLIKELY(count)) {
2181 for (size_t i = 0 ; i < count ; i++) {
2182 const sp<Track>& track = tracksToRemove.itemAt(i);
2183 if ((track->sharedBuffer() != 0) &&
2184 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2185 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2186 }
2187 }
2188 }
2189
2190}
2191
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192// ----------------------------------------------------------------------------
2193
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002194AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002195 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002196 : PlaybackThread(audioFlinger, output, id, device, type),
2197 // mAudioMixer below
2198#ifdef SOAKER
2199 mSoaker(NULL),
2200#endif
2201 // mFastMixer below
2202 mFastMixerFutex(0)
2203 // mOutputSink below
2204 // mPipeSink below
2205 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206{
Glenn Kasten58912562012-04-03 10:45:00 -07002207 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2208 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2209 "mFrameCount=%d, mNormalFrameCount=%d",
2210 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2211 mNormalFrameCount);
2212 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2213
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 // FIXME - Current mixer implementation only supports stereo output
2215 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002216 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 }
Glenn Kasten58912562012-04-03 10:45:00 -07002218
2219 // create an NBAIO sink for the HAL output stream, and negotiate
2220 mOutputSink = new AudioStreamOutSink(output->stream);
2221 size_t numCounterOffers = 0;
2222 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2223 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2224 ALOG_ASSERT(index == 0);
2225
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002226 // initialize fast mixer depending on configuration
2227 bool initFastMixer;
2228 switch (kUseFastMixer) {
2229 case FastMixer_Never:
2230 initFastMixer = false;
2231 break;
2232 case FastMixer_Always:
2233 initFastMixer = true;
2234 break;
2235 case FastMixer_Static:
2236 case FastMixer_Dynamic:
2237 initFastMixer = mFrameCount < mNormalFrameCount;
2238 break;
2239 }
2240 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002241
2242 // create a MonoPipe to connect our submix to FastMixer
2243 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002244 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2245 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2246 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2247 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002248 const NBAIO_Format offers[1] = {format};
2249 size_t numCounterOffers = 0;
2250 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2251 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002252 monoPipe->setAvgFrames((mScreenState & 1) ?
2253 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002254 mPipeSink = monoPipe;
2255
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002256#ifdef TEE_SINK_FRAMES
2257 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2258 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2259 numCounterOffers = 0;
2260 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2261 ALOG_ASSERT(index == 0);
2262 mTeeSink = teeSink;
2263 PipeReader *teeSource = new PipeReader(*teeSink);
2264 numCounterOffers = 0;
2265 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2266 ALOG_ASSERT(index == 0);
2267 mTeeSource = teeSource;
2268#endif
2269
Glenn Kasten58912562012-04-03 10:45:00 -07002270#ifdef SOAKER
2271 // create a soaker as workaround for governor issues
2272 mSoaker = new Soaker();
2273 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2274 mSoaker->run("Soaker", PRIORITY_LOWEST);
2275#endif
2276
2277 // create fast mixer and configure it initially with just one fast track for our submix
2278 mFastMixer = new FastMixer();
2279 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002280#ifdef STATE_QUEUE_DUMP
2281 sq->setObserverDump(&mStateQueueObserverDump);
2282 sq->setMutatorDump(&mStateQueueMutatorDump);
2283#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002284 FastMixerState *state = sq->begin();
2285 FastTrack *fastTrack = &state->mFastTracks[0];
2286 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2287 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2288 fastTrack->mVolumeProvider = NULL;
2289 fastTrack->mGeneration++;
2290 state->mFastTracksGen++;
2291 state->mTrackMask = 1;
2292 // fast mixer will use the HAL output sink
2293 state->mOutputSink = mOutputSink.get();
2294 state->mOutputSinkGen++;
2295 state->mFrameCount = mFrameCount;
2296 state->mCommand = FastMixerState::COLD_IDLE;
2297 // already done in constructor initialization list
2298 //mFastMixerFutex = 0;
2299 state->mColdFutexAddr = &mFastMixerFutex;
2300 state->mColdGen++;
2301 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002302 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002303 sq->end();
2304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2305
2306 // start the fast mixer
2307 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2308#ifdef HAVE_REQUEST_PRIORITY
2309 pid_t tid = mFastMixer->getTid();
2310 int err = requestPriority(getpid_cached, tid, 2);
2311 if (err != 0) {
2312 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2313 2, getpid_cached, tid, err);
2314 }
2315#endif
2316
Glenn Kastenc15d6652012-05-30 14:52:57 -07002317#ifdef AUDIO_WATCHDOG
2318 // create and start the watchdog
2319 mAudioWatchdog = new AudioWatchdog();
2320 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2321 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2322 tid = mAudioWatchdog->getTid();
2323 err = requestPriority(getpid_cached, tid, 1);
2324 if (err != 0) {
2325 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2326 1, getpid_cached, tid, err);
2327 }
2328#endif
2329
Glenn Kasten58912562012-04-03 10:45:00 -07002330 } else {
2331 mFastMixer = NULL;
2332 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002333
2334 switch (kUseFastMixer) {
2335 case FastMixer_Never:
2336 case FastMixer_Dynamic:
2337 mNormalSink = mOutputSink;
2338 break;
2339 case FastMixer_Always:
2340 mNormalSink = mPipeSink;
2341 break;
2342 case FastMixer_Static:
2343 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2344 break;
2345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346}
2347
2348AudioFlinger::MixerThread::~MixerThread()
2349{
Glenn Kasten58912562012-04-03 10:45:00 -07002350 if (mFastMixer != NULL) {
2351 FastMixerStateQueue *sq = mFastMixer->sq();
2352 FastMixerState *state = sq->begin();
2353 if (state->mCommand == FastMixerState::COLD_IDLE) {
2354 int32_t old = android_atomic_inc(&mFastMixerFutex);
2355 if (old == -1) {
2356 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2357 }
2358 }
2359 state->mCommand = FastMixerState::EXIT;
2360 sq->end();
2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2362 mFastMixer->join();
2363 // Though the fast mixer thread has exited, it's state queue is still valid.
2364 // We'll use that extract the final state which contains one remaining fast track
2365 // corresponding to our sub-mix.
2366 state = sq->begin();
2367 ALOG_ASSERT(state->mTrackMask == 1);
2368 FastTrack *fastTrack = &state->mFastTracks[0];
2369 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2370 delete fastTrack->mBufferProvider;
2371 sq->end(false /*didModify*/);
2372 delete mFastMixer;
2373#ifdef SOAKER
2374 if (mSoaker != NULL) {
2375 mSoaker->requestExitAndWait();
2376 }
2377 delete mSoaker;
2378#endif
Glenn Kastenc15d6652012-05-30 14:52:57 -07002379 if (mAudioWatchdog != 0) {
2380 mAudioWatchdog->requestExit();
2381 mAudioWatchdog->requestExitAndWait();
2382 mAudioWatchdog.clear();
2383 }
Glenn Kasten58912562012-04-03 10:45:00 -07002384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 delete mAudioMixer;
2386}
2387
Glenn Kasten83efdd02012-02-24 07:21:32 -08002388class CpuStats {
2389public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390 CpuStats();
2391 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002392#ifdef DEBUG_CPU_USAGE
2393private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2395 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2396
2397 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2398
2399 int mCpuNum; // thread's current CPU number
2400 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401#endif
2402};
2403
Glenn Kasten190a46f2012-03-06 11:27:10 -08002404CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002405#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002406 : mCpuNum(-1), mCpukHz(-1)
2407#endif
2408{
2409}
2410
2411void CpuStats::sample(const String8 &title) {
2412#ifdef DEBUG_CPU_USAGE
2413 // get current thread's delta CPU time in wall clock ns
2414 double wcNs;
2415 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2416
2417 // record sample for wall clock statistics
2418 if (valid) {
2419 mWcStats.sample(wcNs);
2420 }
2421
2422 // get the current CPU number
2423 int cpuNum = sched_getcpu();
2424
2425 // get the current CPU frequency in kHz
2426 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2427
2428 // check if either CPU number or frequency changed
2429 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2430 mCpuNum = cpuNum;
2431 mCpukHz = cpukHz;
2432 // ignore sample for purposes of cycles
2433 valid = false;
2434 }
2435
2436 // if no change in CPU number or frequency, then record sample for cycle statistics
2437 if (valid && mCpukHz > 0) {
2438 double cycles = wcNs * cpukHz * 0.000001;
2439 mHzStats.sample(cycles);
2440 }
2441
2442 unsigned n = mWcStats.n();
2443 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002444 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002446 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2447 double perLoop = elapsed / (double) n;
2448 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002449 double perLoop1k = perLoop * 0.001;
2450 double mean = mWcStats.mean();
2451 double stddev = mWcStats.stddev();
2452 double minimum = mWcStats.minimum();
2453 double maximum = mWcStats.maximum();
2454 double meanCycles = mHzStats.mean();
2455 double stddevCycles = mHzStats.stddev();
2456 double minCycles = mHzStats.minimum();
2457 double maxCycles = mHzStats.maximum();
2458 mCpuUsage.resetElapsed();
2459 mWcStats.reset();
2460 mHzStats.reset();
2461 ALOGD("CPU usage for %s over past %.1f secs\n"
2462 " (%u mixer loops at %.1f mean ms per loop):\n"
2463 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2464 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2465 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2466 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002467 elapsed * .000000001, n, perLoop * .000001,
2468 mean * .001,
2469 stddev * .001,
2470 minimum * .001,
2471 maximum * .001,
2472 mean / perLoop100,
2473 stddev / perLoop100,
2474 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002475 maximum / perLoop100,
2476 meanCycles / perLoop1k,
2477 stddevCycles / perLoop1k,
2478 minCycles / perLoop1k,
2479 maxCycles / perLoop1k);
2480
Glenn Kasten83efdd02012-02-24 07:21:32 -08002481 }
2482 }
2483#endif
2484};
2485
Glenn Kasten37d825e2012-02-24 07:21:48 -08002486void AudioFlinger::PlaybackThread::checkSilentMode_l()
2487{
2488 if (!mMasterMute) {
2489 char value[PROPERTY_VALUE_MAX];
2490 if (property_get("ro.audio.silent", value, "0") > 0) {
2491 char *endptr;
2492 unsigned long ul = strtoul(value, &endptr, 0);
2493 if (*endptr == '\0' && ul != 0) {
2494 ALOGD("Silence is golden");
2495 // The setprop command will not allow a property to be changed after
2496 // the first time it is set, so we don't have to worry about un-muting.
2497 setMasterMute_l(true);
2498 }
2499 }
2500 }
2501}
2502
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504{
2505 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002506
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
2509 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002511if (mType == MIXER) {
2512 longStandbyExit = false;
2513}
Glenn Kasten688a6402012-02-29 07:57:06 -08002514
Glenn Kasten000f0e32012-03-01 17:10:56 -08002515 // DUPLICATING
2516 // FIXME could this be made local to while loop?
2517 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002518
Glenn Kasten66fcab92012-02-24 14:59:21 -08002519 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520 sleepTime = idleSleepTime;
2521
2522if (mType == MIXER) {
2523 sleepTimeShift = 0;
2524}
2525
Glenn Kasten83efdd02012-02-24 07:21:32 -08002526 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528
Eric Laurentfeb0db62011-07-22 09:04:31 -07002529 acquireWakeLock();
2530
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 while (!exitPending())
2532 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002533 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002534
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002535 Vector< sp<EffectChain> > effectChains;
2536
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 processConfigEvents();
2538
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 { // scope for mLock
2540
2541 Mutex::Autolock _l(mLock);
2542
2543 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002544 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
2546
Glenn Kastenfa26a852012-03-06 11:28:04 -08002547 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002550 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002551 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002553
2554 threadLoop_standby();
2555
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 mStandby = true;
2557 mBytesWritten = 0;
2558 }
2559
Glenn Kasten3e074702012-02-28 18:40:35 -08002560 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 // we're about to wait, flush the binder command buffer
2562 IPCThreadState::self()->flushCommands();
2563
Glenn Kastenfa26a852012-03-06 11:28:04 -08002564 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 if (exitPending()) break;
2567
Eric Laurentfeb0db62011-07-22 09:04:31 -07002568 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002570 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002572 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002573 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574
Eric Laurentda747442012-04-25 18:53:13 -07002575 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002576 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577
Glenn Kasten37d825e2012-02-24 07:21:48 -08002578 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002582 if (mType == MIXER) {
2583 sleepTimeShift = 0;
2584 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002585
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 continue;
2587 }
2588 }
2589
Glenn Kasten81028042012-04-30 18:15:12 -07002590 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002591 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592
2593 // prevent any changes in effect chain list and in each effect chain
2594 // during mixing and effect process as the audio buffers could be deleted
2595 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002596 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598
Glenn Kastenfec279f2012-03-08 07:47:15 -08002599 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002600 threadLoop_mix();
2601 } else {
2602 threadLoop_sleepTime();
2603 }
2604
2605 if (mSuspended > 0) {
2606 sleepTime = suspendSleepTimeUs();
2607 }
2608
2609 // only process effects if we're going to write
2610 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002611 for (size_t i = 0; i < effectChains.size(); i ++) {
2612 effectChains[i]->process_l();
2613 }
2614 }
2615
2616 // enable changes in effect chain
2617 unlockEffectChains(effectChains);
2618
2619 // sleepTime == 0 means we must write to audio hardware
2620 if (sleepTime == 0) {
2621
2622 threadLoop_write();
2623
2624if (mType == MIXER) {
2625 // write blocked detection
2626 nsecs_t now = systemTime();
2627 nsecs_t delta = now - mLastWriteTime;
2628 if (!mStandby && delta > maxPeriod) {
2629 mNumDelayedWrites++;
2630 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002631#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002632 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002633#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002634 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2635 ns2ms(delta), mNumDelayedWrites, this);
2636 lastWarning = now;
2637 }
2638 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2639 // a different threshold. Or completely removed for what it is worth anyway...
2640 if (mStandby) {
2641 longStandbyExit = true;
2642 }
2643 }
2644}
2645
2646 mStandby = false;
2647 } else {
2648 usleep(sleepTime);
2649 }
2650
Glenn Kasten58912562012-04-03 10:45:00 -07002651 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002652 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002653 // same lock. This will also mutate and push a new fast mixer state.
2654 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002655 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002656
Glenn Kastenfa26a852012-03-06 11:28:04 -08002657 // FIXME I don't understand the need for this here;
2658 // it was in the original code but maybe the
2659 // assignment in saveOutputTracks() makes this unnecessary?
2660 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002661
2662 // Effect chains will be actually deleted here if they were removed from
2663 // mEffectChains list during mixing or effects processing
2664 effectChains.clear();
2665
2666 // FIXME Note that the above .clear() is no longer necessary since effectChains
2667 // is now local to this block, but will keep it for now (at least until merge done).
2668 }
2669
2670if (mType == MIXER || mType == DIRECT) {
2671 // put output stream into standby mode
2672 if (!mStandby) {
2673 mOutput->stream->common.standby(&mOutput->stream->common);
2674 }
2675}
2676if (mType == DUPLICATING) {
2677 // for DuplicatingThread, standby mode is handled by the outputTracks
2678}
2679
2680 releaseWakeLock();
2681
2682 ALOGV("Thread %p type %d exiting", this, mType);
2683 return false;
2684}
2685
Glenn Kasten58912562012-04-03 10:45:00 -07002686void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2687{
Glenn Kasten58912562012-04-03 10:45:00 -07002688 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2689}
2690
2691void AudioFlinger::MixerThread::threadLoop_write()
2692{
2693 // FIXME we should only do one push per cycle; confirm this is true
2694 // Start the fast mixer if it's not already running
2695 if (mFastMixer != NULL) {
2696 FastMixerStateQueue *sq = mFastMixer->sq();
2697 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002698 if (state->mCommand != FastMixerState::MIX_WRITE &&
2699 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002700 if (state->mCommand == FastMixerState::COLD_IDLE) {
2701 int32_t old = android_atomic_inc(&mFastMixerFutex);
2702 if (old == -1) {
2703 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2704 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002705 if (mAudioWatchdog != 0) {
2706 mAudioWatchdog->resume();
2707 }
Glenn Kasten58912562012-04-03 10:45:00 -07002708 }
2709 state->mCommand = FastMixerState::MIX_WRITE;
2710 sq->end();
2711 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002712 if (kUseFastMixer == FastMixer_Dynamic) {
2713 mNormalSink = mPipeSink;
2714 }
Glenn Kasten58912562012-04-03 10:45:00 -07002715 } else {
2716 sq->end(false /*didModify*/);
2717 }
2718 }
2719 PlaybackThread::threadLoop_write();
2720}
2721
Glenn Kasten000f0e32012-03-01 17:10:56 -08002722// shared by MIXER and DIRECT, overridden by DUPLICATING
2723void AudioFlinger::PlaybackThread::threadLoop_write()
2724{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002725 // FIXME rewrite to reduce number of system calls
2726 mLastWriteTime = systemTime();
2727 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002728 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002729
Eric Laurent67c0a582012-05-01 19:31:12 -07002730 // If an NBAIO sink is present, use it to write the normal mixer's submix
2731 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002732#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002733 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002734#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002735 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002736#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002737 // update the setpoint when gScreenState changes
2738 uint32_t screenState = gScreenState;
2739 if (screenState != mScreenState) {
2740 mScreenState = screenState;
2741 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2742 if (pipe != NULL) {
2743 pipe->setAvgFrames((mScreenState & 1) ?
2744 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2745 }
2746 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002747 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002748#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002749 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002750#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002751 if (framesWritten > 0) {
2752 bytesWritten = framesWritten << mBitShift;
2753 } else {
2754 bytesWritten = framesWritten;
2755 }
2756 // otherwise use the HAL / AudioStreamOut directly
2757 } else {
2758 // Direct output thread.
2759 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002760 }
2761
Eric Laurent67c0a582012-05-01 19:31:12 -07002762 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002763 mNumWrites++;
2764 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002765}
2766
Glenn Kasten58912562012-04-03 10:45:00 -07002767void AudioFlinger::MixerThread::threadLoop_standby()
2768{
2769 // Idle the fast mixer if it's currently running
2770 if (mFastMixer != NULL) {
2771 FastMixerStateQueue *sq = mFastMixer->sq();
2772 FastMixerState *state = sq->begin();
2773 if (!(state->mCommand & FastMixerState::IDLE)) {
2774 state->mCommand = FastMixerState::COLD_IDLE;
2775 state->mColdFutexAddr = &mFastMixerFutex;
2776 state->mColdGen++;
2777 mFastMixerFutex = 0;
2778 sq->end();
2779 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2780 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002781 if (kUseFastMixer == FastMixer_Dynamic) {
2782 mNormalSink = mOutputSink;
2783 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002784 if (mAudioWatchdog != 0) {
2785 mAudioWatchdog->pause();
2786 }
Glenn Kasten58912562012-04-03 10:45:00 -07002787 } else {
2788 sq->end(false /*didModify*/);
2789 }
2790 }
2791 PlaybackThread::threadLoop_standby();
2792}
2793
Glenn Kasten000f0e32012-03-01 17:10:56 -08002794// shared by MIXER and DIRECT, overridden by DUPLICATING
2795void AudioFlinger::PlaybackThread::threadLoop_standby()
2796{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002797 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2798 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002799}
2800
2801void AudioFlinger::MixerThread::threadLoop_mix()
2802{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002803 // obtain the presentation timestamp of the next output buffer
2804 int64_t pts;
2805 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002806
Glenn Kasten952eeb22012-03-06 11:30:57 -08002807 if (NULL != mOutput->stream->get_next_write_timestamp) {
2808 status = mOutput->stream->get_next_write_timestamp(
2809 mOutput->stream, &pts);
2810 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002811
Glenn Kasten952eeb22012-03-06 11:30:57 -08002812 if (status != NO_ERROR) {
2813 pts = AudioBufferProvider::kInvalidPTS;
2814 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002815
Glenn Kasten952eeb22012-03-06 11:30:57 -08002816 // mix buffers...
2817 mAudioMixer->process(pts);
2818 // increase sleep time progressively when application underrun condition clears.
2819 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2820 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2821 // such that we would underrun the audio HAL.
2822 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2823 sleepTimeShift--;
2824 }
2825 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002826 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002827 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002828}
2829
2830void AudioFlinger::MixerThread::threadLoop_sleepTime()
2831{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 // If no tracks are ready, sleep once for the duration of an output
2833 // buffer size, then write 0s to the output
2834 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002835 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002836 sleepTime = activeSleepTime >> sleepTimeShift;
2837 if (sleepTime < kMinThreadSleepTimeUs) {
2838 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002840 // reduce sleep time in case of consecutive application underruns to avoid
2841 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2842 // duration we would end up writing less data than needed by the audio HAL if
2843 // the condition persists.
2844 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2845 sleepTimeShift++;
2846 }
2847 } else {
2848 sleepTime = idleSleepTime;
2849 }
2850 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002851 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002852 memset (mMixBuffer, 0, mixBufferSize);
2853 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002854 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002855 }
2856 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857}
2858
2859// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002860AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002861 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862{
2863
Glenn Kasten29c23c32012-01-26 13:37:52 -08002864 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002866 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 size_t mixedTracks = 0;
2868 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002869 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002870 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002871 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872
2873 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002874 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875
Eric Laurent571d49c2010-08-11 05:20:11 -07002876 if (masterMute) {
2877 masterVolume = 0;
2878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002880 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002882 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002883 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 masterVolume = (float)((v + (1 << 23)) >> 24);
2885 chain.clear();
2886 }
2887
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 // prepare a new state to push
2889 FastMixerStateQueue *sq = NULL;
2890 FastMixerState *state = NULL;
2891 bool didModify = false;
2892 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2893 if (mFastMixer != NULL) {
2894 sq = mFastMixer->sq();
2895 state = sq->begin();
2896 }
2897
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002899 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 if (t == 0) continue;
2901
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002902 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002904
Glenn Kasten288ed212012-04-25 17:52:27 -07002905 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002906 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002907
2908 // It's theoretically possible (though unlikely) for a fast track to be created
2909 // and then removed within the same normal mix cycle. This is not a problem, as
2910 // the track never becomes active so it's fast mixer slot is never touched.
2911 // The converse, of removing an (active) track and then creating a new track
2912 // at the identical fast mixer slot within the same normal mix cycle,
2913 // is impossible because the slot isn't marked available until the end of each cycle.
2914 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002915 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2916 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 FastTrack *fastTrack = &state->mFastTracks[j];
2918
2919 // Determine whether the track is currently in underrun condition,
2920 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002921 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2922 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002923 uint32_t recentFull = (underruns.mBitFields.mFull -
2924 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2925 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2926 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2927 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2928 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2929 uint32_t recentUnderruns = recentPartial + recentEmpty;
2930 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002931 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002932 // or stopped which can occur when flush() is called while active
2933 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002934 track->mUnderrunCount += recentUnderruns;
2935 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002936
Glenn Kastend08f48c2012-05-01 18:14:02 -07002937 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002939 bool isActive = true;
2940 switch (track->mState) {
2941 case TrackBase::STOPPING_1:
2942 // track stays active in STOPPING_1 state until first underrun
2943 if (recentUnderruns > 0) {
2944 track->mState = TrackBase::STOPPING_2;
2945 }
2946 break;
2947 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002948 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002949 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002950 break;
2951 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002952 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002953 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002954 break;
2955 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002956 if (recentFull > 0 || recentPartial > 0) {
2957 // track has provided at least some frames recently: reset retry count
2958 track->mRetryCount = kMaxTrackRetries;
2959 }
2960 if (recentUnderruns == 0) {
2961 // no recent underruns: stay active
2962 break;
2963 }
2964 // there has recently been an underrun of some kind
2965 if (track->sharedBuffer() == 0) {
2966 // were any of the recent underruns "empty" (no frames available)?
2967 if (recentEmpty == 0) {
2968 // no, then ignore the partial underruns as they are allowed indefinitely
2969 break;
2970 }
2971 // there has recently been an "empty" underrun: decrement the retry counter
2972 if (--(track->mRetryCount) > 0) {
2973 break;
2974 }
2975 // indicate to client process that the track was disabled because of underrun;
2976 // it will then automatically call start() when data is available
2977 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2978 // remove from active list, but state remains ACTIVE [confusing but true]
2979 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002980 break;
2981 }
2982 // fall through
2983 case TrackBase::STOPPING_2:
2984 case TrackBase::PAUSED:
2985 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002986 case TrackBase::STOPPED:
2987 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002988 // Check for presentation complete if track is inactive
2989 // We have consumed all the buffers of this track.
2990 // This would be incomplete if we auto-paused on underrun
2991 {
2992 size_t audioHALFrames =
2993 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2994 size_t framesWritten =
2995 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2996 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2997 // track stays in active list until presentation is complete
2998 break;
2999 }
3000 }
3001 if (track->isStopping_2()) {
3002 track->mState = TrackBase::STOPPED;
3003 }
3004 if (track->isStopped()) {
3005 // Can't reset directly, as fast mixer is still polling this track
3006 // track->reset();
3007 // So instead mark this track as needing to be reset after push with ack
3008 resetMask |= 1 << i;
3009 }
3010 isActive = false;
3011 break;
3012 case TrackBase::IDLE:
3013 default:
3014 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003015 }
3016
3017 if (isActive) {
3018 // was it previously inactive?
3019 if (!(state->mTrackMask & (1 << j))) {
3020 ExtendedAudioBufferProvider *eabp = track;
3021 VolumeProvider *vp = track;
3022 fastTrack->mBufferProvider = eabp;
3023 fastTrack->mVolumeProvider = vp;
3024 fastTrack->mSampleRate = track->mSampleRate;
3025 fastTrack->mChannelMask = track->mChannelMask;
3026 fastTrack->mGeneration++;
3027 state->mTrackMask |= 1 << j;
3028 didModify = true;
3029 // no acknowledgement required for newly active tracks
3030 }
3031 // cache the combined master volume and stream type volume for fast mixer; this
3032 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3033 track->mCachedVolume = track->isMuted() ?
3034 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3035 ++fastTracks;
3036 } else {
3037 // was it previously active?
3038 if (state->mTrackMask & (1 << j)) {
3039 fastTrack->mBufferProvider = NULL;
3040 fastTrack->mGeneration++;
3041 state->mTrackMask &= ~(1 << j);
3042 didModify = true;
3043 // If any fast tracks were removed, we must wait for acknowledgement
3044 // because we're about to decrement the last sp<> on those tracks.
3045 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003046 } else {
3047 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003048 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003049 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003050 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003051 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003052 }
3053 continue;
3054 }
3055
3056 { // local variable scope to avoid goto warning
3057
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 audio_track_cblk_t* cblk = track->cblk();
3059
3060 // The first time a track is added we wait
3061 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003062 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003063 // make sure that we have enough frames to mix one full buffer.
3064 // enforce this condition only once to enable draining the buffer in case the client
3065 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003066 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003067 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003068 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003069 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003070 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003071 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003072 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003073 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003074 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003075 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003076 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003077 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003078 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3079 // the minimum track buffer size is normally twice the number of frames necessary
3080 // to fill one buffer and the resampler should not leave more than one buffer worth
3081 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003082 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003083 }
3084 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003085 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 !track->isPaused() && !track->isTerminated())
3087 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003088 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089
3090 mixedTracks++;
3091
3092 // track->mainBuffer() != mMixBuffer means there is an effect chain
3093 // connected to the track
3094 chain.clear();
3095 if (track->mainBuffer() != mMixBuffer) {
3096 chain = getEffectChain_l(track->sessionId());
3097 // Delegate volume control to effect in track effect chain if needed
3098 if (chain != 0) {
3099 tracksWithEffect++;
3100 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003101 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003102 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 }
3104 }
3105
3106
3107 int param = AudioMixer::VOLUME;
3108 if (track->mFillingUpStatus == Track::FS_FILLED) {
3109 // no ramp for the first volume setting
3110 track->mFillingUpStatus = Track::FS_ACTIVE;
3111 if (track->mState == TrackBase::RESUMING) {
3112 track->mState = TrackBase::ACTIVE;
3113 param = AudioMixer::RAMP_VOLUME;
3114 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003115 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 } else if (cblk->server != 0) {
3117 // If the track is stopped before the first frame was mixed,
3118 // do not apply ramp
3119 param = AudioMixer::RAMP_VOLUME;
3120 }
3121
3122 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003123 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003124 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003125 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003126 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 if (track->isPausing()) {
3128 track->setPaused();
3129 }
3130 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003131
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003133 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003135 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003136 vl = vlr & 0xFFFF;
3137 vr = vlr >> 16;
3138 // track volumes come from shared memory, so can't be trusted and must be clamped
3139 if (vl > MAX_GAIN_INT) {
3140 ALOGV("Track left volume out of range: %04X", vl);
3141 vl = MAX_GAIN_INT;
3142 }
3143 if (vr > MAX_GAIN_INT) {
3144 ALOGV("Track right volume out of range: %04X", vr);
3145 vr = MAX_GAIN_INT;
3146 }
3147 // now apply the master volume and stream type volume
3148 vl = (uint32_t)(v * vl) << 12;
3149 vr = (uint32_t)(v * vr) << 12;
3150 // assuming master volume and stream type volume each go up to 1.0,
3151 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152
Glenn Kasten05632a52012-01-03 14:22:33 -08003153 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3154 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003155 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003156 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003157 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003158 }
3159 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003161 // Delegate volume control to effect in track effect chain if needed
3162 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3163 // Do not ramp volume if volume is controlled by effect
3164 param = AudioMixer::VOLUME;
3165 track->mHasVolumeController = true;
3166 } else {
3167 // force no volume ramp when volume controller was just disabled or removed
3168 // from effect chain to avoid volume spike
3169 if (track->mHasVolumeController) {
3170 param = AudioMixer::VOLUME;
3171 }
3172 track->mHasVolumeController = false;
3173 }
3174
3175 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003176 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003177 vl = (vl + (1 << 11)) >> 12;
3178 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3179 vr = (vr + (1 << 11)) >> 12;
3180 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003181
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003182 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 -07003183
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003185 mAudioMixer->setBufferProvider(name, track);
3186 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003188 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3189 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3190 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
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::TRACK,
3194 AudioMixer::FORMAT, (void *)track->format());
3195 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003196 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003198 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003200 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 AudioMixer::RESAMPLE,
3202 AudioMixer::SAMPLE_RATE,
3203 (void *)(cblk->sampleRate));
3204 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003205 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 AudioMixer::TRACK,
3207 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3208 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003209 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 AudioMixer::TRACK,
3211 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3212
3213 // reset retry count
3214 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003215
Eric Laurent27741442012-01-17 19:20:12 -08003216 // If one track is ready, set the mixer ready if:
3217 // - the mixer was not ready during previous round OR
3218 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003219 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003220 mixerStatus != MIXER_TRACKS_ENABLED) {
3221 mixerStatus = MIXER_TRACKS_READY;
3222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003224 // clear effect chain input buffer if an active track underruns to avoid sending
3225 // previous audio buffer again to effects
3226 chain = getEffectChain_l(track->sessionId());
3227 if (chain != 0) {
3228 chain->clearInputBuffer();
3229 }
3230
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003231 //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 -07003232 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3233 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 // We have consumed all the buffers of this track.
3235 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003236 // TODO: use actual buffer filling status instead of latency when available from
3237 // audio HAL
3238 size_t audioHALFrames =
3239 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3240 size_t framesWritten =
3241 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3242 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003243 if (track->isStopped()) {
3244 track->reset();
3245 }
Eric Laurenta011e352012-03-29 15:51:43 -07003246 tracksToRemove->add(track);
3247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003249 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 // No buffers for this track. Give it a few chances to
3251 // fill a buffer, then remove it from active list.
3252 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003253 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003255 // indicate to client process that the track was disabled because of underrun;
3256 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003257 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003258 // If one track is not ready, mark the mixer also not ready if:
3259 // - the mixer was ready during previous round OR
3260 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003261 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003262 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 mixerStatus = MIXER_TRACKS_ENABLED;
3264 }
3265 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003266 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 }
Glenn Kasten58912562012-04-03 10:45:00 -07003268
3269 } // local variable scope to avoid goto warning
3270track_is_ready: ;
3271
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 }
3273
Glenn Kasten288ed212012-04-25 17:52:27 -07003274 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003275 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003276 if (didModify) {
3277 state->mFastTracksGen++;
3278 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3279 if (kUseFastMixer == FastMixer_Dynamic &&
3280 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3281 state->mCommand = FastMixerState::COLD_IDLE;
3282 state->mColdFutexAddr = &mFastMixerFutex;
3283 state->mColdGen++;
3284 mFastMixerFutex = 0;
3285 if (kUseFastMixer == FastMixer_Dynamic) {
3286 mNormalSink = mOutputSink;
3287 }
3288 // If we go into cold idle, need to wait for acknowledgement
3289 // so that fast mixer stops doing I/O.
3290 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003291 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003292 }
3293 sq->end();
3294 }
3295 if (sq != NULL) {
3296 sq->end(didModify);
3297 sq->push(block);
3298 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003299 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3300 mAudioWatchdog->pause();
3301 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003302
3303 // Now perform the deferred reset on fast tracks that have stopped
3304 while (resetMask != 0) {
3305 size_t i = __builtin_ctz(resetMask);
3306 ALOG_ASSERT(i < count);
3307 resetMask &= ~(1 << i);
3308 sp<Track> t = mActiveTracks[i].promote();
3309 if (t == 0) continue;
3310 Track* track = t.get();
3311 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3312 track->reset();
3313 }
Glenn Kasten58912562012-04-03 10:45:00 -07003314
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 // remove all the tracks that need to be...
3316 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003317 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 for (size_t i=0 ; i<count ; i++) {
3319 const sp<Track>& track = tracksToRemove->itemAt(i);
3320 mActiveTracks.remove(track);
3321 if (track->mainBuffer() != mMixBuffer) {
3322 chain = getEffectChain_l(track->sessionId());
3323 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003324 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003325 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 }
3327 }
3328 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003329 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 }
3331 }
3332 }
3333
3334 // mix buffer must be cleared if all tracks are connected to an
3335 // effect chain as in this case the mixer will not write to
3336 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003337 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3338 // FIXME as a performance optimization, should remember previous zero status
3339 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 }
3341
Glenn Kasten58912562012-04-03 10:45:00 -07003342 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003343 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003344 if (fastTracks > 0) {
3345 mixerStatus = MIXER_TRACKS_READY;
3346 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 return mixerStatus;
3348}
3349
Glenn Kasten66fcab92012-02-24 14:59:21 -08003350/*
3351The derived values that are cached:
3352 - mixBufferSize from frame count * frame size
3353 - activeSleepTime from activeSleepTimeUs()
3354 - idleSleepTime from idleSleepTimeUs()
3355 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3356 - maxPeriod from frame count and sample rate (MIXER only)
3357
3358The parameters that affect these derived values are:
3359 - frame count
3360 - frame size
3361 - sample rate
3362 - device type: A2DP or not
3363 - device latency
3364 - format: PCM or not
3365 - active sleep time
3366 - idle sleep time
3367*/
3368
3369void AudioFlinger::PlaybackThread::cacheParameters_l()
3370{
Glenn Kasten58912562012-04-03 10:45:00 -07003371 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003372 activeSleepTime = activeSleepTimeUs();
3373 idleSleepTime = idleSleepTimeUs();
3374}
3375
Glenn Kastenfff6d712012-01-12 16:38:12 -08003376void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377{
Steve Block3856b092011-10-20 11:56:00 +01003378 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003379 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003381
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 size_t size = mTracks.size();
3383 for (size_t i = 0; i < size; i++) {
3384 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003385 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003386 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 }
3389 }
3390}
3391
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003393int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003395 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396}
3397
3398// deleteTrackName_l() must be called with ThreadBase::mLock held
3399void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3400{
Steve Block3856b092011-10-20 11:56:00 +01003401 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 mAudioMixer->deleteTrackName(name);
3403}
3404
3405// checkForNewParameters_l() must be called with ThreadBase::mLock held
3406bool AudioFlinger::MixerThread::checkForNewParameters_l()
3407{
Glenn Kasten58912562012-04-03 10:45:00 -07003408 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3409 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 bool reconfig = false;
3411
3412 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003413
3414 if (mFastMixer != NULL) {
3415 FastMixerStateQueue *sq = mFastMixer->sq();
3416 FastMixerState *state = sq->begin();
3417 if (!(state->mCommand & FastMixerState::IDLE)) {
3418 previousCommand = state->mCommand;
3419 state->mCommand = FastMixerState::HOT_IDLE;
3420 sq->end();
3421 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3422 } else {
3423 sq->end(false /*didModify*/);
3424 }
3425 }
3426
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 status_t status = NO_ERROR;
3428 String8 keyValuePair = mNewParameters[0];
3429 AudioParameter param = AudioParameter(keyValuePair);
3430 int value;
3431
3432 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3433 reconfig = true;
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003436 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 status = BAD_VALUE;
3438 } else {
3439 reconfig = true;
3440 }
3441 }
3442 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003443 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 status = BAD_VALUE;
3445 } else {
3446 reconfig = true;
3447 }
3448 }
3449 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3450 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003451 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 // if frame count is changed after track creation
3453 if (!mTracks.isEmpty()) {
3454 status = INVALID_OPERATION;
3455 } else {
3456 reconfig = true;
3457 }
3458 }
3459 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003460#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003461 // when changing the audio output device, call addBatteryData to notify
3462 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003463 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003464 uint32_t params = 0;
3465 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003466 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003467 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3468 }
3469
3470 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003471 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003472 // check if any other device (except speaker) is on
3473 if (value & deviceWithoutSpeaker ) {
3474 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3475 }
3476
3477 if (params != 0) {
3478 addBatteryData(params);
3479 }
3480 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003481#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003482
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 // forward device change to effects that have requested to be
3484 // aware of attached audio device.
3485 mDevice = (uint32_t)value;
3486 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003487 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 }
3489 }
3490
3491 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003492 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003493 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003495 mOutput->stream->common.standby(&mOutput->stream->common);
3496 mStandby = true;
3497 mBytesWritten = 0;
3498 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003499 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 }
3501 if (status == NO_ERROR && reconfig) {
3502 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003503 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3504 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003506 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003508 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 if (name < 0) break;
3510 mTracks[i]->mName = name;
3511 // limit track sample rate to 2 x new output sample rate
3512 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3513 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3514 }
3515 }
3516 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3517 }
3518 }
3519
3520 mNewParameters.removeAt(0);
3521
3522 mParamStatus = status;
3523 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003524 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3525 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003526 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 }
Glenn Kasten58912562012-04-03 10:45:00 -07003528
3529 if (!(previousCommand & FastMixerState::IDLE)) {
3530 ALOG_ASSERT(mFastMixer != NULL);
3531 FastMixerStateQueue *sq = mFastMixer->sq();
3532 FastMixerState *state = sq->begin();
3533 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3534 state->mCommand = previousCommand;
3535 sq->end();
3536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3537 }
3538
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 return reconfig;
3540}
3541
3542status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3543{
3544 const size_t SIZE = 256;
3545 char buffer[SIZE];
3546 String8 result;
3547
3548 PlaybackThread::dumpInternals(fd, args);
3549
3550 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3551 result.append(buffer);
3552 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003553
3554 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3555 FastMixerDumpState copy = mFastMixerDumpState;
3556 copy.dump(fd);
3557
Glenn Kasten39993082012-05-31 13:40:27 -07003558#ifdef STATE_QUEUE_DUMP
3559 // Similar for state queue
3560 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3561 observerCopy.dump(fd);
3562 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3563 mutatorCopy.dump(fd);
3564#endif
3565
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003566 // Write the tee output to a .wav file
3567 NBAIO_Source *teeSource = mTeeSource.get();
3568 if (teeSource != NULL) {
3569 char teePath[64];
3570 struct timeval tv;
3571 gettimeofday(&tv, NULL);
3572 struct tm tm;
3573 localtime_r(&tv.tv_sec, &tm);
3574 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3575 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3576 if (teeFd >= 0) {
3577 char wavHeader[44];
3578 memcpy(wavHeader,
3579 "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",
3580 sizeof(wavHeader));
3581 NBAIO_Format format = teeSource->format();
3582 unsigned channelCount = Format_channelCount(format);
3583 ALOG_ASSERT(channelCount <= FCC_2);
3584 unsigned sampleRate = Format_sampleRate(format);
3585 wavHeader[22] = channelCount; // number of channels
3586 wavHeader[24] = sampleRate; // sample rate
3587 wavHeader[25] = sampleRate >> 8;
3588 wavHeader[32] = channelCount * 2; // block alignment
3589 write(teeFd, wavHeader, sizeof(wavHeader));
3590 size_t total = 0;
3591 bool firstRead = true;
3592 for (;;) {
3593#define TEE_SINK_READ 1024
3594 short buffer[TEE_SINK_READ * FCC_2];
3595 size_t count = TEE_SINK_READ;
3596 ssize_t actual = teeSource->read(buffer, count);
3597 bool wasFirstRead = firstRead;
3598 firstRead = false;
3599 if (actual <= 0) {
3600 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3601 continue;
3602 }
3603 break;
3604 }
3605 ALOG_ASSERT(actual <= count);
3606 write(teeFd, buffer, actual * channelCount * sizeof(short));
3607 total += actual;
3608 }
3609 lseek(teeFd, (off_t) 4, SEEK_SET);
3610 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3611 write(teeFd, &temp, sizeof(temp));
3612 lseek(teeFd, (off_t) 40, SEEK_SET);
3613 temp = total * channelCount * sizeof(short);
3614 write(teeFd, &temp, sizeof(temp));
3615 close(teeFd);
3616 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3617 } else {
3618 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3619 }
3620 }
3621
Glenn Kastenc15d6652012-05-30 14:52:57 -07003622 if (mAudioWatchdog != 0) {
3623 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3624 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3625 wdCopy.dump(fd);
3626 }
3627
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 return NO_ERROR;
3629}
3630
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003631uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632{
Glenn Kasten58912562012-04-03 10:45:00 -07003633 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634}
3635
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003636uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003637{
Glenn Kasten58912562012-04-03 10:45:00 -07003638 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003639}
3640
Glenn Kasten66fcab92012-02-24 14:59:21 -08003641void AudioFlinger::MixerThread::cacheParameters_l()
3642{
3643 PlaybackThread::cacheParameters_l();
3644
3645 // FIXME: Relaxed timing because of a certain device that can't meet latency
3646 // Should be reduced to 2x after the vendor fixes the driver issue
3647 // increase threshold again due to low power audio mode. The way this warning
3648 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003649 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003650}
3651
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003653AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3654 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003655 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003656 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658}
3659
3660AudioFlinger::DirectOutputThread::~DirectOutputThread()
3661{
3662}
3663
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003664AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3665 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003666)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003668 sp<Track> trackToRemove;
3669
Glenn Kastenfec279f2012-03-08 07:47:15 -08003670 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671
Glenn Kasten952eeb22012-03-06 11:30:57 -08003672 // find out which tracks need to be processed
3673 if (mActiveTracks.size() != 0) {
3674 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003675 // The track died recently
3676 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677
Glenn Kasten952eeb22012-03-06 11:30:57 -08003678 Track* const track = t.get();
3679 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 // The first time a track is added we wait
3682 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003683 uint32_t minFrames;
3684 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3685 minFrames = mNormalFrameCount;
3686 } else {
3687 minFrames = 1;
3688 }
3689 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003690 !track->isPaused() && !track->isTerminated())
3691 {
3692 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 if (track->mFillingUpStatus == Track::FS_FILLED) {
3695 track->mFillingUpStatus = Track::FS_ACTIVE;
3696 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003697 if (track->mState == TrackBase::RESUMING) {
3698 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003701
Glenn Kasten952eeb22012-03-06 11:30:57 -08003702 // compute volume for this track
3703 float left, right;
3704 if (track->isMuted() || mMasterMute || track->isPausing() ||
3705 mStreamTypes[track->streamType()].mute) {
3706 left = right = 0;
3707 if (track->isPausing()) {
3708 track->setPaused();
3709 }
3710 } else {
3711 float typeVolume = mStreamTypes[track->streamType()].volume;
3712 float v = mMasterVolume * typeVolume;
3713 uint32_t vlr = cblk->getVolumeLR();
3714 float v_clamped = v * (vlr & 0xFFFF);
3715 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3716 left = v_clamped/MAX_GAIN;
3717 v_clamped = v * (vlr >> 16);
3718 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3719 right = v_clamped/MAX_GAIN;
3720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 if (left != mLeftVolFloat || right != mRightVolFloat) {
3723 mLeftVolFloat = left;
3724 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 // Convert volumes from float to 8.24
3727 uint32_t vl = (uint32_t)(left * (1 << 24));
3728 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 // Delegate volume control to effect in track effect chain if needed
3731 // only one effect chain can be present on DirectOutputThread, so if
3732 // there is one, the track is connected to it
3733 if (!mEffectChains.isEmpty()) {
3734 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003735 mEffectChains[0]->setVolume_l(&vl, &vr);
3736 left = (float)vl / (1 << 24);
3737 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003738 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003739 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003740 }
3741
3742 // reset retry count
3743 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003744 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003745 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003747 // clear effect chain input buffer if an active track underruns to avoid sending
3748 // previous audio buffer again to effects
3749 if (!mEffectChains.isEmpty()) {
3750 mEffectChains[0]->clearInputBuffer();
3751 }
3752
Glenn Kasten952eeb22012-03-06 11:30:57 -08003753 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003754 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3755 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003756 // We have consumed all the buffers of this track.
3757 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003758 // TODO: implement behavior for compressed audio
3759 size_t audioHALFrames =
3760 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3761 size_t framesWritten =
3762 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3763 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003764 if (track->isStopped()) {
3765 track->reset();
3766 }
Eric Laurenta011e352012-03-29 15:51:43 -07003767 trackToRemove = track;
3768 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 } else {
3770 // No buffers for this track. Give it a few chances to
3771 // fill a buffer, then remove it from active list.
3772 if (--(track->mRetryCount) <= 0) {
3773 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3774 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003776 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777 }
3778 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003779 }
3780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003782 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003783 // remove all the tracks that need to be...
3784 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003785 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 mActiveTracks.remove(trackToRemove);
3787 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003788 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003789 trackToRemove->sessionId());
3790 mEffectChains[0]->decActiveTrackCnt();
3791 }
3792 if (trackToRemove->isTerminated()) {
3793 removeTrack_l(trackToRemove);
3794 }
3795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796
Glenn Kastenfec279f2012-03-08 07:47:15 -08003797 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003798}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799
Glenn Kasten000f0e32012-03-01 17:10:56 -08003800void AudioFlinger::DirectOutputThread::threadLoop_mix()
3801{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003802 AudioBufferProvider::Buffer buffer;
3803 size_t frameCount = mFrameCount;
3804 int8_t *curBuf = (int8_t *)mMixBuffer;
3805 // output audio to hardware
3806 while (frameCount) {
3807 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003808 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003809 if (CC_UNLIKELY(buffer.raw == NULL)) {
3810 memset(curBuf, 0, frameCount * mFrameSize);
3811 break;
3812 }
3813 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3814 frameCount -= buffer.frameCount;
3815 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003816 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003817 }
3818 sleepTime = 0;
3819 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003820 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003821
Glenn Kasten000f0e32012-03-01 17:10:56 -08003822}
3823
3824void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3825{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003827 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003828 sleepTime = activeSleepTime;
3829 } else {
3830 sleepTime = idleSleepTime;
3831 }
3832 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003833 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003834 sleepTime = 0;
3835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836}
3837
3838// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003839int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840{
3841 return 0;
3842}
3843
3844// deleteTrackName_l() must be called with ThreadBase::mLock held
3845void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3846{
3847}
3848
3849// checkForNewParameters_l() must be called with ThreadBase::mLock held
3850bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3851{
3852 bool reconfig = false;
3853
3854 while (!mNewParameters.isEmpty()) {
3855 status_t status = NO_ERROR;
3856 String8 keyValuePair = mNewParameters[0];
3857 AudioParameter param = AudioParameter(keyValuePair);
3858 int value;
3859
3860 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3861 // do not accept frame count changes if tracks are open as the track buffer
3862 // size depends on frame count and correct behavior would not be garantied
3863 // if frame count is changed after track creation
3864 if (!mTracks.isEmpty()) {
3865 status = INVALID_OPERATION;
3866 } else {
3867 reconfig = true;
3868 }
3869 }
3870 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003871 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003872 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003874 mOutput->stream->common.standby(&mOutput->stream->common);
3875 mStandby = true;
3876 mBytesWritten = 0;
3877 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003878 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 }
3880 if (status == NO_ERROR && reconfig) {
3881 readOutputParameters();
3882 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3883 }
3884 }
3885
3886 mNewParameters.removeAt(0);
3887
3888 mParamStatus = status;
3889 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003890 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3891 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003892 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 }
3894 return reconfig;
3895}
3896
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003897uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898{
3899 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003900 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003901 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 } else {
3903 time = 10000;
3904 }
3905 return time;
3906}
3907
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003908uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909{
3910 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003911 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003912 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 } else {
3914 time = 10000;
3915 }
3916 return time;
3917}
3918
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003919uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003920{
3921 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003922 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003923 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3924 } else {
3925 time = 10000;
3926 }
3927 return time;
3928}
3929
Glenn Kasten66fcab92012-02-24 14:59:21 -08003930void AudioFlinger::DirectOutputThread::cacheParameters_l()
3931{
3932 PlaybackThread::cacheParameters_l();
3933
3934 // use shorter standby delay as on normal output to release
3935 // hardware resources as soon as possible
3936 standbyDelay = microseconds(activeSleepTime*2);
3937}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003938
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939// ----------------------------------------------------------------------------
3940
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003941AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003942 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003943 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3944 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946 addOutputTrack(mainThread);
3947}
3948
3949AudioFlinger::DuplicatingThread::~DuplicatingThread()
3950{
3951 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3952 mOutputTracks[i]->destroy();
3953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954}
3955
Glenn Kasten000f0e32012-03-01 17:10:56 -08003956void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003958 // mix buffers...
3959 if (outputsReady(outputTracks)) {
3960 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3961 } else {
3962 memset(mMixBuffer, 0, mixBufferSize);
3963 }
3964 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003965 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003966 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003967}
3968
3969void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3970{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003971 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003972 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003973 sleepTime = activeSleepTime;
3974 } else {
3975 sleepTime = idleSleepTime;
3976 }
3977 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003978 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3979 writeFrames = mNormalFrameCount;
3980 memset(mMixBuffer, 0, mixBufferSize);
3981 } else {
3982 // flush remaining overflow buffers in output tracks
3983 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003984 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003985 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003986 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003987}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988
Glenn Kasten000f0e32012-03-01 17:10:56 -08003989void AudioFlinger::DuplicatingThread::threadLoop_write()
3990{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003991 for (size_t i = 0; i < outputTracks.size(); i++) {
3992 outputTracks[i]->write(mMixBuffer, writeFrames);
3993 }
3994 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003995}
Glenn Kasten688a6402012-02-29 07:57:06 -08003996
Glenn Kasten000f0e32012-03-01 17:10:56 -08003997void AudioFlinger::DuplicatingThread::threadLoop_standby()
3998{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003999 // DuplicatingThread implements standby by stopping all tracks
4000 for (size_t i = 0; i < outputTracks.size(); i++) {
4001 outputTracks[i]->stop();
4002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003}
4004
Glenn Kastenfa26a852012-03-06 11:28:04 -08004005void AudioFlinger::DuplicatingThread::saveOutputTracks()
4006{
4007 outputTracks = mOutputTracks;
4008}
4009
4010void AudioFlinger::DuplicatingThread::clearOutputTracks()
4011{
4012 outputTracks.clear();
4013}
4014
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4016{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004017 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004018 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004019 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004020 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 this,
4022 mSampleRate,
4023 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004024 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 frameCount);
4026 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004027 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004029 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004030 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 }
4032}
4033
4034void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4035{
4036 Mutex::Autolock _l(mLock);
4037 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004038 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 mOutputTracks[i]->destroy();
4040 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004041 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042 return;
4043 }
4044 }
Steve Block3856b092011-10-20 11:56:00 +01004045 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046}
4047
Glenn Kasten438b0362012-03-06 11:24:48 -08004048// caller must hold mLock
4049void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050{
4051 mWaitTimeMs = UINT_MAX;
4052 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4053 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004054 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4056 if (waitTimeMs < mWaitTimeMs) {
4057 mWaitTimeMs = waitTimeMs;
4058 }
4059 }
4060 }
4061}
4062
4063
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004064bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065{
4066 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004067 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004069 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 return false;
4071 }
4072 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4073 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004074 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075 return false;
4076 }
4077 }
4078 return true;
4079}
4080
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004081uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082{
4083 return (mWaitTimeMs * 1000) / 2;
4084}
4085
Glenn Kasten66fcab92012-02-24 14:59:21 -08004086void AudioFlinger::DuplicatingThread::cacheParameters_l()
4087{
4088 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4089 updateWaitTime_l();
4090
4091 MixerThread::cacheParameters_l();
4092}
4093
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094// ----------------------------------------------------------------------------
4095
4096// TrackBase constructor must be called with AudioFlinger::mLock held
4097AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004098 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099 const sp<Client>& client,
4100 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004101 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004102 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 const sp<IMemory>& sharedBuffer,
4105 int sessionId)
4106 : RefBase(),
4107 mThread(thread),
4108 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004109 mCblk(NULL),
4110 // mBuffer
4111 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 mFrameCount(0),
4113 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004114 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004116 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004118 // mChannelCount
4119 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120{
Steve Block3856b092011-10-20 11:56:00 +01004121 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122
Steve Blockb8a80522011-12-20 16:23:08 +00004123 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004124 size_t size = sizeof(audio_track_cblk_t);
4125 uint8_t channelCount = popcount(channelMask);
4126 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4127 if (sharedBuffer == 0) {
4128 size += bufferSize;
4129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004131 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132 mCblkMemory = client->heap()->allocate(size);
4133 if (mCblkMemory != 0) {
4134 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004135 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 new(mCblk) audio_track_cblk_t();
4137 // clear all buffers
4138 mCblk->frameCount = frameCount;
4139 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004140// uncomment the following lines to quickly test 32-bit wraparound
4141// mCblk->user = 0xffff0000;
4142// mCblk->server = 0xffff0000;
4143// mCblk->userBase = 0xffff0000;
4144// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004145 mChannelCount = channelCount;
4146 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 if (sharedBuffer == 0) {
4148 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4149 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4150 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004151 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 mCblk->flags = CBLK_UNDERRUN_ON;
4153 } else {
4154 mBuffer = sharedBuffer->pointer();
4155 }
4156 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4157 }
4158 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004159 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 client->heap()->dump("AudioTrack");
4161 return;
4162 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004163 } else {
4164 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004165 // construct the shared structure in-place.
4166 new(mCblk) audio_track_cblk_t();
4167 // clear all buffers
4168 mCblk->frameCount = frameCount;
4169 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004170// uncomment the following lines to quickly test 32-bit wraparound
4171// mCblk->user = 0xffff0000;
4172// mCblk->server = 0xffff0000;
4173// mCblk->userBase = 0xffff0000;
4174// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004175 mChannelCount = channelCount;
4176 mChannelMask = channelMask;
4177 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4178 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4179 // Force underrun condition to avoid false underrun callback until first data is
4180 // written to buffer (other flags are cleared)
4181 mCblk->flags = CBLK_UNDERRUN_ON;
4182 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184}
4185
4186AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4187{
Glenn Kastena0d68332012-01-27 16:47:15 -08004188 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004189 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004191 } else {
4192 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 }
4194 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004195 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004196 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004197 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004199 // If the client's reference count drops to zero, the associated destructor
4200 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4201 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mClient.clear();
4203 }
4204}
4205
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004206// AudioBufferProvider interface
4207// getNextBuffer() = 0;
4208// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4210{
Glenn Kastene0feee32011-12-13 11:53:26 -08004211 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004213 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004214 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 buffer->frameCount = 0;
4216}
4217
4218bool AudioFlinger::ThreadBase::TrackBase::step() {
4219 bool result;
4220 audio_track_cblk_t* cblk = this->cblk();
4221
4222 result = cblk->stepServer(mFrameCount);
4223 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004224 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004225 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 }
4227 return result;
4228}
4229
4230void AudioFlinger::ThreadBase::TrackBase::reset() {
4231 audio_track_cblk_t* cblk = this->cblk();
4232
4233 cblk->user = 0;
4234 cblk->server = 0;
4235 cblk->userBase = 0;
4236 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004237 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004238 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239}
4240
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4242 return (int)mCblk->sampleRate;
4243}
4244
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4246 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004247 size_t frameSize = cblk->frameSize;
4248 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4249 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250
4251 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004252 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4253 "TrackBase::getBuffer buffer out of range:\n"
4254 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4255 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004257 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258
4259 return bufferStart;
4260}
4261
Eric Laurenta011e352012-03-29 15:51:43 -07004262status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4263{
4264 mSyncEvents.add(event);
4265 return NO_ERROR;
4266}
4267
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268// ----------------------------------------------------------------------------
4269
4270// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4271AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004272 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004274 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004276 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004277 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278 int frameCount,
4279 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004280 int sessionId,
4281 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004282 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004283 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004284 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004285 // mRetryCount initialized later when needed
4286 mSharedBuffer(sharedBuffer),
4287 mStreamType(streamType),
4288 mName(-1), // see note below
4289 mMainBuffer(thread->mixBuffer()),
4290 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004291 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004292 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004293 mFlags(flags),
4294 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004295 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004296 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297{
4298 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4300 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004301 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004302 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4303 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004304 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004305 if (mName < 0) {
4306 ALOGE("no more track names available");
4307 return;
4308 }
4309 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004310 if (flags & IAudioFlinger::TRACK_FAST) {
4311 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4312 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4313 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004314 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004315 // FIXME This is too eager. We allocate a fast track index before the
4316 // fast track becomes active. Since fast tracks are a scarce resource,
4317 // this means we are potentially denying other more important fast tracks from
4318 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004319 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004320 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004321 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004322 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004323 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004326 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327}
4328
4329AudioFlinger::PlaybackThread::Track::~Track()
4330{
Steve Block3856b092011-10-20 11:56:00 +01004331 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004332 sp<ThreadBase> thread = mThread.promote();
4333 if (thread != 0) {
4334 Mutex::Autolock _l(thread->mLock);
4335 mState = TERMINATED;
4336 }
4337}
4338
4339void AudioFlinger::PlaybackThread::Track::destroy()
4340{
4341 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4342 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004343 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 // we must acquire a strong reference on this Track before locking mLock
4345 // here so that the destructor is called only when exiting this function.
4346 // On the other hand, as long as Track::destroy() is only called by
4347 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4348 // this Track with its member mTrack.
4349 sp<Track> keep(this);
4350 { // scope for mLock
4351 sp<ThreadBase> thread = mThread.promote();
4352 if (thread != 0) {
4353 if (!isOutputTrack()) {
4354 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004355 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004356
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004357#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004358 // to track the speaker usage
4359 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004360#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 }
4362 AudioSystem::releaseOutput(thread->id());
4363 }
4364 Mutex::Autolock _l(thread->mLock);
4365 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4366 playbackThread->destroyTrack_l(this);
4367 }
4368 }
4369}
4370
Glenn Kasten288ed212012-04-25 17:52:27 -07004371/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4372{
Glenn Kastene213c862012-04-25 13:46:15 -07004373 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 -07004374 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004375}
4376
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4378{
Glenn Kasten83d86532012-01-17 14:39:34 -08004379 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004380 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004381 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004382 } else {
4383 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4384 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004385 track_state state = mState;
4386 char stateChar;
4387 switch (state) {
4388 case IDLE:
4389 stateChar = 'I';
4390 break;
4391 case TERMINATED:
4392 stateChar = 'T';
4393 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004394 case STOPPING_1:
4395 stateChar = 's';
4396 break;
4397 case STOPPING_2:
4398 stateChar = '5';
4399 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004400 case STOPPED:
4401 stateChar = 'S';
4402 break;
4403 case RESUMING:
4404 stateChar = 'R';
4405 break;
4406 case ACTIVE:
4407 stateChar = 'A';
4408 break;
4409 case PAUSING:
4410 stateChar = 'p';
4411 break;
4412 case PAUSED:
4413 stateChar = 'P';
4414 break;
Eric Laurent29864602012-05-08 18:57:51 -07004415 case FLUSHED:
4416 stateChar = 'F';
4417 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004418 default:
4419 stateChar = '?';
4420 break;
4421 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004422 char nowInUnderrun;
4423 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4424 case UNDERRUN_FULL:
4425 nowInUnderrun = ' ';
4426 break;
4427 case UNDERRUN_PARTIAL:
4428 nowInUnderrun = '<';
4429 break;
4430 case UNDERRUN_EMPTY:
4431 nowInUnderrun = '*';
4432 break;
4433 default:
4434 nowInUnderrun = '?';
4435 break;
4436 }
Glenn Kastene213c862012-04-25 13:46:15 -07004437 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4438 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004439 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 mStreamType,
4441 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004442 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 mSessionId,
4444 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004445 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004446 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 mMute,
4448 mFillingUpStatus,
4449 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004450 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4451 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452 mCblk->server,
4453 mCblk->user,
4454 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004455 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004456 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004457 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004458 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459}
4460
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004461// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004462status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004463 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004465 audio_track_cblk_t* cblk = this->cblk();
4466 uint32_t framesReady;
4467 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004469 // Check if last stepServer failed, try to step now
4470 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004471 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4472 // Since the fast mixer is higher priority than client callback thread,
4473 // it does not result in priority inversion for client.
4474 // But a non-blocking solution would be preferable to avoid
4475 // fast mixer being unable to tryLock(), and
4476 // to avoid the extra context switches if the client wakes up,
4477 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004478 if (!step()) goto getNextBuffer_exit;
4479 ALOGV("stepServer recovered");
4480 mStepServerFailed = false;
4481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482
Glenn Kasten288ed212012-04-25 17:52:27 -07004483 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004484 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004486 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 uint32_t s = cblk->server;
4488 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4489
4490 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4491 if (framesReq > framesReady) {
4492 framesReq = framesReady;
4493 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004494 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 framesReq = bufferEnd - s;
4496 }
4497
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004498 buffer->raw = getBuffer(s, framesReq);
4499 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004501 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504
4505getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004506 buffer->raw = NULL;
4507 buffer->frameCount = 0;
4508 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4509 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510}
4511
Glenn Kasten288ed212012-04-25 17:52:27 -07004512// Note that framesReady() takes a mutex on the control block using tryLock().
4513// This could result in priority inversion if framesReady() is called by the normal mixer,
4514// as the normal mixer thread runs at lower
4515// priority than the client's callback thread: there is a short window within framesReady()
4516// during which the normal mixer could be preempted, and the client callback would block.
4517// Another problem can occur if framesReady() is called by the fast mixer:
4518// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4519// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4520size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004521 return mCblk->framesReady();
4522}
4523
Glenn Kasten288ed212012-04-25 17:52:27 -07004524// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004526 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527
John Grossman4ff14ba2012-02-08 16:37:41 -08004528 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004529 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4530 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004531 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 return true;
4533 }
4534 return false;
4535}
4536
Glenn Kasten3acbd052012-02-28 10:39:56 -08004537status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004538 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539{
4540 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004541 ALOGV("start(%d), calling pid %d session %d",
4542 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004543
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 sp<ThreadBase> thread = mThread.promote();
4545 if (thread != 0) {
4546 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004547 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 // here the track could be either new, or restarted
4549 // in both cases "unstop" the track
4550 if (mState == PAUSED) {
4551 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004552 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 } else {
4554 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004555 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 }
4557
4558 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4559 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004560 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004562
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004563#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004564 // to track the speaker usage
4565 if (status == NO_ERROR) {
4566 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4567 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004568#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 }
4570 if (status == NO_ERROR) {
4571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4572 playbackThread->addTrack_l(this);
4573 } else {
4574 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004575 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 }
4577 } else {
4578 status = BAD_VALUE;
4579 }
4580 return status;
4581}
4582
4583void AudioFlinger::PlaybackThread::Track::stop()
4584{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004585 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 sp<ThreadBase> thread = mThread.promote();
4587 if (thread != 0) {
4588 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004589 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004590 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 // If the track is not active (PAUSED and buffers full), flush buffers
4592 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4593 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4594 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004595 mState = STOPPED;
4596 } else if (!isFastTrack()) {
4597 mState = STOPPED;
4598 } else {
4599 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4600 // and then to STOPPED and reset() when presentation is complete
4601 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004603 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 }
4605 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4606 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004607 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004609
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004610#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004611 // to track the speaker usage
4612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004613#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 }
4615 }
4616}
4617
4618void AudioFlinger::PlaybackThread::Track::pause()
4619{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004620 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 sp<ThreadBase> thread = mThread.promote();
4622 if (thread != 0) {
4623 Mutex::Autolock _l(thread->mLock);
4624 if (mState == ACTIVE || mState == RESUMING) {
4625 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004626 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 if (!isOutputTrack()) {
4628 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004629 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004631
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004632#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004633 // to track the speaker usage
4634 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004635#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 }
4637 }
4638 }
4639}
4640
4641void AudioFlinger::PlaybackThread::Track::flush()
4642{
Steve Block3856b092011-10-20 11:56:00 +01004643 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 sp<ThreadBase> thread = mThread.promote();
4645 if (thread != 0) {
4646 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004647 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4648 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 return;
4650 }
4651 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004652 // FLUSHED state
4653 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004654 // do not reset the track if it is still in the process of being stopped or paused.
4655 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004656 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004657 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4659 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4660 reset();
4661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 }
4663}
4664
4665void AudioFlinger::PlaybackThread::Track::reset()
4666{
4667 // Do not reset twice to avoid discarding data written just after a flush and before
4668 // the audioflinger thread detects the track is stopped.
4669 if (!mResetDone) {
4670 TrackBase::reset();
4671 // Force underrun condition to avoid false underrun callback until first data is
4672 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004673 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4674 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675 mFillingUpStatus = FS_FILLING;
4676 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004677 if (mState == FLUSHED) {
4678 mState = IDLE;
4679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 }
4681}
4682
4683void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4684{
4685 mMute = muted;
4686}
4687
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4689{
4690 status_t status = DEAD_OBJECT;
4691 sp<ThreadBase> thread = mThread.promote();
4692 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004693 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004694 sp<AudioFlinger> af = mClient->audioFlinger();
4695
4696 Mutex::Autolock _l(af->mLock);
4697
4698 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004699
Eric Laurent109347d2012-07-02 12:31:03 -07004700 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004701 Mutex::Autolock _dl(playbackThread->mLock);
4702 Mutex::Autolock _sl(srcThread->mLock);
4703 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4704 if (chain == 0) {
4705 return INVALID_OPERATION;
4706 }
4707
4708 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4709 if (effect == 0) {
4710 return INVALID_OPERATION;
4711 }
4712 srcThread->removeEffect_l(effect);
4713 playbackThread->addEffect_l(effect);
4714 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4715 if (effect->state() == EffectModule::ACTIVE ||
4716 effect->state() == EffectModule::STOPPING) {
4717 effect->start();
4718 }
4719
4720 sp<EffectChain> dstChain = effect->chain().promote();
4721 if (dstChain == 0) {
4722 srcThread->addEffect_l(effect);
4723 return INVALID_OPERATION;
4724 }
4725 AudioSystem::unregisterEffect(effect->id());
4726 AudioSystem::registerEffect(&effect->desc(),
4727 srcThread->id(),
4728 dstChain->strategy(),
4729 AUDIO_SESSION_OUTPUT_MIX,
4730 effect->id());
4731 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004732 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733 }
4734 return status;
4735}
4736
4737void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4738{
4739 mAuxEffectId = EffectId;
4740 mAuxBuffer = buffer;
4741}
4742
Eric Laurenta011e352012-03-29 15:51:43 -07004743bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4744 size_t audioHalFrames)
4745{
4746 // a track is considered presented when the total number of frames written to audio HAL
4747 // corresponds to the number of frames written when presentationComplete() is called for the
4748 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4749 if (mPresentationCompleteFrames == 0) {
4750 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4751 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4752 mPresentationCompleteFrames, audioHalFrames);
4753 }
4754 if (framesWritten >= mPresentationCompleteFrames) {
4755 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4756 mSessionId, framesWritten);
4757 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004758 return true;
4759 }
4760 return false;
4761}
4762
4763void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4764{
4765 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4766 if (mSyncEvents[i]->type() == type) {
4767 mSyncEvents[i]->trigger();
4768 mSyncEvents.removeAt(i);
4769 i--;
4770 }
4771 }
4772}
4773
Glenn Kasten58912562012-04-03 10:45:00 -07004774// implement VolumeBufferProvider interface
4775
4776uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4777{
4778 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4779 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4780 uint32_t vlr = mCblk->getVolumeLR();
4781 uint32_t vl = vlr & 0xFFFF;
4782 uint32_t vr = vlr >> 16;
4783 // track volumes come from shared memory, so can't be trusted and must be clamped
4784 if (vl > MAX_GAIN_INT) {
4785 vl = MAX_GAIN_INT;
4786 }
4787 if (vr > MAX_GAIN_INT) {
4788 vr = MAX_GAIN_INT;
4789 }
4790 // now apply the cached master volume and stream type volume;
4791 // this is trusted but lacks any synchronization or barrier so may be stale
4792 float v = mCachedVolume;
4793 vl *= v;
4794 vr *= v;
4795 // re-combine into U4.16
4796 vlr = (vr << 16) | (vl & 0xFFFF);
4797 // FIXME look at mute, pause, and stop flags
4798 return vlr;
4799}
Eric Laurenta011e352012-03-29 15:51:43 -07004800
Eric Laurent29864602012-05-08 18:57:51 -07004801status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4802{
4803 if (mState == TERMINATED || mState == PAUSED ||
4804 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4805 (mState == STOPPED)))) {
4806 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4807 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4808 event->cancel();
4809 return INVALID_OPERATION;
4810 }
4811 TrackBase::setSyncEvent(event);
4812 return NO_ERROR;
4813}
4814
John Grossman4ff14ba2012-02-08 16:37:41 -08004815// timed audio tracks
4816
4817sp<AudioFlinger::PlaybackThread::TimedTrack>
4818AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004819 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004820 const sp<Client>& client,
4821 audio_stream_type_t streamType,
4822 uint32_t sampleRate,
4823 audio_format_t format,
4824 uint32_t channelMask,
4825 int frameCount,
4826 const sp<IMemory>& sharedBuffer,
4827 int sessionId) {
4828 if (!client->reserveTimedTrack())
4829 return NULL;
4830
Glenn Kastena0356762012-03-19 10:38:51 -07004831 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004832 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4833 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004834}
4835
4836AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004837 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004838 const sp<Client>& client,
4839 audio_stream_type_t streamType,
4840 uint32_t sampleRate,
4841 audio_format_t format,
4842 uint32_t channelMask,
4843 int frameCount,
4844 const sp<IMemory>& sharedBuffer,
4845 int sessionId)
4846 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004847 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004848 mQueueHeadInFlight(false),
4849 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004850 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004851 mTimedSilenceBuffer(NULL),
4852 mTimedSilenceBufferSize(0),
4853 mTimedAudioOutputOnTime(false),
4854 mMediaTimeTransformValid(false)
4855{
4856 LocalClock lc;
4857 mLocalTimeFreq = lc.getLocalFreq();
4858
4859 mLocalTimeToSampleTransform.a_zero = 0;
4860 mLocalTimeToSampleTransform.b_zero = 0;
4861 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4862 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4863 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4864 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004865
4866 mMediaTimeToSampleTransform.a_zero = 0;
4867 mMediaTimeToSampleTransform.b_zero = 0;
4868 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4869 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4870 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4871 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004872}
4873
4874AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4875 mClient->releaseTimedTrack();
4876 delete [] mTimedSilenceBuffer;
4877}
4878
4879status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4880 size_t size, sp<IMemory>* buffer) {
4881
4882 Mutex::Autolock _l(mTimedBufferQueueLock);
4883
4884 trimTimedBufferQueue_l();
4885
4886 // lazily initialize the shared memory heap for timed buffers
4887 if (mTimedMemoryDealer == NULL) {
4888 const int kTimedBufferHeapSize = 512 << 10;
4889
4890 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4891 "AudioFlingerTimed");
4892 if (mTimedMemoryDealer == NULL)
4893 return NO_MEMORY;
4894 }
4895
4896 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4897 if (newBuffer == NULL) {
4898 newBuffer = mTimedMemoryDealer->allocate(size);
4899 if (newBuffer == NULL)
4900 return NO_MEMORY;
4901 }
4902
4903 *buffer = newBuffer;
4904 return NO_ERROR;
4905}
4906
4907// caller must hold mTimedBufferQueueLock
4908void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4909 int64_t mediaTimeNow;
4910 {
4911 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4912 if (!mMediaTimeTransformValid)
4913 return;
4914
4915 int64_t targetTimeNow;
4916 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4917 ? mCCHelper.getCommonTime(&targetTimeNow)
4918 : mCCHelper.getLocalTime(&targetTimeNow);
4919
4920 if (OK != res)
4921 return;
4922
4923 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4924 &mediaTimeNow)) {
4925 return;
4926 }
4927 }
4928
John Grossman1c345192012-03-27 14:00:17 -07004929 size_t trimEnd;
4930 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004931 int64_t bufEnd;
4932
John Grossmanc95cfbb2012-04-12 11:53:11 -07004933 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4934 // We have a next buffer. Just use its PTS as the PTS of the frame
4935 // following the last frame in this buffer. If the stream is sparse
4936 // (ie, there are deliberate gaps left in the stream which should be
4937 // filled with silence by the TimedAudioTrack), then this can result
4938 // in one extra buffer being left un-trimmed when it could have
4939 // been. In general, this is not typical, and we would rather
4940 // optimized away the TS calculation below for the more common case
4941 // where PTSes are contiguous.
4942 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4943 } else {
4944 // We have no next buffer. Compute the PTS of the frame following
4945 // the last frame in this buffer by computing the duration of of
4946 // this frame in media time units and adding it to the PTS of the
4947 // buffer.
4948 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4949 / mCblk->frameSize;
4950
4951 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4952 &bufEnd)) {
4953 ALOGE("Failed to convert frame count of %lld to media time"
4954 " duration" " (scale factor %d/%u) in %s",
4955 frameCount,
4956 mMediaTimeToSampleTransform.a_to_b_numer,
4957 mMediaTimeToSampleTransform.a_to_b_denom,
4958 __PRETTY_FUNCTION__);
4959 break;
4960 }
4961 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004962 }
John Grossman9fbdee12012-03-26 17:51:46 -07004963
4964 if (bufEnd > mediaTimeNow)
4965 break;
4966
4967 // Is the buffer we want to use in the middle of a mix operation right
4968 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4969 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004970 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004971 mTrimQueueHeadOnRelease = true;
4972 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004973 }
4974
John Grossman9fbdee12012-03-26 17:51:46 -07004975 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004976 if (trimStart < trimEnd) {
4977 // Update the bookkeeping for framesReady()
4978 for (size_t i = trimStart; i < trimEnd; ++i) {
4979 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4980 }
4981
4982 // Now actually remove the buffers from the queue.
4983 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004984 }
4985}
4986
John Grossman1c345192012-03-27 14:00:17 -07004987void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4988 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004989 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4990 "%s called (reason \"%s\"), but timed buffer queue has no"
4991 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004992
4993 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4994 mTimedBufferQueue.removeAt(0);
4995}
4996
4997void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4998 const TimedBuffer& buf,
4999 const char* logTag) {
5000 uint32_t bufBytes = buf.buffer()->size();
5001 uint32_t consumedAlready = buf.position();
5002
Eric Laurentb388e532012-04-14 13:32:48 -07005003 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005004 "Bad bookkeeping while updating frames pending. Timed buffer is"
5005 " only %u bytes long, but claims to have consumed %u"
5006 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005007 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005008
5009 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005010 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5011 "Bad bookkeeping while updating frames pending. Should have at"
5012 " least %u queued frames, but we think we have only %u. (update"
5013 " reason: \"%s\")",
5014 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005015
5016 mFramesPendingInQueue -= bufFrames;
5017}
5018
John Grossman4ff14ba2012-02-08 16:37:41 -08005019status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5020 const sp<IMemory>& buffer, int64_t pts) {
5021
5022 {
5023 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5024 if (!mMediaTimeTransformValid)
5025 return INVALID_OPERATION;
5026 }
5027
5028 Mutex::Autolock _l(mTimedBufferQueueLock);
5029
John Grossman1c345192012-03-27 14:00:17 -07005030 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5031 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005032 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5033
5034 return NO_ERROR;
5035}
5036
5037status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5038 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5039
John Grossman1c345192012-03-27 14:00:17 -07005040 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5041 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5042 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005043
5044 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5045 target == TimedAudioTrack::COMMON_TIME)) {
5046 return BAD_VALUE;
5047 }
5048
5049 Mutex::Autolock lock(mMediaTimeTransformLock);
5050 mMediaTimeTransform = xform;
5051 mMediaTimeTransformTarget = target;
5052 mMediaTimeTransformValid = true;
5053
5054 return NO_ERROR;
5055}
5056
5057#define min(a, b) ((a) < (b) ? (a) : (b))
5058
5059// implementation of getNextBuffer for tracks whose buffers have timestamps
5060status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5061 AudioBufferProvider::Buffer* buffer, int64_t pts)
5062{
5063 if (pts == AudioBufferProvider::kInvalidPTS) {
5064 buffer->raw = 0;
5065 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005066 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 return INVALID_OPERATION;
5068 }
5069
John Grossman4ff14ba2012-02-08 16:37:41 -08005070 Mutex::Autolock _l(mTimedBufferQueueLock);
5071
John Grossman9fbdee12012-03-26 17:51:46 -07005072 ALOG_ASSERT(!mQueueHeadInFlight,
5073 "getNextBuffer called without releaseBuffer!");
5074
John Grossman4ff14ba2012-02-08 16:37:41 -08005075 while (true) {
5076
5077 // if we have no timed buffers, then fail
5078 if (mTimedBufferQueue.isEmpty()) {
5079 buffer->raw = 0;
5080 buffer->frameCount = 0;
5081 return NOT_ENOUGH_DATA;
5082 }
5083
5084 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5085
5086 // calculate the PTS of the head of the timed buffer queue expressed in
5087 // local time
5088 int64_t headLocalPTS;
5089 {
5090 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5091
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005092 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005093
5094 if (mMediaTimeTransform.a_to_b_denom == 0) {
5095 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005096 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005097 return NO_ERROR;
5098 }
5099
5100 int64_t transformedPTS;
5101 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5102 &transformedPTS)) {
5103 // the transform failed. this shouldn't happen, but if it does
5104 // then just drop this buffer
5105 ALOGW("timedGetNextBuffer transform failed");
5106 buffer->raw = 0;
5107 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005108 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005109 return NO_ERROR;
5110 }
5111
5112 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5113 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5114 &headLocalPTS)) {
5115 buffer->raw = 0;
5116 buffer->frameCount = 0;
5117 return INVALID_OPERATION;
5118 }
5119 } else {
5120 headLocalPTS = transformedPTS;
5121 }
5122 }
5123
5124 // adjust the head buffer's PTS to reflect the portion of the head buffer
5125 // that has already been consumed
5126 int64_t effectivePTS = headLocalPTS +
5127 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5128
5129 // Calculate the delta in samples between the head of the input buffer
5130 // queue and the start of the next output buffer that will be written.
5131 // If the transformation fails because of over or underflow, it means
5132 // that the sample's position in the output stream is so far out of
5133 // whack that it should just be dropped.
5134 int64_t sampleDelta;
5135 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5136 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005137 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5138 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005139 continue;
5140 }
5141 if (!mLocalTimeToSampleTransform.doForwardTransform(
5142 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005143 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005144 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 continue;
5146 }
5147
John Grossman1c345192012-03-27 14:00:17 -07005148 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5149 " sampleDelta=[%d.%08x]",
5150 head.pts(), head.position(), pts,
5151 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5152 + (sampleDelta >> 32)),
5153 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005154
5155 // if the delta between the ideal placement for the next input sample and
5156 // the current output position is within this threshold, then we will
5157 // concatenate the next input samples to the previous output
5158 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005159 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005160
5161 // if this is the first buffer of audio that we're emitting from this track
5162 // then it should be almost exactly on time.
5163 const int64_t kSampleStartupThreshold = 1LL << 32;
5164
5165 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005166 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005167 // the next input is close enough to being on time, so concatenate it
5168 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005169 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005170
John Grossman1c345192012-03-27 14:00:17 -07005171 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5172 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005173 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005174 }
5175
5176 // Looks like our output is not on time. Reset our on timed status.
5177 // Next time we mix samples from our input queue, then should be within
5178 // the StartupThreshold.
5179 mTimedAudioOutputOnTime = false;
5180 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005181 // the gap between the current output position and the proper start of
5182 // the next input sample is too big, so fill it with silence
5183 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5184
John Grossman9fbdee12012-03-26 17:51:46 -07005185 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005186 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5187 return NO_ERROR;
5188 } else {
5189 // the next input sample is late
5190 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5191 size_t onTimeSamplePosition =
5192 head.position() + lateFrames * mCblk->frameSize;
5193
5194 if (onTimeSamplePosition > head.buffer()->size()) {
5195 // all the remaining samples in the head are too late, so
5196 // drop it and move on
5197 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005198 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005199 continue;
5200 } else {
5201 // skip over the late samples
5202 head.setPosition(onTimeSamplePosition);
5203
5204 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005205 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005206
5207 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5208 return NO_ERROR;
5209 }
5210 }
5211 }
5212}
5213
5214// Yield samples from the timed buffer queue head up to the given output
5215// buffer's capacity.
5216//
5217// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005218void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005219 AudioBufferProvider::Buffer* buffer) {
5220
5221 const TimedBuffer& head = mTimedBufferQueue[0];
5222
5223 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5224 head.position());
5225
5226 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5227 mCblk->frameSize);
5228 size_t framesRequested = buffer->frameCount;
5229 buffer->frameCount = min(framesLeftInHead, framesRequested);
5230
John Grossman9fbdee12012-03-26 17:51:46 -07005231 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005232 mTimedAudioOutputOnTime = true;
5233}
5234
5235// Yield samples of silence up to the given output buffer's capacity
5236//
5237// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005238void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005239 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5240
5241 // lazily allocate a buffer filled with silence
5242 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5243 delete [] mTimedSilenceBuffer;
5244 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5245 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5246 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5247 }
5248
5249 buffer->raw = mTimedSilenceBuffer;
5250 size_t framesRequested = buffer->frameCount;
5251 buffer->frameCount = min(numFrames, framesRequested);
5252
5253 mTimedAudioOutputOnTime = false;
5254}
5255
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005256// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005257void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5258 AudioBufferProvider::Buffer* buffer) {
5259
5260 Mutex::Autolock _l(mTimedBufferQueueLock);
5261
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005262 // If the buffer which was just released is part of the buffer at the head
5263 // of the queue, be sure to update the amt of the buffer which has been
5264 // consumed. If the buffer being returned is not part of the head of the
5265 // queue, its either because the buffer is part of the silence buffer, or
5266 // because the head of the timed queue was trimmed after the mixer called
5267 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005268 if (buffer->raw == mTimedSilenceBuffer) {
5269 ALOG_ASSERT(!mQueueHeadInFlight,
5270 "Queue head in flight during release of silence buffer!");
5271 goto done;
5272 }
5273
5274 ALOG_ASSERT(mQueueHeadInFlight,
5275 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5276 " head in flight.");
5277
5278 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005279 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005280
5281 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005282 void* end = reinterpret_cast<void*>(
5283 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5284 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005285
John Grossman9fbdee12012-03-26 17:51:46 -07005286 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5287 "released buffer not within the head of the timed buffer"
5288 " queue; qHead = [%p, %p], released buffer = %p",
5289 start, end, buffer->raw);
5290
5291 head.setPosition(head.position() +
5292 (buffer->frameCount * mCblk->frameSize));
5293 mQueueHeadInFlight = false;
5294
John Grossman1c345192012-03-27 14:00:17 -07005295 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5296 "Bad bookkeeping during releaseBuffer! Should have at"
5297 " least %u queued frames, but we think we have only %u",
5298 buffer->frameCount, mFramesPendingInQueue);
5299
5300 mFramesPendingInQueue -= buffer->frameCount;
5301
John Grossman9fbdee12012-03-26 17:51:46 -07005302 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5303 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005304 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005305 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005306 }
John Grossman9fbdee12012-03-26 17:51:46 -07005307 } else {
5308 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5309 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005310 }
5311
John Grossman9fbdee12012-03-26 17:51:46 -07005312done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005313 buffer->raw = 0;
5314 buffer->frameCount = 0;
5315}
5316
Glenn Kasten288ed212012-04-25 17:52:27 -07005317size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005318 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005319 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005320}
5321
5322AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5323 : mPTS(0), mPosition(0) {}
5324
5325AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5326 const sp<IMemory>& buffer, int64_t pts)
5327 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5328
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329// ----------------------------------------------------------------------------
5330
5331// RecordTrack constructor must be called with AudioFlinger::mLock held
5332AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005333 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 const sp<Client>& client,
5335 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005336 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005337 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339 int sessionId)
5340 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005341 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 mOverflow(false)
5343{
5344 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005345 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5346 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5347 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5348 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5349 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5350 } else {
5351 mCblk->frameSize = sizeof(int8_t);
5352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 }
5354}
5355
5356AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5357{
5358 sp<ThreadBase> thread = mThread.promote();
5359 if (thread != 0) {
5360 AudioSystem::releaseInput(thread->id());
5361 }
5362}
5363
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005364// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005365status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366{
5367 audio_track_cblk_t* cblk = this->cblk();
5368 uint32_t framesAvail;
5369 uint32_t framesReq = buffer->frameCount;
5370
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005371 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005372 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005374 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005375 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 }
5377
5378 framesAvail = cblk->framesAvailable_l();
5379
Glenn Kastenf6b16782011-12-15 09:51:17 -08005380 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381 uint32_t s = cblk->server;
5382 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5383
5384 if (framesReq > framesAvail) {
5385 framesReq = framesAvail;
5386 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005387 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 framesReq = bufferEnd - s;
5389 }
5390
5391 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005392 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393
5394 buffer->frameCount = framesReq;
5395 return NO_ERROR;
5396 }
5397
5398getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005399 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 buffer->frameCount = 0;
5401 return NOT_ENOUGH_DATA;
5402}
5403
Glenn Kasten3acbd052012-02-28 10:39:56 -08005404status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005405 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406{
5407 sp<ThreadBase> thread = mThread.promote();
5408 if (thread != 0) {
5409 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005410 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 } else {
5412 return BAD_VALUE;
5413 }
5414}
5415
5416void AudioFlinger::RecordThread::RecordTrack::stop()
5417{
5418 sp<ThreadBase> thread = mThread.promote();
5419 if (thread != 0) {
5420 RecordThread *recordThread = (RecordThread *)thread.get();
5421 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005422 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005423 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005424 // read from buffer
5425 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 }
5427}
5428
5429void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5430{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005431 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005432 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005434 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 mSessionId,
5436 mFrameCount,
5437 mState,
5438 mCblk->sampleRate,
5439 mCblk->server,
5440 mCblk->user);
5441}
5442
5443
5444// ----------------------------------------------------------------------------
5445
5446AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005447 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 DuplicatingThread *sourceThread,
5449 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005450 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005451 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005453 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5454 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 mActive(false), mSourceThread(sourceThread)
5456{
5457
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 if (mCblk != NULL) {
5459 mCblk->flags |= CBLK_DIRECTION_OUT;
5460 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 mOutBuffer.frameCount = 0;
5462 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005463 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005464 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5465 mCblk, mBuffer, mCblk->buffers,
5466 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 }
5470}
5471
5472AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5473{
5474 clearBufferQueue();
5475}
5476
Glenn Kasten3acbd052012-02-28 10:39:56 -08005477status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005478 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005480 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 if (status != NO_ERROR) {
5482 return status;
5483 }
5484
5485 mActive = true;
5486 mRetryCount = 127;
5487 return status;
5488}
5489
5490void AudioFlinger::PlaybackThread::OutputTrack::stop()
5491{
5492 Track::stop();
5493 clearBufferQueue();
5494 mOutBuffer.frameCount = 0;
5495 mActive = false;
5496}
5497
5498bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5499{
5500 Buffer *pInBuffer;
5501 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005502 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 bool outputBufferFull = false;
5504 inBuffer.frameCount = frames;
5505 inBuffer.i16 = data;
5506
5507 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5508
5509 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005510 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 sp<ThreadBase> thread = mThread.promote();
5512 if (thread != 0) {
5513 MixerThread *mixerThread = (MixerThread *)thread.get();
5514 if (mCblk->frameCount > frames){
5515 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5516 uint32_t startFrames = (mCblk->frameCount - frames);
5517 pInBuffer = new Buffer;
5518 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5519 pInBuffer->frameCount = startFrames;
5520 pInBuffer->i16 = pInBuffer->mBuffer;
5521 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5522 mBufferQueue.add(pInBuffer);
5523 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005524 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 }
5526 }
5527 }
5528 }
5529
5530 while (waitTimeLeftMs) {
5531 // First write pending buffers, then new data
5532 if (mBufferQueue.size()) {
5533 pInBuffer = mBufferQueue.itemAt(0);
5534 } else {
5535 pInBuffer = &inBuffer;
5536 }
5537
5538 if (pInBuffer->frameCount == 0) {
5539 break;
5540 }
5541
5542 if (mOutBuffer.frameCount == 0) {
5543 mOutBuffer.frameCount = pInBuffer->frameCount;
5544 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005545 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005546 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 outputBufferFull = true;
5548 break;
5549 }
5550 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5551 if (waitTimeLeftMs >= waitTimeMs) {
5552 waitTimeLeftMs -= waitTimeMs;
5553 } else {
5554 waitTimeLeftMs = 0;
5555 }
5556 }
5557
5558 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5559 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5560 mCblk->stepUser(outFrames);
5561 pInBuffer->frameCount -= outFrames;
5562 pInBuffer->i16 += outFrames * channelCount;
5563 mOutBuffer.frameCount -= outFrames;
5564 mOutBuffer.i16 += outFrames * channelCount;
5565
5566 if (pInBuffer->frameCount == 0) {
5567 if (mBufferQueue.size()) {
5568 mBufferQueue.removeAt(0);
5569 delete [] pInBuffer->mBuffer;
5570 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005571 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 } else {
5573 break;
5574 }
5575 }
5576 }
5577
5578 // If we could not write all frames, allocate a buffer and queue it for next time.
5579 if (inBuffer.frameCount) {
5580 sp<ThreadBase> thread = mThread.promote();
5581 if (thread != 0 && !thread->standby()) {
5582 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5583 pInBuffer = new Buffer;
5584 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5585 pInBuffer->frameCount = inBuffer.frameCount;
5586 pInBuffer->i16 = pInBuffer->mBuffer;
5587 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5588 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005589 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005591 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 }
5593 }
5594 }
5595
5596 // Calling write() with a 0 length buffer, means that no more data will be written:
5597 // If no more buffers are pending, fill output track buffer to make sure it is started
5598 // by output mixer.
5599 if (frames == 0 && mBufferQueue.size() == 0) {
5600 if (mCblk->user < mCblk->frameCount) {
5601 frames = mCblk->frameCount - mCblk->user;
5602 pInBuffer = new Buffer;
5603 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5604 pInBuffer->frameCount = frames;
5605 pInBuffer->i16 = pInBuffer->mBuffer;
5606 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5607 mBufferQueue.add(pInBuffer);
5608 } else if (mActive) {
5609 stop();
5610 }
5611 }
5612
5613 return outputBufferFull;
5614}
5615
5616status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5617{
5618 int active;
5619 status_t result;
5620 audio_track_cblk_t* cblk = mCblk;
5621 uint32_t framesReq = buffer->frameCount;
5622
Steve Block3856b092011-10-20 11:56:00 +01005623// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005624 buffer->frameCount = 0;
5625
5626 uint32_t framesAvail = cblk->framesAvailable();
5627
5628
5629 if (framesAvail == 0) {
5630 Mutex::Autolock _l(cblk->lock);
5631 goto start_loop_here;
5632 while (framesAvail == 0) {
5633 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005634 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005635 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005636 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637 }
5638 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5639 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005640 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 }
5642 // read the server count again
5643 start_loop_here:
5644 framesAvail = cblk->framesAvailable_l();
5645 }
5646 }
5647
5648// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005649// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650// }
5651
5652 if (framesReq > framesAvail) {
5653 framesReq = framesAvail;
5654 }
5655
5656 uint32_t u = cblk->user;
5657 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5658
Marco Nelissena1472d92012-03-30 14:36:54 -07005659 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 framesReq = bufferEnd - u;
5661 }
5662
5663 buffer->frameCount = framesReq;
5664 buffer->raw = (void *)cblk->buffer(u);
5665 return NO_ERROR;
5666}
5667
5668
5669void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5670{
5671 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672
5673 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005674 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 delete [] pBuffer->mBuffer;
5676 delete pBuffer;
5677 }
5678 mBufferQueue.clear();
5679}
5680
5681// ----------------------------------------------------------------------------
5682
5683AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5684 : RefBase(),
5685 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005686 // 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 -07005687 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005688 mPid(pid),
5689 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690{
5691 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5692}
5693
5694// Client destructor must be called with AudioFlinger::mLock held
5695AudioFlinger::Client::~Client()
5696{
5697 mAudioFlinger->removeClient_l(mPid);
5698}
5699
Glenn Kasten435dbe62012-01-30 10:15:48 -08005700sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701{
5702 return mMemoryDealer;
5703}
5704
John Grossman4ff14ba2012-02-08 16:37:41 -08005705// Reserve one of the limited slots for a timed audio track associated
5706// with this client
5707bool AudioFlinger::Client::reserveTimedTrack()
5708{
5709 const int kMaxTimedTracksPerClient = 4;
5710
5711 Mutex::Autolock _l(mTimedTrackLock);
5712
5713 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5714 ALOGW("can not create timed track - pid %d has exceeded the limit",
5715 mPid);
5716 return false;
5717 }
5718
5719 mTimedTrackCount++;
5720 return true;
5721}
5722
5723// Release a slot for a timed audio track
5724void AudioFlinger::Client::releaseTimedTrack()
5725{
5726 Mutex::Autolock _l(mTimedTrackLock);
5727 mTimedTrackCount--;
5728}
5729
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730// ----------------------------------------------------------------------------
5731
5732AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5733 const sp<IAudioFlingerClient>& client,
5734 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005735 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736{
5737}
5738
5739AudioFlinger::NotificationClient::~NotificationClient()
5740{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741}
5742
5743void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5744{
5745 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005746 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747}
5748
5749// ----------------------------------------------------------------------------
5750
5751AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5752 : BnAudioTrack(),
5753 mTrack(track)
5754{
5755}
5756
5757AudioFlinger::TrackHandle::~TrackHandle() {
5758 // just stop the track on deletion, associated resources
5759 // will be freed from the main thread once all pending buffers have
5760 // been played. Unless it's not in the active track list, in which
5761 // case we free everything now...
5762 mTrack->destroy();
5763}
5764
Glenn Kasten90716c52012-01-26 13:40:12 -08005765sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5766 return mTrack->getCblk();
5767}
5768
Glenn Kasten3acbd052012-02-28 10:39:56 -08005769status_t AudioFlinger::TrackHandle::start() {
5770 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771}
5772
5773void AudioFlinger::TrackHandle::stop() {
5774 mTrack->stop();
5775}
5776
5777void AudioFlinger::TrackHandle::flush() {
5778 mTrack->flush();
5779}
5780
5781void AudioFlinger::TrackHandle::mute(bool e) {
5782 mTrack->mute(e);
5783}
5784
5785void AudioFlinger::TrackHandle::pause() {
5786 mTrack->pause();
5787}
5788
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5790{
5791 return mTrack->attachAuxEffect(EffectId);
5792}
5793
John Grossman4ff14ba2012-02-08 16:37:41 -08005794status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5795 sp<IMemory>* buffer) {
5796 if (!mTrack->isTimedTrack())
5797 return INVALID_OPERATION;
5798
5799 PlaybackThread::TimedTrack* tt =
5800 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5801 return tt->allocateTimedBuffer(size, buffer);
5802}
5803
5804status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5805 int64_t pts) {
5806 if (!mTrack->isTimedTrack())
5807 return INVALID_OPERATION;
5808
5809 PlaybackThread::TimedTrack* tt =
5810 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5811 return tt->queueTimedBuffer(buffer, pts);
5812}
5813
5814status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5815 const LinearTransform& xform, int target) {
5816
5817 if (!mTrack->isTimedTrack())
5818 return INVALID_OPERATION;
5819
5820 PlaybackThread::TimedTrack* tt =
5821 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5822 return tt->setMediaTimeTransform(
5823 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5824}
5825
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826status_t AudioFlinger::TrackHandle::onTransact(
5827 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5828{
5829 return BnAudioTrack::onTransact(code, data, reply, flags);
5830}
5831
5832// ----------------------------------------------------------------------------
5833
5834sp<IAudioRecord> AudioFlinger::openRecord(
5835 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005836 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005838 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005839 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005841 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 int *sessionId,
5843 status_t *status)
5844{
5845 sp<RecordThread::RecordTrack> recordTrack;
5846 sp<RecordHandle> recordHandle;
5847 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848 status_t lStatus;
5849 RecordThread *thread;
5850 size_t inFrameCount;
5851 int lSessionId;
5852
5853 // check calling permissions
5854 if (!recordingAllowed()) {
5855 lStatus = PERMISSION_DENIED;
5856 goto Exit;
5857 }
5858
5859 // add client to list
5860 { // scope for mLock
5861 Mutex::Autolock _l(mLock);
5862 thread = checkRecordThread_l(input);
5863 if (thread == NULL) {
5864 lStatus = BAD_VALUE;
5865 goto Exit;
5866 }
5867
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005868 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005869
5870 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005871 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 lSessionId = *sessionId;
5873 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005874 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 if (sessionId != NULL) {
5876 *sessionId = lSessionId;
5877 }
5878 }
5879 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 recordTrack = thread->createRecordTrack_l(client,
5881 sampleRate,
5882 format,
5883 channelMask,
5884 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005885 lSessionId,
5886 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005887 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005888 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5890 // destructor is called by the TrackBase destructor with mLock held
5891 client.clear();
5892 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893 goto Exit;
5894 }
5895
5896 // return to handle to client
5897 recordHandle = new RecordHandle(recordTrack);
5898 lStatus = NO_ERROR;
5899
5900Exit:
5901 if (status) {
5902 *status = lStatus;
5903 }
5904 return recordHandle;
5905}
5906
5907// ----------------------------------------------------------------------------
5908
5909AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5910 : BnAudioRecord(),
5911 mRecordTrack(recordTrack)
5912{
5913}
5914
5915AudioFlinger::RecordHandle::~RecordHandle() {
5916 stop();
5917}
5918
Glenn Kasten90716c52012-01-26 13:40:12 -08005919sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5920 return mRecordTrack->getCblk();
5921}
5922
Glenn Kasten3acbd052012-02-28 10:39:56 -08005923status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005924 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005925 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926}
5927
5928void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005929 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 mRecordTrack->stop();
5931}
5932
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933status_t AudioFlinger::RecordHandle::onTransact(
5934 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5935{
5936 return BnAudioRecord::onTransact(code, data, reply, flags);
5937}
5938
5939// ----------------------------------------------------------------------------
5940
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005941AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5942 AudioStreamIn *input,
5943 uint32_t sampleRate,
5944 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005945 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005946 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005947 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005948 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5949 // mRsmpInIndex and mInputBytes set by readInputParameters()
5950 mReqChannelCount(popcount(channels)),
5951 mReqSampleRate(sampleRate)
5952 // mBytesRead is only meaningful while active, and so is cleared in start()
5953 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954{
Glenn Kasten480b4682012-02-28 12:30:08 -08005955 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005956
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 readInputParameters();
5958}
5959
5960
5961AudioFlinger::RecordThread::~RecordThread()
5962{
5963 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005964 delete mResampler;
5965 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966}
5967
5968void AudioFlinger::RecordThread::onFirstRef()
5969{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005970 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971}
5972
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005973status_t AudioFlinger::RecordThread::readyToRun()
5974{
5975 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005976 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005977 return status;
5978}
5979
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980bool AudioFlinger::RecordThread::threadLoop()
5981{
5982 AudioBufferProvider::Buffer buffer;
5983 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005984 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985
Eric Laurent44d98482010-09-30 16:12:31 -07005986 nsecs_t lastWarning = 0;
5987
Eric Laurentfeb0db62011-07-22 09:04:31 -07005988 acquireWakeLock();
5989
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 // start recording
5991 while (!exitPending()) {
5992
5993 processConfigEvents();
5994
5995 { // scope for mLock
5996 Mutex::Autolock _l(mLock);
5997 checkForNewParameters_l();
5998 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5999 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006000 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 mStandby = true;
6002 }
6003
6004 if (exitPending()) break;
6005
Eric Laurentfeb0db62011-07-22 09:04:31 -07006006 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006007 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 // go to sleep
6009 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006010 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006011 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 continue;
6013 }
6014 if (mActiveTrack != 0) {
6015 if (mActiveTrack->mState == TrackBase::PAUSING) {
6016 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006017 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 mStandby = true;
6019 }
6020 mActiveTrack.clear();
6021 mStartStopCond.broadcast();
6022 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6023 if (mReqChannelCount != mActiveTrack->channelCount()) {
6024 mActiveTrack.clear();
6025 mStartStopCond.broadcast();
6026 } else if (mBytesRead != 0) {
6027 // record start succeeds only if first read from audio input
6028 // succeeds
6029 if (mBytesRead > 0) {
6030 mActiveTrack->mState = TrackBase::ACTIVE;
6031 } else {
6032 mActiveTrack.clear();
6033 }
6034 mStartStopCond.broadcast();
6035 }
6036 mStandby = false;
6037 }
6038 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 }
6041
6042 if (mActiveTrack != 0) {
6043 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6044 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 unlockEffectChains(effectChains);
6046 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 continue;
6048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049 for (size_t i = 0; i < effectChains.size(); i ++) {
6050 effectChains[i]->process_l();
6051 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006054 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006056 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 // no resampling
6058 while (framesOut) {
6059 size_t framesIn = mFrameCount - mRsmpInIndex;
6060 if (framesIn) {
6061 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6062 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6063 if (framesIn > framesOut)
6064 framesIn = framesOut;
6065 mRsmpInIndex += framesIn;
6066 framesOut -= framesIn;
6067 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006068 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 memcpy(dst, src, framesIn * mFrameSize);
6070 } else {
6071 int16_t *src16 = (int16_t *)src;
6072 int16_t *dst16 = (int16_t *)dst;
6073 if (mChannelCount == 1) {
6074 while (framesIn--) {
6075 *dst16++ = *src16;
6076 *dst16++ = *src16++;
6077 }
6078 } else {
6079 while (framesIn--) {
6080 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6081 src16 += 2;
6082 }
6083 }
6084 }
6085 }
6086 if (framesOut && mFrameCount == mRsmpInIndex) {
6087 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006088 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006089 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090 framesOut = 0;
6091 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006092 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 mRsmpInIndex = 0;
6094 }
6095 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006096 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6098 // Force input into standby so that it tries to
6099 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006100 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 }
6103 mRsmpInIndex = mFrameCount;
6104 framesOut = 0;
6105 buffer.frameCount = 0;
6106 }
6107 }
6108 }
6109 } else {
6110 // resampling
6111
6112 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6113 // alter output frame count as if we were expecting stereo samples
6114 if (mChannelCount == 1 && mReqChannelCount == 1) {
6115 framesOut >>= 1;
6116 }
6117 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6118 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6119 // are 32 bit aligned which should be always true.
6120 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006121 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 // the resampler always outputs stereo samples: do post stereo to mono conversion
6123 int16_t *src = (int16_t *)mRsmpOutBuffer;
6124 int16_t *dst = buffer.i16;
6125 while (framesOut--) {
6126 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6127 src += 2;
6128 }
6129 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006130 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 }
6132
6133 }
Eric Laurenta011e352012-03-29 15:51:43 -07006134 if (mFramestoDrop == 0) {
6135 mActiveTrack->releaseBuffer(&buffer);
6136 } else {
6137 if (mFramestoDrop > 0) {
6138 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006139 if (mFramestoDrop <= 0) {
6140 clearSyncStartEvent();
6141 }
6142 } else {
6143 mFramestoDrop += buffer.frameCount;
6144 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6145 mSyncStartEvent->isCancelled()) {
6146 ALOGW("Synced record %s, session %d, trigger session %d",
6147 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6148 mActiveTrack->sessionId(),
6149 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6150 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006151 }
6152 }
6153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 mActiveTrack->overflow();
6155 }
6156 // client isn't retrieving buffers fast enough
6157 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006158 if (!mActiveTrack->setOverflow()) {
6159 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006160 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006161 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006162 lastWarning = now;
6163 }
6164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165 // Release the processor for a while before asking for a new buffer.
6166 // This will give the application more chance to read from the buffer and
6167 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006168 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
6170 }
Eric Laurentec437d82011-07-26 20:54:46 -07006171 // enable changes in effect chain
6172 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006173 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 }
6175
6176 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006177 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 }
6179 mActiveTrack.clear();
6180
6181 mStartStopCond.broadcast();
6182
Eric Laurentfeb0db62011-07-22 09:04:31 -07006183 releaseWakeLock();
6184
Steve Block3856b092011-10-20 11:56:00 +01006185 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 return false;
6187}
6188
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006189
6190sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6191 const sp<AudioFlinger::Client>& client,
6192 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006193 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006194 int channelMask,
6195 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006196 int sessionId,
6197 status_t *status)
6198{
6199 sp<RecordTrack> track;
6200 status_t lStatus;
6201
6202 lStatus = initCheck();
6203 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006204 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006205 goto Exit;
6206 }
6207
6208 { // scope for mLock
6209 Mutex::Autolock _l(mLock);
6210
6211 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006212 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006213
Glenn Kasten7378ca52012-01-20 13:44:40 -08006214 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006215 lStatus = NO_MEMORY;
6216 goto Exit;
6217 }
6218
6219 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006220 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6221 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006222 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006223 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6224 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006225 }
6226 lStatus = NO_ERROR;
6227
6228Exit:
6229 if (status) {
6230 *status = lStatus;
6231 }
6232 return track;
6233}
6234
Eric Laurenta011e352012-03-29 15:51:43 -07006235status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006236 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006237 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238{
Glenn Kasten58912562012-04-03 10:45:00 -07006239 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006240 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006242
6243 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006244 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006245 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6246 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6247 triggerSession,
6248 recordTrack->sessionId(),
6249 syncStartEventCallback,
6250 this);
Eric Laurent29864602012-05-08 18:57:51 -07006251 // Sync event can be cancelled by the trigger session if the track is not in a
6252 // compatible state in which case we start record immediately
6253 if (mSyncStartEvent->isCancelled()) {
6254 clearSyncStartEvent();
6255 } else {
6256 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6257 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6258 }
Eric Laurenta011e352012-03-29 15:51:43 -07006259 }
6260
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006262 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 if (mActiveTrack != 0) {
6264 if (recordTrack != mActiveTrack.get()) {
6265 status = -EBUSY;
6266 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6267 mActiveTrack->mState = TrackBase::ACTIVE;
6268 }
6269 return status;
6270 }
6271
6272 recordTrack->mState = TrackBase::IDLE;
6273 mActiveTrack = recordTrack;
6274 mLock.unlock();
6275 status_t status = AudioSystem::startInput(mId);
6276 mLock.lock();
6277 if (status != NO_ERROR) {
6278 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006279 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 return status;
6281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 mRsmpInIndex = mFrameCount;
6283 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006284 if (mResampler != NULL) {
6285 mResampler->reset();
6286 }
6287 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006289 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 mWaitWorkCV.signal();
6291 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006292 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 mActiveTrack.clear();
6294 status = INVALID_OPERATION;
6295 goto startError;
6296 }
6297 mStartStopCond.wait(mLock);
6298 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006299 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 status = BAD_VALUE;
6301 goto startError;
6302 }
Steve Block3856b092011-10-20 11:56:00 +01006303 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 return status;
6305 }
6306startError:
6307 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006308 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 return status;
6310}
6311
Eric Laurenta011e352012-03-29 15:51:43 -07006312void AudioFlinger::RecordThread::clearSyncStartEvent()
6313{
6314 if (mSyncStartEvent != 0) {
6315 mSyncStartEvent->cancel();
6316 }
6317 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006318 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006319}
6320
6321void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6322{
6323 sp<SyncEvent> strongEvent = event.promote();
6324
6325 if (strongEvent != 0) {
6326 RecordThread *me = (RecordThread *)strongEvent->cookie();
6327 me->handleSyncStartEvent(strongEvent);
6328 }
6329}
6330
6331void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6332{
Eric Laurent29864602012-05-08 18:57:51 -07006333 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006334 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6335 // from audio HAL
6336 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006337 }
6338}
6339
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006341 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006342 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006344 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6346 mActiveTrack->mState = TrackBase::PAUSING;
6347 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006348 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 return;
6350 }
6351 mStartStopCond.wait(mLock);
6352 // if we have been restarted, recordTrack == mActiveTrack.get() here
6353 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6354 mLock.unlock();
6355 AudioSystem::stopInput(mId);
6356 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006357 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 }
6359 }
6360 }
6361}
6362
Eric Laurenta011e352012-03-29 15:51:43 -07006363bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6364{
6365 return false;
6366}
6367
6368status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6369{
6370 if (!isValidSyncEvent(event)) {
6371 return BAD_VALUE;
6372 }
6373
6374 Mutex::Autolock _l(mLock);
6375
6376 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6377 mTrack->setSyncEvent(event);
6378 return NO_ERROR;
6379 }
6380 return NAME_NOT_FOUND;
6381}
6382
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6384{
6385 const size_t SIZE = 256;
6386 char buffer[SIZE];
6387 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388
6389 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6390 result.append(buffer);
6391
6392 if (mActiveTrack != 0) {
6393 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006394 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 mActiveTrack->dump(buffer, SIZE);
6396 result.append(buffer);
6397
6398 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6399 result.append(buffer);
6400 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6401 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006402 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 result.append(buffer);
6404 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6405 result.append(buffer);
6406 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6407 result.append(buffer);
6408
6409
6410 } else {
6411 result.append("No record client\n");
6412 }
6413 write(fd, result.string(), result.size());
6414
6415 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006416 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417
6418 return NO_ERROR;
6419}
6420
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006421// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006422status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423{
6424 size_t framesReq = buffer->frameCount;
6425 size_t framesReady = mFrameCount - mRsmpInIndex;
6426 int channelCount;
6427
6428 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006429 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006431 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6433 // Force input into standby so that it tries to
6434 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006435 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006436 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006438 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 buffer->frameCount = 0;
6440 return NOT_ENOUGH_DATA;
6441 }
6442 mRsmpInIndex = 0;
6443 framesReady = mFrameCount;
6444 }
6445
6446 if (framesReq > framesReady) {
6447 framesReq = framesReady;
6448 }
6449
6450 if (mChannelCount == 1 && mReqChannelCount == 2) {
6451 channelCount = 1;
6452 } else {
6453 channelCount = 2;
6454 }
6455 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6456 buffer->frameCount = framesReq;
6457 return NO_ERROR;
6458}
6459
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006460// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6462{
6463 mRsmpInIndex += buffer->frameCount;
6464 buffer->frameCount = 0;
6465}
6466
6467bool AudioFlinger::RecordThread::checkForNewParameters_l()
6468{
6469 bool reconfig = false;
6470
6471 while (!mNewParameters.isEmpty()) {
6472 status_t status = NO_ERROR;
6473 String8 keyValuePair = mNewParameters[0];
6474 AudioParameter param = AudioParameter(keyValuePair);
6475 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006476 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 int reqSamplingRate = mReqSampleRate;
6478 int reqChannelCount = mReqChannelCount;
6479
6480 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6481 reqSamplingRate = value;
6482 reconfig = true;
6483 }
6484 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006485 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 reconfig = true;
6487 }
6488 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006489 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 reconfig = true;
6491 }
6492 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6493 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006494 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495 // if frame count is changed after track creation
6496 if (mActiveTrack != 0) {
6497 status = INVALID_OPERATION;
6498 } else {
6499 reconfig = true;
6500 }
6501 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006502 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6503 // forward device change to effects that have requested to be
6504 // aware of attached audio device.
6505 for (size_t i = 0; i < mEffectChains.size(); i++) {
6506 mEffectChains[i]->setDevice_l(value);
6507 }
6508 // store input device and output device but do not forward output device to audio HAL.
6509 // Note that status is ignored by the caller for output device
6510 // (see AudioFlinger::setParameters()
6511 if (value & AUDIO_DEVICE_OUT_ALL) {
6512 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6513 status = BAD_VALUE;
6514 } else {
6515 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006516 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6517 if (mTrack != NULL) {
6518 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006519 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006520 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6521 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6522 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006523 }
6524 mDevice |= (uint32_t)value;
6525 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006527 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006529 mInput->stream->common.standby(&mInput->stream->common);
6530 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6531 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 }
6533 if (reconfig) {
6534 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006535 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006536 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006537 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006538 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6539 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 status = NO_ERROR;
6541 }
6542 if (status == NO_ERROR) {
6543 readInputParameters();
6544 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6545 }
6546 }
6547 }
6548
6549 mNewParameters.removeAt(0);
6550
6551 mParamStatus = status;
6552 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006553 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6554 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006555 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556 }
6557 return reconfig;
6558}
6559
6560String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6561{
Dima Zavinfce7a472011-04-19 22:30:36 -07006562 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006563 String8 out_s8 = String8();
6564
6565 Mutex::Autolock _l(mLock);
6566 if (initCheck() != NO_ERROR) {
6567 return out_s8;
6568 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006569
Dima Zavin799a70e2011-04-18 16:57:27 -07006570 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006571 out_s8 = String8(s);
6572 free(s);
6573 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006574}
6575
6576void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6577 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006578 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579
6580 switch (event) {
6581 case AudioSystem::INPUT_OPENED:
6582 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006583 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 desc.samplingRate = mSampleRate;
6585 desc.format = mFormat;
6586 desc.frameCount = mFrameCount;
6587 desc.latency = 0;
6588 param2 = &desc;
6589 break;
6590
6591 case AudioSystem::INPUT_CLOSED:
6592 default:
6593 break;
6594 }
6595 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6596}
6597
6598void AudioFlinger::RecordThread::readInputParameters()
6599{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006600 delete mRsmpInBuffer;
6601 // mRsmpInBuffer is always assigned a new[] below
6602 delete mRsmpOutBuffer;
6603 mRsmpOutBuffer = NULL;
6604 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006605 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606
Dima Zavin799a70e2011-04-18 16:57:27 -07006607 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006608 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6609 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006610 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006611 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006612 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006614 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6616
Glenn Kasten53d76db2012-03-08 12:32:47 -08006617 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 {
6619 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006620 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6621 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622 if (mChannelCount == 1 && mReqChannelCount == 2) {
6623 channelCount = 1;
6624 } else {
6625 channelCount = 2;
6626 }
6627 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6628 mResampler->setSampleRate(mSampleRate);
6629 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6630 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6631
6632 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6633 if (mChannelCount == 1 && mReqChannelCount == 1) {
6634 mFrameCount >>= 1;
6635 }
6636
6637 }
6638 mRsmpInIndex = mFrameCount;
6639}
6640
6641unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6642{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006643 Mutex::Autolock _l(mLock);
6644 if (initCheck() != NO_ERROR) {
6645 return 0;
6646 }
6647
Dima Zavin799a70e2011-04-18 16:57:27 -07006648 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649}
6650
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6652{
6653 Mutex::Autolock _l(mLock);
6654 uint32_t result = 0;
6655 if (getEffectChain_l(sessionId) != 0) {
6656 result = EFFECT_SESSION;
6657 }
6658
6659 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6660 result |= TRACK_SESSION;
6661 }
6662
6663 return result;
6664}
6665
Eric Laurent59bd0da2011-08-01 09:52:20 -07006666AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6667{
6668 Mutex::Autolock _l(mLock);
6669 return mTrack;
6670}
6671
Glenn Kastenaed850d2012-01-26 09:46:34 -08006672AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006673{
6674 Mutex::Autolock _l(mLock);
6675 return mInput;
6676}
6677
6678AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6679{
6680 Mutex::Autolock _l(mLock);
6681 AudioStreamIn *input = mInput;
6682 mInput = NULL;
6683 return input;
6684}
6685
6686// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006687audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006688{
6689 if (mInput == NULL) {
6690 return NULL;
6691 }
6692 return &mInput->stream->common;
6693}
6694
6695
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696// ----------------------------------------------------------------------------
6697
Eric Laurenta4c5a552012-03-29 10:12:40 -07006698audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6699{
6700 if (!settingsAllowed()) {
6701 return 0;
6702 }
6703 Mutex::Autolock _l(mLock);
6704 return loadHwModule_l(name);
6705}
6706
6707// loadHwModule_l() must be called with AudioFlinger::mLock held
6708audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6709{
6710 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6711 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6712 ALOGW("loadHwModule() module %s already loaded", name);
6713 return mAudioHwDevs.keyAt(i);
6714 }
6715 }
6716
Eric Laurenta4c5a552012-03-29 10:12:40 -07006717 audio_hw_device_t *dev;
6718
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006719 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006720 if (rc) {
6721 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6722 return 0;
6723 }
6724
6725 mHardwareStatus = AUDIO_HW_INIT;
6726 rc = dev->init_check(dev);
6727 mHardwareStatus = AUDIO_HW_IDLE;
6728 if (rc) {
6729 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6730 return 0;
6731 }
6732
6733 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6734 (NULL != dev->set_master_volume)) {
6735 AutoMutex lock(mHardwareLock);
6736 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6737 dev->set_master_volume(dev, mMasterVolume);
6738 mHardwareStatus = AUDIO_HW_IDLE;
6739 }
6740
6741 audio_module_handle_t handle = nextUniqueId();
6742 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6743
6744 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006745 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006746
6747 return handle;
6748
6749}
6750
6751audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6752 audio_devices_t *pDevices,
6753 uint32_t *pSamplingRate,
6754 audio_format_t *pFormat,
6755 audio_channel_mask_t *pChannelMask,
6756 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006757 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758{
6759 status_t status;
6760 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006761 struct audio_config config = {
6762 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6763 channel_mask: pChannelMask ? *pChannelMask : 0,
6764 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6765 };
6766 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006767 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768
Eric Laurenta4c5a552012-03-29 10:12:40 -07006769 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6770 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006771 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006772 config.sample_rate,
6773 config.format,
6774 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006775 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776
6777 if (pDevices == NULL || *pDevices == 0) {
6778 return 0;
6779 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006780
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 Mutex::Autolock _l(mLock);
6782
Eric Laurenta4c5a552012-03-29 10:12:40 -07006783 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006784 if (outHwDev == NULL)
6785 return 0;
6786
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006787 audio_io_handle_t id = nextUniqueId();
6788
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006789 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006790
6791 status = outHwDev->open_output_stream(outHwDev,
6792 id,
6793 *pDevices,
6794 (audio_output_flags_t)flags,
6795 &config,
6796 &outStream);
6797
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006798 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006799 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006800 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006801 config.sample_rate,
6802 config.format,
6803 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 status);
6805
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006806 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006807 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006808
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006809 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006810 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6811 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006813 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 } else {
6815 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006816 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 }
6818 mPlaybackThreads.add(id, thread);
6819
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006820 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6821 if (pFormat != NULL) *pFormat = config.format;
6822 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006823 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006824
6825 // notify client processes of the new output creation
6826 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006827
6828 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006829 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006830 ALOGI("Using module %d has the primary audio interface", module);
6831 mPrimaryHardwareDev = outHwDev;
6832
6833 AutoMutex lock(mHardwareLock);
6834 mHardwareStatus = AUDIO_HW_SET_MODE;
6835 outHwDev->set_mode(outHwDev, mMode);
6836
6837 // Determine the level of master volume support the primary audio HAL has,
6838 // and set the initial master volume at the same time.
6839 float initialVolume = 1.0;
6840 mMasterVolumeSupportLvl = MVS_NONE;
6841
6842 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6843 if ((NULL != outHwDev->get_master_volume) &&
6844 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6845 mMasterVolumeSupportLvl = MVS_FULL;
6846 } else {
6847 mMasterVolumeSupportLvl = MVS_SETONLY;
6848 initialVolume = 1.0;
6849 }
6850
6851 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6852 if ((NULL == outHwDev->set_master_volume) ||
6853 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6854 mMasterVolumeSupportLvl = MVS_NONE;
6855 }
6856 // now that we have a primary device, initialize master volume on other devices
6857 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6858 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6859
6860 if ((dev != mPrimaryHardwareDev) &&
6861 (NULL != dev->set_master_volume)) {
6862 dev->set_master_volume(dev, initialVolume);
6863 }
6864 }
6865 mHardwareStatus = AUDIO_HW_IDLE;
6866 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6867 ? initialVolume
6868 : 1.0;
6869 mMasterVolume = initialVolume;
6870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 return id;
6872 }
6873
6874 return 0;
6875}
6876
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006877audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6878 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879{
6880 Mutex::Autolock _l(mLock);
6881 MixerThread *thread1 = checkMixerThread_l(output1);
6882 MixerThread *thread2 = checkMixerThread_l(output2);
6883
6884 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006885 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 return 0;
6887 }
6888
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006889 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6891 thread->addOutputTrack(thread2);
6892 mPlaybackThreads.add(id, thread);
6893 // notify client processes of the new output creation
6894 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6895 return id;
6896}
6897
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006898status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899{
6900 // keep strong reference on the playback thread so that
6901 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006902 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903 {
6904 Mutex::Autolock _l(mLock);
6905 thread = checkPlaybackThread_l(output);
6906 if (thread == NULL) {
6907 return BAD_VALUE;
6908 }
6909
Steve Block3856b092011-10-20 11:56:00 +01006910 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006912 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006914 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6916 dupThread->removeOutputTrack((MixerThread *)thread.get());
6917 }
6918 }
6919 }
Glenn Kastena1117922012-01-26 10:53:32 -08006920 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 mPlaybackThreads.removeItem(output);
6922 }
6923 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006924 // The thread entity (active unit of execution) is no longer running here,
6925 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006927 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006928 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006929 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006930 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006931 out->hwDev->close_output_stream(out->hwDev, out->stream);
6932 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 }
6934 return NO_ERROR;
6935}
6936
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006937status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938{
6939 Mutex::Autolock _l(mLock);
6940 PlaybackThread *thread = checkPlaybackThread_l(output);
6941
6942 if (thread == NULL) {
6943 return BAD_VALUE;
6944 }
6945
Steve Block3856b092011-10-20 11:56:00 +01006946 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947 thread->suspend();
6948
6949 return NO_ERROR;
6950}
6951
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006952status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953{
6954 Mutex::Autolock _l(mLock);
6955 PlaybackThread *thread = checkPlaybackThread_l(output);
6956
6957 if (thread == NULL) {
6958 return BAD_VALUE;
6959 }
6960
Steve Block3856b092011-10-20 11:56:00 +01006961 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962
6963 thread->restore();
6964
6965 return NO_ERROR;
6966}
6967
Eric Laurenta4c5a552012-03-29 10:12:40 -07006968audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6969 audio_devices_t *pDevices,
6970 uint32_t *pSamplingRate,
6971 audio_format_t *pFormat,
6972 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973{
6974 status_t status;
6975 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006976 struct audio_config config = {
6977 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6978 channel_mask: pChannelMask ? *pChannelMask : 0,
6979 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6980 };
6981 uint32_t reqSamplingRate = config.sample_rate;
6982 audio_format_t reqFormat = config.format;
6983 audio_channel_mask_t reqChannels = config.channel_mask;
6984 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006985 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986
6987 if (pDevices == NULL || *pDevices == 0) {
6988 return 0;
6989 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006990
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 Mutex::Autolock _l(mLock);
6992
Eric Laurenta4c5a552012-03-29 10:12:40 -07006993 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006994 if (inHwDev == NULL)
6995 return 0;
6996
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006997 audio_io_handle_t id = nextUniqueId();
6998
6999 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007000 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007001 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007002 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007003 config.sample_rate,
7004 config.format,
7005 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 status);
7007
7008 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7009 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7010 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007011 if (status == BAD_VALUE &&
7012 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7013 (config.sample_rate <= 2 * reqSamplingRate) &&
7014 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01007015 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007016 inStream = NULL;
7017 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 }
7019
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007020 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007021 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7022
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007023 // Start record thread
7024 // RecorThread require both input and output device indication to forward to audio
7025 // pre processing modules
7026 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7027 thread = new RecordThread(this,
7028 input,
7029 reqSamplingRate,
7030 reqChannels,
7031 id,
7032 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007034 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007035 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007036 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007037 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038
Dima Zavin799a70e2011-04-18 16:57:27 -07007039 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040
7041 // notify client processes of the new input creation
7042 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7043 return id;
7044 }
7045
7046 return 0;
7047}
7048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007049status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050{
7051 // keep strong reference on the record thread so that
7052 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007053 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 {
7055 Mutex::Autolock _l(mLock);
7056 thread = checkRecordThread_l(input);
7057 if (thread == NULL) {
7058 return BAD_VALUE;
7059 }
7060
Steve Block3856b092011-10-20 11:56:00 +01007061 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007062 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063 mRecordThreads.removeItem(input);
7064 }
7065 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007066 // The thread entity (active unit of execution) is no longer running here,
7067 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007069 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007070 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007071 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007072 in->hwDev->close_input_stream(in->hwDev, in->stream);
7073 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074
7075 return NO_ERROR;
7076}
7077
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007078status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079{
7080 Mutex::Autolock _l(mLock);
7081 MixerThread *dstThread = checkMixerThread_l(output);
7082 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007083 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 return BAD_VALUE;
7085 }
7086
Steve Block3856b092011-10-20 11:56:00 +01007087 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7089
7090 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7091 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08007092 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 MixerThread *srcThread = (MixerThread *)thread;
7094 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 }
Eric Laurentde070132010-07-13 04:45:46 -07007096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007097
7098 return NO_ERROR;
7099}
7100
7101
7102int AudioFlinger::newAudioSessionId()
7103{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007104 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105}
7106
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007107void AudioFlinger::acquireAudioSessionId(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("acquiring %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.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007115 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7116 ref->mCnt++;
7117 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007118 return;
7119 }
7120 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007121 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7122 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007123}
7124
7125void AudioFlinger::releaseAudioSessionId(int audioSession)
7126{
7127 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007128 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007129 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007130 size_t num = mAudioSessionRefs.size();
7131 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007132 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007133 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7134 ref->mCnt--;
7135 ALOGV(" decremented refcount to %d", ref->mCnt);
7136 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007137 mAudioSessionRefs.removeAt(i);
7138 delete ref;
7139 purgeStaleEffects_l();
7140 }
7141 return;
7142 }
7143 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007144 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007145}
7146
7147void AudioFlinger::purgeStaleEffects_l() {
7148
Steve Block3856b092011-10-20 11:56:00 +01007149 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007150
7151 Vector< sp<EffectChain> > chains;
7152
7153 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7154 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7155 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7156 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007157 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7158 chains.push(ec);
7159 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007160 }
7161 }
7162 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7163 sp<RecordThread> t = mRecordThreads.valueAt(i);
7164 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7165 sp<EffectChain> ec = t->mEffectChains[j];
7166 chains.push(ec);
7167 }
7168 }
7169
7170 for (size_t i = 0; i < chains.size(); i++) {
7171 sp<EffectChain> ec = chains[i];
7172 int sessionid = ec->sessionId();
7173 sp<ThreadBase> t = ec->mThread.promote();
7174 if (t == 0) {
7175 continue;
7176 }
7177 size_t numsessionrefs = mAudioSessionRefs.size();
7178 bool found = false;
7179 for (size_t k = 0; k < numsessionrefs; k++) {
7180 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007181 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007182 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007183 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007184 found = true;
7185 break;
7186 }
7187 }
7188 if (!found) {
7189 // remove all effects from the chain
7190 while (ec->mEffects.size()) {
7191 sp<EffectModule> effect = ec->mEffects[0];
7192 effect->unPin();
7193 Mutex::Autolock _l (t->mLock);
7194 t->removeEffect_l(effect);
7195 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7196 sp<EffectHandle> handle = effect->mHandles[j].promote();
7197 if (handle != 0) {
7198 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007199 if (handle->mHasControl && handle->mEnabled) {
7200 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7201 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007202 }
7203 }
7204 AudioSystem::unregisterEffect(effect->id());
7205 }
7206 }
7207 }
7208 return;
7209}
7210
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007212AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213{
Glenn Kastena1117922012-01-26 10:53:32 -08007214 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215}
7216
7217// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007218AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007219{
7220 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007221 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222}
7223
7224// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007225AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226{
Glenn Kastena1117922012-01-26 10:53:32 -08007227 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228}
7229
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007230uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007232 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007233}
7234
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007235AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007236{
7237 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7238 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007239 AudioStreamOut *output = thread->getOutput();
7240 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007241 return thread;
7242 }
7243 }
7244 return NULL;
7245}
7246
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007247uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007248{
7249 PlaybackThread *thread = primaryPlaybackThread_l();
7250
7251 if (thread == NULL) {
7252 return 0;
7253 }
7254
7255 return thread->device();
7256}
7257
Eric Laurenta011e352012-03-29 15:51:43 -07007258sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7259 int triggerSession,
7260 int listenerSession,
7261 sync_event_callback_t callBack,
7262 void *cookie)
7263{
7264 Mutex::Autolock _l(mLock);
7265
7266 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7267 status_t playStatus = NAME_NOT_FOUND;
7268 status_t recStatus = NAME_NOT_FOUND;
7269 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7270 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7271 if (playStatus == NO_ERROR) {
7272 return event;
7273 }
7274 }
7275 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7276 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7277 if (recStatus == NO_ERROR) {
7278 return event;
7279 }
7280 }
7281 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7282 mPendingSyncEvents.add(event);
7283 } else {
7284 ALOGV("createSyncEvent() invalid event %d", event->type());
7285 event.clear();
7286 }
7287 return event;
7288}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007289
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290// ----------------------------------------------------------------------------
7291// Effect management
7292// ----------------------------------------------------------------------------
7293
7294
Glenn Kastenf587ba52012-01-26 16:25:10 -08007295status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296{
7297 Mutex::Autolock _l(mLock);
7298 return EffectQueryNumberEffects(numEffects);
7299}
7300
Glenn Kastenf587ba52012-01-26 16:25:10 -08007301status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302{
7303 Mutex::Autolock _l(mLock);
7304 return EffectQueryEffect(index, descriptor);
7305}
7306
Glenn Kasten5e92a782012-01-30 07:40:52 -08007307status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007308 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309{
7310 Mutex::Autolock _l(mLock);
7311 return EffectGetDescriptor(pUuid, descriptor);
7312}
7313
7314
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7316 effect_descriptor_t *pDesc,
7317 const sp<IEffectClient>& effectClient,
7318 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007319 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 int sessionId,
7321 status_t *status,
7322 int *id,
7323 int *enabled)
7324{
7325 status_t lStatus = NO_ERROR;
7326 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007329 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007330 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331
7332 if (pDesc == NULL) {
7333 lStatus = BAD_VALUE;
7334 goto Exit;
7335 }
7336
Eric Laurent84e9a102010-09-23 16:10:16 -07007337 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007338 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007339 lStatus = PERMISSION_DENIED;
7340 goto Exit;
7341 }
7342
Dima Zavinfce7a472011-04-19 22:30:36 -07007343 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007344 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007345 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007346 lStatus = PERMISSION_DENIED;
7347 goto Exit;
7348 }
7349
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007350 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007351 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007352 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007353 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007354 lStatus = BAD_VALUE;
7355 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007356 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007357 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007358 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007359 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007360 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007361 }
7362 }
7363
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 {
7365 Mutex::Autolock _l(mLock);
7366
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367
7368 if (!EffectIsNullUuid(&pDesc->uuid)) {
7369 // if uuid is specified, request effect descriptor
7370 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7371 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007372 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 goto Exit;
7374 }
7375 } else {
7376 // if uuid is not specified, look for an available implementation
7377 // of the required type in effect factory
7378 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007379 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 lStatus = BAD_VALUE;
7381 goto Exit;
7382 }
7383 uint32_t numEffects = 0;
7384 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007385 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 bool found = false;
7387
7388 lStatus = EffectQueryNumberEffects(&numEffects);
7389 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007390 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391 goto Exit;
7392 }
7393 for (uint32_t i = 0; i < numEffects; i++) {
7394 lStatus = EffectQueryEffect(i, &desc);
7395 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007396 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 continue;
7398 }
7399 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7400 // If matching type found save effect descriptor. If the session is
7401 // 0 and the effect is not auxiliary, continue enumeration in case
7402 // an auxiliary version of this effect type is available
7403 found = true;
7404 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007405 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7407 break;
7408 }
7409 }
7410 }
7411 if (!found) {
7412 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007413 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 goto Exit;
7415 }
7416 // For same effect type, chose auxiliary version over insert version if
7417 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7420 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7421 }
7422 }
7423
7424 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007425 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7427 lStatus = INVALID_OPERATION;
7428 goto Exit;
7429 }
7430
Eric Laurent59255e42011-07-27 19:49:51 -07007431 // check recording permission for visualizer
7432 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7433 !recordingAllowed()) {
7434 lStatus = PERMISSION_DENIED;
7435 goto Exit;
7436 }
7437
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 // return effect descriptor
7439 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7440
7441 // If output is not specified try to find a matching audio session ID in one of the
7442 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007443 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7444 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007445 // Note: io is never 0 when creating an effect on an input
7446 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007447 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007448 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7449 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007450 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007451 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007454 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007455 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7456 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7457 io = mRecordThreads.keyAt(i);
7458 break;
7459 }
7460 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007461 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007462 // If no output thread contains the requested session ID, default to
7463 // first output. The effect chain will be moved to the correct output
7464 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007465 if (io == 0 && mPlaybackThreads.size()) {
7466 io = mPlaybackThreads.keyAt(0);
7467 }
Steve Block3856b092011-10-20 11:56:00 +01007468 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007469 }
7470 ThreadBase *thread = checkRecordThread_l(io);
7471 if (thread == NULL) {
7472 thread = checkPlaybackThread_l(io);
7473 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007474 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007475 lStatus = BAD_VALUE;
7476 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007479
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007480 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007482 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007483 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7484 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 if (handle != 0 && id != NULL) {
7486 *id = handle->id();
7487 }
7488 }
7489
7490Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007491 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 *status = lStatus;
7493 }
7494 return handle;
7495}
7496
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007497status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7498 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007499{
Steve Block3856b092011-10-20 11:56:00 +01007500 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007501 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007502 Mutex::Autolock _l(mLock);
7503 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007504 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007505 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007506 }
Eric Laurentde070132010-07-13 04:45:46 -07007507 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7508 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007509 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007510 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 }
Eric Laurentde070132010-07-13 04:45:46 -07007512 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7513 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007514 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007515 return BAD_VALUE;
7516 }
7517
7518 Mutex::Autolock _dl(dstThread->mLock);
7519 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007520 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007521
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522 return NO_ERROR;
7523}
7524
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007525// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007526status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007527 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007528 AudioFlinger::PlaybackThread *dstThread,
7529 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007530{
Steve Block3856b092011-10-20 11:56:00 +01007531 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007532 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007533
Eric Laurent59255e42011-07-27 19:49:51 -07007534 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007535 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007536 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007537 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007538 return INVALID_OPERATION;
7539 }
7540
Eric Laurent39e94f82010-07-28 01:32:47 -07007541 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007542 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007543 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007544 // removed.
7545 srcThread->removeEffectChain_l(chain);
7546
7547 // transfer all effects one by one so that new effect chain is created on new thread with
7548 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007549 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007550 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007551 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007552 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7553 while (effect != 0) {
7554 srcThread->removeEffect_l(effect);
7555 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007556 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7557 if (effect->state() == EffectModule::ACTIVE ||
7558 effect->state() == EffectModule::STOPPING) {
7559 effect->start();
7560 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007561 // if the move request is not received from audio policy manager, the effect must be
7562 // re-registered with the new strategy and output
7563 if (dstChain == 0) {
7564 dstChain = effect->chain().promote();
7565 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007567 srcThread->addEffect_l(effect);
7568 return NO_INIT;
7569 }
7570 strategy = dstChain->strategy();
7571 }
7572 if (reRegister) {
7573 AudioSystem::unregisterEffect(effect->id());
7574 AudioSystem::registerEffect(&effect->desc(),
7575 dstOutput,
7576 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007577 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007578 effect->id());
7579 }
Eric Laurentde070132010-07-13 04:45:46 -07007580 effect = chain->getEffectFromId_l(0);
7581 }
7582
7583 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584}
7585
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007586
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589 const sp<AudioFlinger::Client>& client,
7590 const sp<IEffectClient>& effectClient,
7591 int32_t priority,
7592 int sessionId,
7593 effect_descriptor_t *desc,
7594 int *enabled,
7595 status_t *status
7596 )
7597{
7598 sp<EffectModule> effect;
7599 sp<EffectHandle> handle;
7600 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007602 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603 bool effectCreated = false;
7604 bool effectRegistered = false;
7605
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007606 lStatus = initCheck();
7607 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007608 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 goto Exit;
7610 }
7611
7612 // Do not allow effects with session ID 0 on direct output or duplicating threads
7613 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007614 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007615 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007616 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617 lStatus = BAD_VALUE;
7618 goto Exit;
7619 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007620 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007621 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007622 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007623 desc->name, desc->flags, mType);
7624 lStatus = BAD_VALUE;
7625 goto Exit;
7626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627
Steve Block3856b092011-10-20 11:56:00 +01007628 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629
7630 { // scope for mLock
7631 Mutex::Autolock _l(mLock);
7632
7633 // check for existing effect chain with the requested audio session
7634 chain = getEffectChain_l(sessionId);
7635 if (chain == 0) {
7636 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007637 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 chain = new EffectChain(this, sessionId);
7639 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007640 chain->setStrategy(getStrategyForSession_l(sessionId));
7641 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007642 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007643 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644 }
7645
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007646 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647
7648 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007649 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007650 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007651 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652 if (lStatus != NO_ERROR) {
7653 goto Exit;
7654 }
7655 effectRegistered = true;
7656 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007657 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 lStatus = effect->status();
7659 if (lStatus != NO_ERROR) {
7660 goto Exit;
7661 }
Eric Laurentcab11242010-07-15 12:50:15 -07007662 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 if (lStatus != NO_ERROR) {
7664 goto Exit;
7665 }
7666 effectCreated = true;
7667
7668 effect->setDevice(mDevice);
7669 effect->setMode(mAudioFlinger->getMode());
7670 }
7671 // create effect handle and connect it to effect module
7672 handle = new EffectHandle(effect, client, effectClient, priority);
7673 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007674 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 *enabled = (int)effect->isEnabled();
7676 }
7677 }
7678
7679Exit:
7680 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007681 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007683 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007684 }
7685 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007686 AudioSystem::unregisterEffect(effect->id());
7687 }
7688 if (chainCreated) {
7689 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690 }
7691 handle.clear();
7692 }
7693
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007694 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007695 *status = lStatus;
7696 }
7697 return handle;
7698}
7699
Eric Laurent717e1282012-06-29 16:36:52 -07007700sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7701{
7702 Mutex::Autolock _l(mLock);
7703 return getEffect_l(sessionId, effectId);
7704}
7705
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007706sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7707{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007708 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007709 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007710}
7711
Eric Laurentde070132010-07-13 04:45:46 -07007712// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7713// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007714status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007715{
7716 // check for existing effect chain with the requested audio session
7717 int sessionId = effect->sessionId();
7718 sp<EffectChain> chain = getEffectChain_l(sessionId);
7719 bool chainCreated = false;
7720
7721 if (chain == 0) {
7722 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007723 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007724 chain = new EffectChain(this, sessionId);
7725 addEffectChain_l(chain);
7726 chain->setStrategy(getStrategyForSession_l(sessionId));
7727 chainCreated = true;
7728 }
Steve Block3856b092011-10-20 11:56:00 +01007729 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007730
7731 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007732 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007733 this, effect->desc().name, chain.get());
7734 return BAD_VALUE;
7735 }
7736
7737 status_t status = chain->addEffect_l(effect);
7738 if (status != NO_ERROR) {
7739 if (chainCreated) {
7740 removeEffectChain_l(chain);
7741 }
7742 return status;
7743 }
7744
7745 effect->setDevice(mDevice);
7746 effect->setMode(mAudioFlinger->getMode());
7747 return NO_ERROR;
7748}
7749
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007750void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007751
Steve Block3856b092011-10-20 11:56:00 +01007752 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007754 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7755 detachAuxEffect_l(effect->id());
7756 }
7757
7758 sp<EffectChain> chain = effect->chain().promote();
7759 if (chain != 0) {
7760 // remove effect chain if removing last effect
7761 if (chain->removeEffect_l(effect) == 0) {
7762 removeEffectChain_l(chain);
7763 }
7764 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007765 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007766 }
7767}
7768
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007769void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007770 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007771{
7772 effectChains = mEffectChains;
7773 for (size_t i = 0; i < mEffectChains.size(); i++) {
7774 mEffectChains[i]->lock();
7775 }
7776}
7777
7778void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007779 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007780{
7781 for (size_t i = 0; i < effectChains.size(); i++) {
7782 effectChains[i]->unlock();
7783 }
7784}
7785
7786sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7787{
7788 Mutex::Autolock _l(mLock);
7789 return getEffectChain_l(sessionId);
7790}
7791
7792sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7793{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007794 size_t size = mEffectChains.size();
7795 for (size_t i = 0; i < size; i++) {
7796 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007797 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007798 }
7799 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007800 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007801}
7802
Glenn Kastenf78aee72012-01-04 11:00:47 -08007803void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007804{
7805 Mutex::Autolock _l(mLock);
7806 size_t size = mEffectChains.size();
7807 for (size_t i = 0; i < size; i++) {
7808 mEffectChains[i]->setMode_l(mode);
7809 }
7810}
7811
7812void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007813 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007814 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007815
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007817 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 // delete the effect module if removing last handle on it
7819 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007820 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007821 removeEffect_l(effect);
7822 AudioSystem::unregisterEffect(effect->id());
7823 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824 }
7825}
7826
7827status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7828{
7829 int session = chain->sessionId();
7830 int16_t *buffer = mMixBuffer;
7831 bool ownsBuffer = false;
7832
Steve Block3856b092011-10-20 11:56:00 +01007833 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834 if (session > 0) {
7835 // Only one effect chain can be present in direct output thread and it uses
7836 // the mix buffer as input
7837 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007838 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 buffer = new int16_t[numSamples];
7840 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007841 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842 ownsBuffer = true;
7843 }
7844
7845 // Attach all tracks with same session ID to this chain.
7846 for (size_t i = 0; i < mTracks.size(); ++i) {
7847 sp<Track> track = mTracks[i];
7848 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007849 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007850 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007851 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 }
7853 }
7854
7855 // indicate all active tracks in the chain
7856 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7857 sp<Track> track = mActiveTracks[i].promote();
7858 if (track == 0) continue;
7859 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007860 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007861 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 }
7863 }
7864 }
7865
7866 chain->setInBuffer(buffer, ownsBuffer);
7867 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007868 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007869 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007870 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7871 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007873 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7874 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007875 // Effect chain for other sessions are inserted at beginning of effect
7876 // chains list to be processed before output mix effects. Relative order between other
7877 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 size_t size = mEffectChains.size();
7879 size_t i = 0;
7880 for (i = 0; i < size; i++) {
7881 if (mEffectChains[i]->sessionId() < session) break;
7882 }
7883 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007884 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885
7886 return NO_ERROR;
7887}
7888
7889size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7890{
7891 int session = chain->sessionId();
7892
Steve Block3856b092011-10-20 11:56:00 +01007893 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894
7895 for (size_t i = 0; i < mEffectChains.size(); i++) {
7896 if (chain == mEffectChains[i]) {
7897 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007898 // detach all active tracks from the chain
7899 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7900 sp<Track> track = mActiveTracks[i].promote();
7901 if (track == 0) continue;
7902 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007903 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007904 chain.get(), session);
7905 chain->decActiveTrackCnt();
7906 }
7907 }
7908
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 // detach all tracks with same session ID from this chain
7910 for (size_t i = 0; i < mTracks.size(); ++i) {
7911 sp<Track> track = mTracks[i];
7912 if (session == track->sessionId()) {
7913 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007914 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915 }
7916 }
Eric Laurentde070132010-07-13 04:45:46 -07007917 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 }
7919 }
7920 return mEffectChains.size();
7921}
7922
Eric Laurentde070132010-07-13 04:45:46 -07007923status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7924 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925{
7926 Mutex::Autolock _l(mLock);
7927 return attachAuxEffect_l(track, EffectId);
7928}
7929
Eric Laurentde070132010-07-13 04:45:46 -07007930status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7931 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932{
7933 status_t status = NO_ERROR;
7934
7935 if (EffectId == 0) {
7936 track->setAuxBuffer(0, NULL);
7937 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007938 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7939 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 if (effect != 0) {
7941 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7942 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7943 } else {
7944 status = INVALID_OPERATION;
7945 }
7946 } else {
7947 status = BAD_VALUE;
7948 }
7949 }
7950 return status;
7951}
7952
7953void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7954{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007955 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 sp<Track> track = mTracks[i];
7957 if (track->auxEffectId() == effectId) {
7958 attachAuxEffect_l(track, 0);
7959 }
7960 }
7961}
7962
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007963status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7964{
7965 // only one chain per input thread
7966 if (mEffectChains.size() != 0) {
7967 return INVALID_OPERATION;
7968 }
Steve Block3856b092011-10-20 11:56:00 +01007969 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007970
7971 chain->setInBuffer(NULL);
7972 chain->setOutBuffer(NULL);
7973
Eric Laurent59255e42011-07-27 19:49:51 -07007974 checkSuspendOnAddEffectChain_l(chain);
7975
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007976 mEffectChains.add(chain);
7977
7978 return NO_ERROR;
7979}
7980
7981size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7982{
Steve Block3856b092011-10-20 11:56:00 +01007983 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007984 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007985 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7986 chain.get(), mEffectChains.size(), this);
7987 if (mEffectChains.size() == 1) {
7988 mEffectChains.removeAt(0);
7989 }
7990 return 0;
7991}
7992
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993// ----------------------------------------------------------------------------
7994// EffectModule implementation
7995// ----------------------------------------------------------------------------
7996
7997#undef LOG_TAG
7998#define LOG_TAG "AudioFlinger::EffectModule"
7999
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008000AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001 const wp<AudioFlinger::EffectChain>& chain,
8002 effect_descriptor_t *desc,
8003 int id,
8004 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008005 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008006 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007{
Steve Block3856b092011-10-20 11:56:00 +01008008 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008010 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008011 return;
8012 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013
8014 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
8015
8016 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008017 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018
8019 if (mStatus != NO_ERROR) {
8020 return;
8021 }
8022 lStatus = init();
8023 if (lStatus < 0) {
8024 mStatus = lStatus;
8025 goto Error;
8026 }
8027
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008028 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
8029 mPinned = true;
8030 }
Steve Block3856b092011-10-20 11:56:00 +01008031 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032 return;
8033Error:
8034 EffectRelease(mEffectInterface);
8035 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008036 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037}
8038
8039AudioFlinger::EffectModule::~EffectModule()
8040{
Steve Block3856b092011-10-20 11:56:00 +01008041 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008043 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8044 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8045 sp<ThreadBase> thread = mThread.promote();
8046 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008047 audio_stream_t *stream = thread->stream();
8048 if (stream != NULL) {
8049 stream->remove_audio_effect(stream, mEffectInterface);
8050 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008051 }
8052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 // release effect engine
8054 EffectRelease(mEffectInterface);
8055 }
8056}
8057
Glenn Kasten435dbe62012-01-30 10:15:48 -08008058status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059{
8060 status_t status;
8061
8062 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063 int priority = handle->priority();
8064 size_t size = mHandles.size();
8065 sp<EffectHandle> h;
8066 size_t i;
8067 for (i = 0; i < size; i++) {
8068 h = mHandles[i].promote();
8069 if (h == 0) continue;
8070 if (h->priority() <= priority) break;
8071 }
8072 // if inserted in first place, move effect control from previous owner to this handle
8073 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008074 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008076 enabled = h->enabled();
8077 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 }
Eric Laurent59255e42011-07-27 19:49:51 -07008079 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080 status = NO_ERROR;
8081 } else {
8082 status = ALREADY_EXISTS;
8083 }
Steve Block3856b092011-10-20 11:56:00 +01008084 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085 mHandles.insertAt(handle, i);
8086 return status;
8087}
8088
8089size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8090{
8091 Mutex::Autolock _l(mLock);
8092 size_t size = mHandles.size();
8093 size_t i;
8094 for (i = 0; i < size; i++) {
8095 if (mHandles[i] == handle) break;
8096 }
8097 if (i == size) {
8098 return size;
8099 }
Steve Block3856b092011-10-20 11:56:00 +01008100 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008101
8102 bool enabled = false;
8103 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008104 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008105 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008106 enabled = hdl->enabled();
8107 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 mHandles.removeAt(i);
8109 size = mHandles.size();
8110 // if removed from first place, move effect control from this handle to next in line
8111 if (i == 0 && size != 0) {
8112 sp<EffectHandle> h = mHandles[0].promote();
8113 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008114 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115 }
8116 }
8117
Eric Laurentec437d82011-07-26 20:54:46 -07008118 // Prevent calls to process() and other functions on effect interface from now on.
8119 // The effect engine will be released by the destructor when the last strong reference on
8120 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008121 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008122 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008123 }
8124
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125 return size;
8126}
8127
Eric Laurent59255e42011-07-27 19:49:51 -07008128sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8129{
8130 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008131 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008132}
8133
Glenn Kasten58123c32012-02-03 10:32:24 -08008134void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008136 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137 // keep a strong reference on this EffectModule to avoid calling the
8138 // destructor before we exit
8139 sp<EffectModule> keep(this);
8140 {
8141 sp<ThreadBase> thread = mThread.promote();
8142 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008143 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144 }
8145 }
8146}
8147
8148void AudioFlinger::EffectModule::updateState() {
8149 Mutex::Autolock _l(mLock);
8150
8151 switch (mState) {
8152 case RESTART:
8153 reset_l();
8154 // FALL THROUGH
8155
8156 case STARTING:
8157 // clear auxiliary effect input buffer for next accumulation
8158 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8159 memset(mConfig.inputCfg.buffer.raw,
8160 0,
8161 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8162 }
8163 start_l();
8164 mState = ACTIVE;
8165 break;
8166 case STOPPING:
8167 stop_l();
8168 mDisableWaitCnt = mMaxDisableWaitCnt;
8169 mState = STOPPED;
8170 break;
8171 case STOPPED:
8172 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8173 // turn off sequence.
8174 if (--mDisableWaitCnt == 0) {
8175 reset_l();
8176 mState = IDLE;
8177 }
8178 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008179 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 break;
8181 }
8182}
8183
8184void AudioFlinger::EffectModule::process()
8185{
8186 Mutex::Autolock _l(mLock);
8187
Eric Laurentec437d82011-07-26 20:54:46 -07008188 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 mConfig.inputCfg.buffer.raw == NULL ||
8190 mConfig.outputCfg.buffer.raw == NULL) {
8191 return;
8192 }
8193
Eric Laurent8f45bd72010-08-31 13:50:07 -07008194 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8196 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008197 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008198 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008199 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 }
8201
8202 // do the actual processing in the effect engine
8203 int ret = (*mEffectInterface)->process(mEffectInterface,
8204 &mConfig.inputCfg.buffer,
8205 &mConfig.outputCfg.buffer);
8206
8207 // force transition to IDLE state when engine is ready
8208 if (mState == STOPPED && ret == -ENODATA) {
8209 mDisableWaitCnt = 1;
8210 }
8211
8212 // clear auxiliary effect input buffer for next accumulation
8213 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008214 memset(mConfig.inputCfg.buffer.raw, 0,
8215 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008216 }
8217 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008218 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8219 // If an insert effect is idle and input buffer is different from output buffer,
8220 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008222 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008223 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8224 int16_t *in = mConfig.inputCfg.buffer.s16;
8225 int16_t *out = mConfig.outputCfg.buffer.s16;
8226 for (size_t i = 0; i < frameCnt; i++) {
8227 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008229 }
8230 }
8231}
8232
8233void AudioFlinger::EffectModule::reset_l()
8234{
8235 if (mEffectInterface == NULL) {
8236 return;
8237 }
8238 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8239}
8240
8241status_t AudioFlinger::EffectModule::configure()
8242{
8243 uint32_t channels;
8244 if (mEffectInterface == NULL) {
8245 return NO_INIT;
8246 }
8247
8248 sp<ThreadBase> thread = mThread.promote();
8249 if (thread == 0) {
8250 return DEAD_OBJECT;
8251 }
8252
8253 // TODO: handle configuration of effects replacing track process
8254 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008255 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008257 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008258 }
8259
8260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008261 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 } else {
8263 mConfig.inputCfg.channels = channels;
8264 }
8265 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008266 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8267 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268 mConfig.inputCfg.samplingRate = thread->sampleRate();
8269 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8270 mConfig.inputCfg.bufferProvider.cookie = NULL;
8271 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8272 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8273 mConfig.outputCfg.bufferProvider.cookie = NULL;
8274 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8275 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8276 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8277 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008278 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008279 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 // - in other sessions:
8281 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8282 // other effect: overwrites output buffer: input buffer == output buffer
8283 // Auxiliary effect:
8284 // accumulates in output buffer: input buffer != output buffer
8285 // Therefore: accumulate <=> input buffer != output buffer
8286 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8287 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8288 } else {
8289 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8290 }
8291 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8292 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8293 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8294 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8295
Steve Block3856b092011-10-20 11:56:00 +01008296 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008297 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8298
Mathias Agopian65ab4712010-07-14 17:59:35 -07008299 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008300 uint32_t size = sizeof(int);
8301 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008302 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008303 sizeof(effect_config_t),
8304 &mConfig,
8305 &size,
8306 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008307 if (status == 0) {
8308 status = cmdStatus;
8309 }
8310
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008311 if (status == 0 &&
8312 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8313 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8314 effect_param_t *p = (effect_param_t *)buf32;
8315
8316 p->psize = sizeof(uint32_t);
8317 p->vsize = sizeof(uint32_t);
8318 size = sizeof(int);
8319 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8320
8321 uint32_t latency = 0;
8322 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8323 if (pbt != NULL) {
8324 latency = pbt->latency_l();
8325 }
8326
8327 *((int32_t *)p->data + 1)= latency;
8328 (*mEffectInterface)->command(mEffectInterface,
8329 EFFECT_CMD_SET_PARAM,
8330 sizeof(effect_param_t) + 8,
8331 &buf32,
8332 &size,
8333 &cmdStatus);
8334 }
8335
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8337 (1000 * mConfig.outputCfg.buffer.frameCount);
8338
8339 return status;
8340}
8341
8342status_t AudioFlinger::EffectModule::init()
8343{
8344 Mutex::Autolock _l(mLock);
8345 if (mEffectInterface == NULL) {
8346 return NO_INIT;
8347 }
8348 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008349 uint32_t size = sizeof(status_t);
8350 status_t status = (*mEffectInterface)->command(mEffectInterface,
8351 EFFECT_CMD_INIT,
8352 0,
8353 NULL,
8354 &size,
8355 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008356 if (status == 0) {
8357 status = cmdStatus;
8358 }
8359 return status;
8360}
8361
Eric Laurentec35a142011-10-05 17:42:25 -07008362status_t AudioFlinger::EffectModule::start()
8363{
8364 Mutex::Autolock _l(mLock);
8365 return start_l();
8366}
8367
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368status_t AudioFlinger::EffectModule::start_l()
8369{
8370 if (mEffectInterface == NULL) {
8371 return NO_INIT;
8372 }
8373 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008374 uint32_t size = sizeof(status_t);
8375 status_t status = (*mEffectInterface)->command(mEffectInterface,
8376 EFFECT_CMD_ENABLE,
8377 0,
8378 NULL,
8379 &size,
8380 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008381 if (status == 0) {
8382 status = cmdStatus;
8383 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008384 if (status == 0 &&
8385 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8386 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8387 sp<ThreadBase> thread = mThread.promote();
8388 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008389 audio_stream_t *stream = thread->stream();
8390 if (stream != NULL) {
8391 stream->add_audio_effect(stream, mEffectInterface);
8392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008393 }
8394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395 return status;
8396}
8397
Eric Laurentec437d82011-07-26 20:54:46 -07008398status_t AudioFlinger::EffectModule::stop()
8399{
8400 Mutex::Autolock _l(mLock);
8401 return stop_l();
8402}
8403
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404status_t AudioFlinger::EffectModule::stop_l()
8405{
8406 if (mEffectInterface == NULL) {
8407 return NO_INIT;
8408 }
8409 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008410 uint32_t size = sizeof(status_t);
8411 status_t status = (*mEffectInterface)->command(mEffectInterface,
8412 EFFECT_CMD_DISABLE,
8413 0,
8414 NULL,
8415 &size,
8416 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008417 if (status == 0) {
8418 status = cmdStatus;
8419 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008420 if (status == 0 &&
8421 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8422 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8423 sp<ThreadBase> thread = mThread.promote();
8424 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008425 audio_stream_t *stream = thread->stream();
8426 if (stream != NULL) {
8427 stream->remove_audio_effect(stream, mEffectInterface);
8428 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008429 }
8430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008431 return status;
8432}
8433
Eric Laurent25f43952010-07-28 05:40:18 -07008434status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8435 uint32_t cmdSize,
8436 void *pCmdData,
8437 uint32_t *replySize,
8438 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439{
8440 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008441// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008442
Eric Laurentec437d82011-07-26 20:54:46 -07008443 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 return NO_INIT;
8445 }
Eric Laurent25f43952010-07-28 05:40:18 -07008446 status_t status = (*mEffectInterface)->command(mEffectInterface,
8447 cmdCode,
8448 cmdSize,
8449 pCmdData,
8450 replySize,
8451 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008453 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454 for (size_t i = 1; i < mHandles.size(); i++) {
8455 sp<EffectHandle> h = mHandles[i].promote();
8456 if (h != 0) {
8457 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8458 }
8459 }
8460 }
8461 return status;
8462}
8463
8464status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8465{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008466
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008468 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008469
8470 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008471 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8472 if (enabled && status != NO_ERROR) {
8473 return status;
8474 }
8475
Mathias Agopian65ab4712010-07-14 17:59:35 -07008476 switch (mState) {
8477 // going from disabled to enabled
8478 case IDLE:
8479 mState = STARTING;
8480 break;
8481 case STOPPED:
8482 mState = RESTART;
8483 break;
8484 case STOPPING:
8485 mState = ACTIVE;
8486 break;
8487
8488 // going from enabled to disabled
8489 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008490 mState = STOPPED;
8491 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492 case STARTING:
8493 mState = IDLE;
8494 break;
8495 case ACTIVE:
8496 mState = STOPPING;
8497 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008498 case DESTROYED:
8499 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500 }
8501 for (size_t i = 1; i < mHandles.size(); i++) {
8502 sp<EffectHandle> h = mHandles[i].promote();
8503 if (h != 0) {
8504 h->setEnabled(enabled);
8505 }
8506 }
8507 }
8508 return NO_ERROR;
8509}
8510
Glenn Kastenc59c0042012-02-02 14:06:11 -08008511bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512{
8513 switch (mState) {
8514 case RESTART:
8515 case STARTING:
8516 case ACTIVE:
8517 return true;
8518 case IDLE:
8519 case STOPPING:
8520 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008521 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 default:
8523 return false;
8524 }
8525}
8526
Glenn Kastenc59c0042012-02-02 14:06:11 -08008527bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008528{
8529 switch (mState) {
8530 case RESTART:
8531 case ACTIVE:
8532 case STOPPING:
8533 case STOPPED:
8534 return true;
8535 case IDLE:
8536 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008537 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008538 default:
8539 return false;
8540 }
8541}
8542
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8544{
8545 Mutex::Autolock _l(mLock);
8546 status_t status = NO_ERROR;
8547
8548 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8549 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008550 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008551 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8552 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008553 status_t cmdStatus;
8554 uint32_t volume[2];
8555 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008556 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557 volume[0] = *left;
8558 volume[1] = *right;
8559 if (controller) {
8560 pVolume = volume;
8561 }
Eric Laurent25f43952010-07-28 05:40:18 -07008562 status = (*mEffectInterface)->command(mEffectInterface,
8563 EFFECT_CMD_SET_VOLUME,
8564 size,
8565 volume,
8566 &size,
8567 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8569 *left = volume[0];
8570 *right = volume[1];
8571 }
8572 }
8573 return status;
8574}
8575
8576status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8577{
8578 Mutex::Autolock _l(mLock);
8579 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008580 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8581 // audio pre processing modules on RecordThread can receive both output and
8582 // input device indication in the same call
8583 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8584 if (dev) {
8585 status_t cmdStatus;
8586 uint32_t size = sizeof(status_t);
8587
8588 status = (*mEffectInterface)->command(mEffectInterface,
8589 EFFECT_CMD_SET_DEVICE,
8590 sizeof(uint32_t),
8591 &dev,
8592 &size,
8593 &cmdStatus);
8594 if (status == NO_ERROR) {
8595 status = cmdStatus;
8596 }
8597 }
8598 dev = device & AUDIO_DEVICE_IN_ALL;
8599 if (dev) {
8600 status_t cmdStatus;
8601 uint32_t size = sizeof(status_t);
8602
8603 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8604 EFFECT_CMD_SET_INPUT_DEVICE,
8605 sizeof(uint32_t),
8606 &dev,
8607 &size,
8608 &cmdStatus);
8609 if (status2 == NO_ERROR) {
8610 status2 = cmdStatus;
8611 }
8612 if (status == NO_ERROR) {
8613 status = status2;
8614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008615 }
8616 }
8617 return status;
8618}
8619
Glenn Kastenf78aee72012-01-04 11:00:47 -08008620status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008621{
8622 Mutex::Autolock _l(mLock);
8623 status_t status = NO_ERROR;
8624 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008626 uint32_t size = sizeof(status_t);
8627 status = (*mEffectInterface)->command(mEffectInterface,
8628 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008629 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008630 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008631 &size,
8632 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008633 if (status == NO_ERROR) {
8634 status = cmdStatus;
8635 }
8636 }
8637 return status;
8638}
8639
Eric Laurent59255e42011-07-27 19:49:51 -07008640void AudioFlinger::EffectModule::setSuspended(bool suspended)
8641{
8642 Mutex::Autolock _l(mLock);
8643 mSuspended = suspended;
8644}
Glenn Kastena3a85482012-01-04 11:01:11 -08008645
8646bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008647{
8648 Mutex::Autolock _l(mLock);
8649 return mSuspended;
8650}
8651
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8653{
8654 const size_t SIZE = 256;
8655 char buffer[SIZE];
8656 String8 result;
8657
8658 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8659 result.append(buffer);
8660
8661 bool locked = tryLock(mLock);
8662 // failed to lock - AudioFlinger is probably deadlocked
8663 if (!locked) {
8664 result.append("\t\tCould not lock Fx mutex:\n");
8665 }
8666
8667 result.append("\t\tSession Status State Engine:\n");
8668 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8669 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8670 result.append(buffer);
8671
8672 result.append("\t\tDescriptor:\n");
8673 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8674 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8675 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8676 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8677 result.append(buffer);
8678 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8679 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8680 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8681 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8682 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008683 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008684 mDescriptor.apiVersion,
8685 mDescriptor.flags);
8686 result.append(buffer);
8687 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8688 mDescriptor.name);
8689 result.append(buffer);
8690 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8691 mDescriptor.implementor);
8692 result.append(buffer);
8693
8694 result.append("\t\t- Input configuration:\n");
8695 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8696 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8697 (uint32_t)mConfig.inputCfg.buffer.raw,
8698 mConfig.inputCfg.buffer.frameCount,
8699 mConfig.inputCfg.samplingRate,
8700 mConfig.inputCfg.channels,
8701 mConfig.inputCfg.format);
8702 result.append(buffer);
8703
8704 result.append("\t\t- Output configuration:\n");
8705 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8706 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8707 (uint32_t)mConfig.outputCfg.buffer.raw,
8708 mConfig.outputCfg.buffer.frameCount,
8709 mConfig.outputCfg.samplingRate,
8710 mConfig.outputCfg.channels,
8711 mConfig.outputCfg.format);
8712 result.append(buffer);
8713
8714 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8715 result.append(buffer);
8716 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8717 for (size_t i = 0; i < mHandles.size(); ++i) {
8718 sp<EffectHandle> handle = mHandles[i].promote();
8719 if (handle != 0) {
8720 handle->dump(buffer, SIZE);
8721 result.append(buffer);
8722 }
8723 }
8724
8725 result.append("\n");
8726
8727 write(fd, result.string(), result.length());
8728
8729 if (locked) {
8730 mLock.unlock();
8731 }
8732
8733 return NO_ERROR;
8734}
8735
8736// ----------------------------------------------------------------------------
8737// EffectHandle implementation
8738// ----------------------------------------------------------------------------
8739
8740#undef LOG_TAG
8741#define LOG_TAG "AudioFlinger::EffectHandle"
8742
8743AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8744 const sp<AudioFlinger::Client>& client,
8745 const sp<IEffectClient>& effectClient,
8746 int32_t priority)
8747 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008748 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008749 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750{
Steve Block3856b092011-10-20 11:56:00 +01008751 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008753 if (client == 0) {
8754 return;
8755 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8757 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8758 if (mCblkMemory != 0) {
8759 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8760
Glenn Kastena0d68332012-01-27 16:47:15 -08008761 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762 new(mCblk) effect_param_cblk_t();
8763 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008764 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008766 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767 return;
8768 }
8769}
8770
8771AudioFlinger::EffectHandle::~EffectHandle()
8772{
Steve Block3856b092011-10-20 11:56:00 +01008773 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008774 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008775 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008776}
8777
8778status_t AudioFlinger::EffectHandle::enable()
8779{
Steve Block3856b092011-10-20 11:56:00 +01008780 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008781 if (!mHasControl) return INVALID_OPERATION;
8782 if (mEffect == 0) return DEAD_OBJECT;
8783
Eric Laurentdb7c0792011-08-10 10:37:50 -07008784 if (mEnabled) {
8785 return NO_ERROR;
8786 }
8787
Eric Laurent59255e42011-07-27 19:49:51 -07008788 mEnabled = true;
8789
8790 sp<ThreadBase> thread = mEffect->thread().promote();
8791 if (thread != 0) {
8792 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8793 }
8794
8795 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8796 if (mEffect->suspended()) {
8797 return NO_ERROR;
8798 }
8799
Eric Laurentdb7c0792011-08-10 10:37:50 -07008800 status_t status = mEffect->setEnabled(true);
8801 if (status != NO_ERROR) {
8802 if (thread != 0) {
8803 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8804 }
8805 mEnabled = false;
8806 }
8807 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808}
8809
8810status_t AudioFlinger::EffectHandle::disable()
8811{
Steve Block3856b092011-10-20 11:56:00 +01008812 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008814 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008815
Eric Laurentdb7c0792011-08-10 10:37:50 -07008816 if (!mEnabled) {
8817 return NO_ERROR;
8818 }
Eric Laurent59255e42011-07-27 19:49:51 -07008819 mEnabled = false;
8820
8821 if (mEffect->suspended()) {
8822 return NO_ERROR;
8823 }
8824
8825 status_t status = mEffect->setEnabled(false);
8826
8827 sp<ThreadBase> thread = mEffect->thread().promote();
8828 if (thread != 0) {
8829 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8830 }
8831
8832 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008833}
8834
8835void AudioFlinger::EffectHandle::disconnect()
8836{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008837 disconnect(true);
8838}
8839
Glenn Kasten58123c32012-02-03 10:32:24 -08008840void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008841{
Glenn Kasten58123c32012-02-03 10:32:24 -08008842 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843 if (mEffect == 0) {
8844 return;
8845 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008846 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008847
Eric Laurenta85a74a2011-10-19 11:44:54 -07008848 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008849 sp<ThreadBase> thread = mEffect->thread().promote();
8850 if (thread != 0) {
8851 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8852 }
Eric Laurent59255e42011-07-27 19:49:51 -07008853 }
8854
Mathias Agopian65ab4712010-07-14 17:59:35 -07008855 // release sp on module => module destructor can be called now
8856 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008858 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008859 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008860 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8861 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008862 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008863 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008864 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8865 mClient.clear();
8866 }
8867}
8868
Eric Laurent25f43952010-07-28 05:40:18 -07008869status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8870 uint32_t cmdSize,
8871 void *pCmdData,
8872 uint32_t *replySize,
8873 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008874{
Steve Block3856b092011-10-20 11:56:00 +01008875// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008876// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877
8878 // only get parameter command is permitted for applications not controlling the effect
8879 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8880 return INVALID_OPERATION;
8881 }
8882 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008883 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008884
8885 // handle commands that are not forwarded transparently to effect engine
8886 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8887 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8888 // no risk to block the whole media server process or mixer threads is we are stuck here
8889 Mutex::Autolock _l(mCblk->lock);
8890 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8891 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8892 mCblk->serverIndex = 0;
8893 mCblk->clientIndex = 0;
8894 return BAD_VALUE;
8895 }
8896 status_t status = NO_ERROR;
8897 while (mCblk->serverIndex < mCblk->clientIndex) {
8898 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008899 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008900 int *p = (int *)(mBuffer + mCblk->serverIndex);
8901 int size = *p++;
8902 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008903 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904 break;
8905 }
8906 effect_param_t *param = (effect_param_t *)p;
8907 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008908 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008909 mCblk->serverIndex += size;
8910 continue;
8911 }
Eric Laurent25f43952010-07-28 05:40:18 -07008912 uint32_t psize = sizeof(effect_param_t) +
8913 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8914 param->vsize;
8915 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8916 psize,
8917 p,
8918 &rsize,
8919 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008920 // stop at first error encountered
8921 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008922 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008923 *(int *)pReplyData = reply;
8924 break;
8925 } else if (reply != NO_ERROR) {
8926 *(int *)pReplyData = reply;
8927 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928 }
8929 mCblk->serverIndex += size;
8930 }
8931 mCblk->serverIndex = 0;
8932 mCblk->clientIndex = 0;
8933 return status;
8934 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008935 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936 return enable();
8937 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008938 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 return disable();
8940 }
8941
8942 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8943}
8944
Eric Laurent59255e42011-07-27 19:49:51 -07008945void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008946{
Steve Block3856b092011-10-20 11:56:00 +01008947 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008948
8949 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008950 mEnabled = enabled;
8951
Mathias Agopian65ab4712010-07-14 17:59:35 -07008952 if (signal && mEffectClient != 0) {
8953 mEffectClient->controlStatusChanged(hasControl);
8954 }
8955}
8956
Eric Laurent25f43952010-07-28 05:40:18 -07008957void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8958 uint32_t cmdSize,
8959 void *pCmdData,
8960 uint32_t replySize,
8961 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962{
8963 if (mEffectClient != 0) {
8964 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8965 }
8966}
8967
8968
8969
8970void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8971{
8972 if (mEffectClient != 0) {
8973 mEffectClient->enableStatusChanged(enabled);
8974 }
8975}
8976
8977status_t AudioFlinger::EffectHandle::onTransact(
8978 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8979{
8980 return BnEffect::onTransact(code, data, reply, flags);
8981}
8982
8983
8984void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8985{
Glenn Kastena0d68332012-01-27 16:47:15 -08008986 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008987
8988 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008989 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008990 mPriority,
8991 mHasControl,
8992 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008993 mCblk ? mCblk->clientIndex : 0,
8994 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995 );
8996
8997 if (locked) {
8998 mCblk->lock.unlock();
8999 }
9000}
9001
9002#undef LOG_TAG
9003#define LOG_TAG "AudioFlinger::EffectChain"
9004
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009005AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009007 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009008 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9009 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009010{
Dima Zavinfce7a472011-04-19 22:30:36 -07009011 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009012 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009013 return;
9014 }
9015 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9016 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017}
9018
9019AudioFlinger::EffectChain::~EffectChain()
9020{
9021 if (mOwnInBuffer) {
9022 delete mInBuffer;
9023 }
9024
9025}
9026
Eric Laurent59255e42011-07-27 19:49:51 -07009027// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009028sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 size_t size = mEffects.size();
9031
9032 for (size_t i = 0; i < size; i++) {
9033 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009034 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035 }
9036 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009037 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038}
9039
Eric Laurent59255e42011-07-27 19:49:51 -07009040// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009041sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
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++) {
Eric Laurentde070132010-07-13 04:45:46 -07009046 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9047 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009048 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009049 }
9050 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009051 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009052}
9053
Eric Laurent59255e42011-07-27 19:49:51 -07009054// getEffectFromType_l() must be called with ThreadBase::mLock held
9055sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9056 const effect_uuid_t *type)
9057{
Eric Laurent59255e42011-07-27 19:49:51 -07009058 size_t size = mEffects.size();
9059
9060 for (size_t i = 0; i < size; i++) {
9061 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009062 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009063 }
9064 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009065 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009066}
9067
Eric Laurent91b14c42012-05-30 12:30:29 -07009068void AudioFlinger::EffectChain::clearInputBuffer()
9069{
9070 Mutex::Autolock _l(mLock);
9071 sp<ThreadBase> thread = mThread.promote();
9072 if (thread == 0) {
9073 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9074 return;
9075 }
9076 clearInputBuffer_l(thread);
9077}
9078
9079// Must be called with EffectChain::mLock locked
9080void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9081{
9082 size_t numSamples = thread->frameCount() * thread->channelCount();
9083 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9084
9085}
9086
Mathias Agopian65ab4712010-07-14 17:59:35 -07009087// Must be called with EffectChain::mLock locked
9088void AudioFlinger::EffectChain::process_l()
9089{
Eric Laurentdac69112010-09-28 14:09:57 -07009090 sp<ThreadBase> thread = mThread.promote();
9091 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009092 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009093 return;
9094 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009095 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9096 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009097 // always process effects unless no more tracks are on the session and the effect tail
9098 // has been rendered
9099 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009100 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009101 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009102
Eric Laurent544fe9b2011-11-11 15:42:52 -08009103 if (!tracksOnSession && mTailBufferCount == 0) {
9104 doProcess = false;
9105 }
9106
9107 if (activeTrackCnt() == 0) {
9108 // if no track is active and the effect tail has not been rendered,
9109 // the input buffer must be cleared here as the mixer process will not do it
9110 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009111 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009112 if (mTailBufferCount > 0) {
9113 mTailBufferCount--;
9114 }
9115 }
9116 }
Eric Laurentdac69112010-09-28 14:09:57 -07009117 }
9118
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009120 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009121 for (size_t i = 0; i < size; i++) {
9122 mEffects[i]->process();
9123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124 }
9125 for (size_t i = 0; i < size; i++) {
9126 mEffects[i]->updateState();
9127 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128}
9129
Eric Laurentcab11242010-07-15 12:50:15 -07009130// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009131status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132{
9133 effect_descriptor_t desc = effect->desc();
9134 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9135
9136 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009137 effect->setChain(this);
9138 sp<ThreadBase> thread = mThread.promote();
9139 if (thread == 0) {
9140 return NO_INIT;
9141 }
9142 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009143
9144 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9145 // Auxiliary effects are inserted at the beginning of mEffects vector as
9146 // they are processed first and accumulated in chain input buffer
9147 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009148
Mathias Agopian65ab4712010-07-14 17:59:35 -07009149 // the input buffer for auxiliary effect contains mono samples in
9150 // 32 bit format. This is to avoid saturation in AudoMixer
9151 // accumulation stage. Saturation is done in EffectModule::process() before
9152 // calling the process in effect engine
9153 size_t numSamples = thread->frameCount();
9154 int32_t *buffer = new int32_t[numSamples];
9155 memset(buffer, 0, numSamples * sizeof(int32_t));
9156 effect->setInBuffer((int16_t *)buffer);
9157 // auxiliary effects output samples to chain input buffer for further processing
9158 // by insert effects
9159 effect->setOutBuffer(mInBuffer);
9160 } else {
9161 // Insert effects are inserted at the end of mEffects vector as they are processed
9162 // after track and auxiliary effects.
9163 // Insert effect order as a function of indicated preference:
9164 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9165 // another effect is present
9166 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9167 // last effect claiming first position
9168 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9169 // first effect claiming last position
9170 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9171 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9172 // already present
9173
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009174 size_t size = mEffects.size();
9175 size_t idx_insert = size;
9176 ssize_t idx_insert_first = -1;
9177 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009178
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009179 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009180 effect_descriptor_t d = mEffects[i]->desc();
9181 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9182 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9183 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9184 // check invalid effect chaining combinations
9185 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9186 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009187 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009188 return INVALID_OPERATION;
9189 }
9190 // remember position of first insert effect and by default
9191 // select this as insert position for new effect
9192 if (idx_insert == size) {
9193 idx_insert = i;
9194 }
9195 // remember position of last insert effect claiming
9196 // first position
9197 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9198 idx_insert_first = i;
9199 }
9200 // remember position of first insert effect claiming
9201 // last position
9202 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9203 idx_insert_last == -1) {
9204 idx_insert_last = i;
9205 }
9206 }
9207 }
9208
9209 // modify idx_insert from first position if needed
9210 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9211 if (idx_insert_last != -1) {
9212 idx_insert = idx_insert_last;
9213 } else {
9214 idx_insert = size;
9215 }
9216 } else {
9217 if (idx_insert_first != -1) {
9218 idx_insert = idx_insert_first + 1;
9219 }
9220 }
9221
9222 // always read samples from chain input buffer
9223 effect->setInBuffer(mInBuffer);
9224
9225 // if last effect in the chain, output samples to chain
9226 // output buffer, otherwise to chain input buffer
9227 if (idx_insert == size) {
9228 if (idx_insert != 0) {
9229 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9230 mEffects[idx_insert-1]->configure();
9231 }
9232 effect->setOutBuffer(mOutBuffer);
9233 } else {
9234 effect->setOutBuffer(mInBuffer);
9235 }
9236 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237
Steve Block3856b092011-10-20 11:56:00 +01009238 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009239 }
9240 effect->configure();
9241 return NO_ERROR;
9242}
9243
Eric Laurentcab11242010-07-15 12:50:15 -07009244// removeEffect_l() must be called with PlaybackThread::mLock held
9245size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009246{
9247 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009248 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009249 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9250
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009251 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009253 // calling stop here will remove pre-processing effect from the audio HAL.
9254 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9255 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009256 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9257 mEffects[i]->state() == EffectModule::STOPPING) {
9258 mEffects[i]->stop();
9259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009260 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9261 delete[] effect->inBuffer();
9262 } else {
9263 if (i == size - 1 && i != 0) {
9264 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9265 mEffects[i - 1]->configure();
9266 }
9267 }
9268 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009269 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009270 break;
9271 }
9272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273
9274 return mEffects.size();
9275}
9276
Eric Laurentcab11242010-07-15 12:50:15 -07009277// setDevice_l() must be called with PlaybackThread::mLock held
9278void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009279{
9280 size_t size = mEffects.size();
9281 for (size_t i = 0; i < size; i++) {
9282 mEffects[i]->setDevice(device);
9283 }
9284}
9285
Eric Laurentcab11242010-07-15 12:50:15 -07009286// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009287void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288{
9289 size_t size = mEffects.size();
9290 for (size_t i = 0; i < size; i++) {
9291 mEffects[i]->setMode(mode);
9292 }
9293}
9294
Eric Laurentcab11242010-07-15 12:50:15 -07009295// setVolume_l() must be called with PlaybackThread::mLock held
9296bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009297{
9298 uint32_t newLeft = *left;
9299 uint32_t newRight = *right;
9300 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009301 int ctrlIdx = -1;
9302 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009303
Eric Laurentcab11242010-07-15 12:50:15 -07009304 // first update volume controller
9305 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009306 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009307 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9308 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009309 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009310 break;
9311 }
9312 }
9313
9314 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009315 if (hasControl) {
9316 *left = mNewLeftVolume;
9317 *right = mNewRightVolume;
9318 }
9319 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009320 }
9321
9322 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009323 mLeftVolume = newLeft;
9324 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009325
9326 // second get volume update from volume controller
9327 if (ctrlIdx >= 0) {
9328 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009329 mNewLeftVolume = newLeft;
9330 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009331 }
9332 // then indicate volume to all other effects in chain.
9333 // Pass altered volume to effects before volume controller
9334 // and requested volume to effects after controller
9335 uint32_t lVol = newLeft;
9336 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009337
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009339 if ((int)i == ctrlIdx) continue;
9340 // this also works for ctrlIdx == -1 when there is no volume controller
9341 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009342 lVol = *left;
9343 rVol = *right;
9344 }
9345 mEffects[i]->setVolume(&lVol, &rVol, false);
9346 }
9347 *left = newLeft;
9348 *right = newRight;
9349
9350 return hasControl;
9351}
9352
Mathias Agopian65ab4712010-07-14 17:59:35 -07009353status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9354{
9355 const size_t SIZE = 256;
9356 char buffer[SIZE];
9357 String8 result;
9358
9359 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9360 result.append(buffer);
9361
9362 bool locked = tryLock(mLock);
9363 // failed to lock - AudioFlinger is probably deadlocked
9364 if (!locked) {
9365 result.append("\tCould not lock mutex:\n");
9366 }
9367
Eric Laurentcab11242010-07-15 12:50:15 -07009368 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9369 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009370 mEffects.size(),
9371 (uint32_t)mInBuffer,
9372 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373 mActiveTrackCnt);
9374 result.append(buffer);
9375 write(fd, result.string(), result.size());
9376
9377 for (size_t i = 0; i < mEffects.size(); ++i) {
9378 sp<EffectModule> effect = mEffects[i];
9379 if (effect != 0) {
9380 effect->dump(fd, args);
9381 }
9382 }
9383
9384 if (locked) {
9385 mLock.unlock();
9386 }
9387
9388 return NO_ERROR;
9389}
9390
Eric Laurent59255e42011-07-27 19:49:51 -07009391// must be called with ThreadBase::mLock held
9392void AudioFlinger::EffectChain::setEffectSuspended_l(
9393 const effect_uuid_t *type, bool suspend)
9394{
9395 sp<SuspendedEffectDesc> desc;
9396 // use effect type UUID timelow as key as there is no real risk of identical
9397 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009398 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009399 if (suspend) {
9400 if (index >= 0) {
9401 desc = mSuspendedEffects.valueAt(index);
9402 } else {
9403 desc = new SuspendedEffectDesc();
9404 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9405 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009406 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009407 }
9408 if (desc->mRefCount++ == 0) {
9409 sp<EffectModule> effect = getEffectIfEnabled(type);
9410 if (effect != 0) {
9411 desc->mEffect = effect;
9412 effect->setSuspended(true);
9413 effect->setEnabled(false);
9414 }
9415 }
9416 } else {
9417 if (index < 0) {
9418 return;
9419 }
9420 desc = mSuspendedEffects.valueAt(index);
9421 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009422 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009423 desc->mRefCount = 1;
9424 }
9425 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009426 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009427 if (desc->mEffect != 0) {
9428 sp<EffectModule> effect = desc->mEffect.promote();
9429 if (effect != 0) {
9430 effect->setSuspended(false);
9431 sp<EffectHandle> handle = effect->controlHandle();
9432 if (handle != 0) {
9433 effect->setEnabled(handle->enabled());
9434 }
9435 }
9436 desc->mEffect.clear();
9437 }
9438 mSuspendedEffects.removeItemsAt(index);
9439 }
9440 }
9441}
9442
9443// must be called with ThreadBase::mLock held
9444void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9445{
9446 sp<SuspendedEffectDesc> desc;
9447
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009448 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009449 if (suspend) {
9450 if (index >= 0) {
9451 desc = mSuspendedEffects.valueAt(index);
9452 } else {
9453 desc = new SuspendedEffectDesc();
9454 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009455 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009456 }
9457 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009458 Vector< sp<EffectModule> > effects;
9459 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009460 for (size_t i = 0; i < effects.size(); i++) {
9461 setEffectSuspended_l(&effects[i]->desc().type, true);
9462 }
9463 }
9464 } else {
9465 if (index < 0) {
9466 return;
9467 }
9468 desc = mSuspendedEffects.valueAt(index);
9469 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009470 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009471 desc->mRefCount = 1;
9472 }
9473 if (--desc->mRefCount == 0) {
9474 Vector<const effect_uuid_t *> types;
9475 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9476 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9477 continue;
9478 }
9479 types.add(&mSuspendedEffects.valueAt(i)->mType);
9480 }
9481 for (size_t i = 0; i < types.size(); i++) {
9482 setEffectSuspended_l(types[i], false);
9483 }
Steve Block3856b092011-10-20 11:56:00 +01009484 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009485 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9486 }
9487 }
9488}
9489
Eric Laurent6bffdb82011-09-23 08:40:41 -07009490
9491// The volume effect is used for automated tests only
9492#ifndef OPENSL_ES_H_
9493static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9494 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9495const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9496#endif //OPENSL_ES_H_
9497
Eric Laurentdb7c0792011-08-10 10:37:50 -07009498bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9499{
9500 // auxiliary effects and visualizer are never suspended on output mix
9501 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9502 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009503 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9504 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009505 return false;
9506 }
9507 return true;
9508}
9509
Glenn Kastend0539712012-01-30 12:56:03 -08009510void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009511{
Glenn Kastend0539712012-01-30 12:56:03 -08009512 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009513 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009514 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9515 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 }
Eric Laurent59255e42011-07-27 19:49:51 -07009517 }
Eric Laurent59255e42011-07-27 19:49:51 -07009518}
9519
9520sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9521 const effect_uuid_t *type)
9522{
Glenn Kasten090f0192012-01-30 13:00:02 -08009523 sp<EffectModule> effect = getEffectFromType_l(type);
9524 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009525}
9526
9527void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9528 bool enabled)
9529{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009530 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009531 if (enabled) {
9532 if (index < 0) {
9533 // if the effect is not suspend check if all effects are suspended
9534 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9535 if (index < 0) {
9536 return;
9537 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009538 if (!isEffectEligibleForSuspend(effect->desc())) {
9539 return;
9540 }
Eric Laurent59255e42011-07-27 19:49:51 -07009541 setEffectSuspended_l(&effect->desc().type, enabled);
9542 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009543 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009544 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009545 return;
9546 }
Eric Laurent59255e42011-07-27 19:49:51 -07009547 }
Steve Block3856b092011-10-20 11:56:00 +01009548 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009549 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009550 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9551 // if effect is requested to suspended but was not yet enabled, supend it now.
9552 if (desc->mEffect == 0) {
9553 desc->mEffect = effect;
9554 effect->setEnabled(false);
9555 effect->setSuspended(true);
9556 }
9557 } else {
9558 if (index < 0) {
9559 return;
9560 }
Steve Block3856b092011-10-20 11:56:00 +01009561 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009562 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009563 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9564 desc->mEffect.clear();
9565 effect->setSuspended(false);
9566 }
9567}
9568
Mathias Agopian65ab4712010-07-14 17:59:35 -07009569#undef LOG_TAG
9570#define LOG_TAG "AudioFlinger"
9571
9572// ----------------------------------------------------------------------------
9573
9574status_t AudioFlinger::onTransact(
9575 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9576{
9577 return BnAudioFlinger::onTransact(code, data, reply, flags);
9578}
9579
Mathias Agopian65ab4712010-07-14 17:59:35 -07009580}; // namespace android