blob: abe02932e9890c6ef2d9e6fff979abe58cc3f146 [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);
4699 if (srcThread == 0) {
4700 return INVALID_OPERATION;
4701 }
4702
4703 if (EffectId != 0 && playbackThread != srcThread.get()) {
4704 Mutex::Autolock _dl(playbackThread->mLock);
4705 Mutex::Autolock _sl(srcThread->mLock);
4706 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4707 if (chain == 0) {
4708 return INVALID_OPERATION;
4709 }
4710
4711 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4712 if (effect == 0) {
4713 return INVALID_OPERATION;
4714 }
4715 srcThread->removeEffect_l(effect);
4716 playbackThread->addEffect_l(effect);
4717 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4718 if (effect->state() == EffectModule::ACTIVE ||
4719 effect->state() == EffectModule::STOPPING) {
4720 effect->start();
4721 }
4722
4723 sp<EffectChain> dstChain = effect->chain().promote();
4724 if (dstChain == 0) {
4725 srcThread->addEffect_l(effect);
4726 return INVALID_OPERATION;
4727 }
4728 AudioSystem::unregisterEffect(effect->id());
4729 AudioSystem::registerEffect(&effect->desc(),
4730 srcThread->id(),
4731 dstChain->strategy(),
4732 AUDIO_SESSION_OUTPUT_MIX,
4733 effect->id());
4734 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004735 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 }
4737 return status;
4738}
4739
4740void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4741{
4742 mAuxEffectId = EffectId;
4743 mAuxBuffer = buffer;
4744}
4745
Eric Laurenta011e352012-03-29 15:51:43 -07004746bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4747 size_t audioHalFrames)
4748{
4749 // a track is considered presented when the total number of frames written to audio HAL
4750 // corresponds to the number of frames written when presentationComplete() is called for the
4751 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4752 if (mPresentationCompleteFrames == 0) {
4753 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4754 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4755 mPresentationCompleteFrames, audioHalFrames);
4756 }
4757 if (framesWritten >= mPresentationCompleteFrames) {
4758 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4759 mSessionId, framesWritten);
4760 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004761 return true;
4762 }
4763 return false;
4764}
4765
4766void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4767{
4768 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4769 if (mSyncEvents[i]->type() == type) {
4770 mSyncEvents[i]->trigger();
4771 mSyncEvents.removeAt(i);
4772 i--;
4773 }
4774 }
4775}
4776
Glenn Kasten58912562012-04-03 10:45:00 -07004777// implement VolumeBufferProvider interface
4778
4779uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4780{
4781 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4782 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4783 uint32_t vlr = mCblk->getVolumeLR();
4784 uint32_t vl = vlr & 0xFFFF;
4785 uint32_t vr = vlr >> 16;
4786 // track volumes come from shared memory, so can't be trusted and must be clamped
4787 if (vl > MAX_GAIN_INT) {
4788 vl = MAX_GAIN_INT;
4789 }
4790 if (vr > MAX_GAIN_INT) {
4791 vr = MAX_GAIN_INT;
4792 }
4793 // now apply the cached master volume and stream type volume;
4794 // this is trusted but lacks any synchronization or barrier so may be stale
4795 float v = mCachedVolume;
4796 vl *= v;
4797 vr *= v;
4798 // re-combine into U4.16
4799 vlr = (vr << 16) | (vl & 0xFFFF);
4800 // FIXME look at mute, pause, and stop flags
4801 return vlr;
4802}
Eric Laurenta011e352012-03-29 15:51:43 -07004803
Eric Laurent29864602012-05-08 18:57:51 -07004804status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4805{
4806 if (mState == TERMINATED || mState == PAUSED ||
4807 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4808 (mState == STOPPED)))) {
4809 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4810 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4811 event->cancel();
4812 return INVALID_OPERATION;
4813 }
4814 TrackBase::setSyncEvent(event);
4815 return NO_ERROR;
4816}
4817
John Grossman4ff14ba2012-02-08 16:37:41 -08004818// timed audio tracks
4819
4820sp<AudioFlinger::PlaybackThread::TimedTrack>
4821AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004822 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004823 const sp<Client>& client,
4824 audio_stream_type_t streamType,
4825 uint32_t sampleRate,
4826 audio_format_t format,
4827 uint32_t channelMask,
4828 int frameCount,
4829 const sp<IMemory>& sharedBuffer,
4830 int sessionId) {
4831 if (!client->reserveTimedTrack())
4832 return NULL;
4833
Glenn Kastena0356762012-03-19 10:38:51 -07004834 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004835 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4836 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004837}
4838
4839AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004840 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004841 const sp<Client>& client,
4842 audio_stream_type_t streamType,
4843 uint32_t sampleRate,
4844 audio_format_t format,
4845 uint32_t channelMask,
4846 int frameCount,
4847 const sp<IMemory>& sharedBuffer,
4848 int sessionId)
4849 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004850 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004851 mQueueHeadInFlight(false),
4852 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004853 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004854 mTimedSilenceBuffer(NULL),
4855 mTimedSilenceBufferSize(0),
4856 mTimedAudioOutputOnTime(false),
4857 mMediaTimeTransformValid(false)
4858{
4859 LocalClock lc;
4860 mLocalTimeFreq = lc.getLocalFreq();
4861
4862 mLocalTimeToSampleTransform.a_zero = 0;
4863 mLocalTimeToSampleTransform.b_zero = 0;
4864 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4865 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4866 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4867 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004868
4869 mMediaTimeToSampleTransform.a_zero = 0;
4870 mMediaTimeToSampleTransform.b_zero = 0;
4871 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4872 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4873 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4874 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004875}
4876
4877AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4878 mClient->releaseTimedTrack();
4879 delete [] mTimedSilenceBuffer;
4880}
4881
4882status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4883 size_t size, sp<IMemory>* buffer) {
4884
4885 Mutex::Autolock _l(mTimedBufferQueueLock);
4886
4887 trimTimedBufferQueue_l();
4888
4889 // lazily initialize the shared memory heap for timed buffers
4890 if (mTimedMemoryDealer == NULL) {
4891 const int kTimedBufferHeapSize = 512 << 10;
4892
4893 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4894 "AudioFlingerTimed");
4895 if (mTimedMemoryDealer == NULL)
4896 return NO_MEMORY;
4897 }
4898
4899 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4900 if (newBuffer == NULL) {
4901 newBuffer = mTimedMemoryDealer->allocate(size);
4902 if (newBuffer == NULL)
4903 return NO_MEMORY;
4904 }
4905
4906 *buffer = newBuffer;
4907 return NO_ERROR;
4908}
4909
4910// caller must hold mTimedBufferQueueLock
4911void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4912 int64_t mediaTimeNow;
4913 {
4914 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4915 if (!mMediaTimeTransformValid)
4916 return;
4917
4918 int64_t targetTimeNow;
4919 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4920 ? mCCHelper.getCommonTime(&targetTimeNow)
4921 : mCCHelper.getLocalTime(&targetTimeNow);
4922
4923 if (OK != res)
4924 return;
4925
4926 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4927 &mediaTimeNow)) {
4928 return;
4929 }
4930 }
4931
John Grossman1c345192012-03-27 14:00:17 -07004932 size_t trimEnd;
4933 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004934 int64_t bufEnd;
4935
John Grossmanc95cfbb2012-04-12 11:53:11 -07004936 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4937 // We have a next buffer. Just use its PTS as the PTS of the frame
4938 // following the last frame in this buffer. If the stream is sparse
4939 // (ie, there are deliberate gaps left in the stream which should be
4940 // filled with silence by the TimedAudioTrack), then this can result
4941 // in one extra buffer being left un-trimmed when it could have
4942 // been. In general, this is not typical, and we would rather
4943 // optimized away the TS calculation below for the more common case
4944 // where PTSes are contiguous.
4945 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4946 } else {
4947 // We have no next buffer. Compute the PTS of the frame following
4948 // the last frame in this buffer by computing the duration of of
4949 // this frame in media time units and adding it to the PTS of the
4950 // buffer.
4951 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4952 / mCblk->frameSize;
4953
4954 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4955 &bufEnd)) {
4956 ALOGE("Failed to convert frame count of %lld to media time"
4957 " duration" " (scale factor %d/%u) in %s",
4958 frameCount,
4959 mMediaTimeToSampleTransform.a_to_b_numer,
4960 mMediaTimeToSampleTransform.a_to_b_denom,
4961 __PRETTY_FUNCTION__);
4962 break;
4963 }
4964 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004965 }
John Grossman9fbdee12012-03-26 17:51:46 -07004966
4967 if (bufEnd > mediaTimeNow)
4968 break;
4969
4970 // Is the buffer we want to use in the middle of a mix operation right
4971 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4972 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004973 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004974 mTrimQueueHeadOnRelease = true;
4975 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 }
4977
John Grossman9fbdee12012-03-26 17:51:46 -07004978 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004979 if (trimStart < trimEnd) {
4980 // Update the bookkeeping for framesReady()
4981 for (size_t i = trimStart; i < trimEnd; ++i) {
4982 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4983 }
4984
4985 // Now actually remove the buffers from the queue.
4986 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004987 }
4988}
4989
John Grossman1c345192012-03-27 14:00:17 -07004990void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4991 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004992 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4993 "%s called (reason \"%s\"), but timed buffer queue has no"
4994 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004995
4996 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4997 mTimedBufferQueue.removeAt(0);
4998}
4999
5000void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5001 const TimedBuffer& buf,
5002 const char* logTag) {
5003 uint32_t bufBytes = buf.buffer()->size();
5004 uint32_t consumedAlready = buf.position();
5005
Eric Laurentb388e532012-04-14 13:32:48 -07005006 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005007 "Bad bookkeeping while updating frames pending. Timed buffer is"
5008 " only %u bytes long, but claims to have consumed %u"
5009 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005010 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005011
5012 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005013 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5014 "Bad bookkeeping while updating frames pending. Should have at"
5015 " least %u queued frames, but we think we have only %u. (update"
5016 " reason: \"%s\")",
5017 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005018
5019 mFramesPendingInQueue -= bufFrames;
5020}
5021
John Grossman4ff14ba2012-02-08 16:37:41 -08005022status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5023 const sp<IMemory>& buffer, int64_t pts) {
5024
5025 {
5026 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5027 if (!mMediaTimeTransformValid)
5028 return INVALID_OPERATION;
5029 }
5030
5031 Mutex::Autolock _l(mTimedBufferQueueLock);
5032
John Grossman1c345192012-03-27 14:00:17 -07005033 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5034 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005035 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5036
5037 return NO_ERROR;
5038}
5039
5040status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5041 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5042
John Grossman1c345192012-03-27 14:00:17 -07005043 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5044 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5045 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005046
5047 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5048 target == TimedAudioTrack::COMMON_TIME)) {
5049 return BAD_VALUE;
5050 }
5051
5052 Mutex::Autolock lock(mMediaTimeTransformLock);
5053 mMediaTimeTransform = xform;
5054 mMediaTimeTransformTarget = target;
5055 mMediaTimeTransformValid = true;
5056
5057 return NO_ERROR;
5058}
5059
5060#define min(a, b) ((a) < (b) ? (a) : (b))
5061
5062// implementation of getNextBuffer for tracks whose buffers have timestamps
5063status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5064 AudioBufferProvider::Buffer* buffer, int64_t pts)
5065{
5066 if (pts == AudioBufferProvider::kInvalidPTS) {
5067 buffer->raw = 0;
5068 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005069 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005070 return INVALID_OPERATION;
5071 }
5072
John Grossman4ff14ba2012-02-08 16:37:41 -08005073 Mutex::Autolock _l(mTimedBufferQueueLock);
5074
John Grossman9fbdee12012-03-26 17:51:46 -07005075 ALOG_ASSERT(!mQueueHeadInFlight,
5076 "getNextBuffer called without releaseBuffer!");
5077
John Grossman4ff14ba2012-02-08 16:37:41 -08005078 while (true) {
5079
5080 // if we have no timed buffers, then fail
5081 if (mTimedBufferQueue.isEmpty()) {
5082 buffer->raw = 0;
5083 buffer->frameCount = 0;
5084 return NOT_ENOUGH_DATA;
5085 }
5086
5087 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5088
5089 // calculate the PTS of the head of the timed buffer queue expressed in
5090 // local time
5091 int64_t headLocalPTS;
5092 {
5093 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5094
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005095 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005096
5097 if (mMediaTimeTransform.a_to_b_denom == 0) {
5098 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005099 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005100 return NO_ERROR;
5101 }
5102
5103 int64_t transformedPTS;
5104 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5105 &transformedPTS)) {
5106 // the transform failed. this shouldn't happen, but if it does
5107 // then just drop this buffer
5108 ALOGW("timedGetNextBuffer transform failed");
5109 buffer->raw = 0;
5110 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005111 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005112 return NO_ERROR;
5113 }
5114
5115 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5116 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5117 &headLocalPTS)) {
5118 buffer->raw = 0;
5119 buffer->frameCount = 0;
5120 return INVALID_OPERATION;
5121 }
5122 } else {
5123 headLocalPTS = transformedPTS;
5124 }
5125 }
5126
5127 // adjust the head buffer's PTS to reflect the portion of the head buffer
5128 // that has already been consumed
5129 int64_t effectivePTS = headLocalPTS +
5130 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5131
5132 // Calculate the delta in samples between the head of the input buffer
5133 // queue and the start of the next output buffer that will be written.
5134 // If the transformation fails because of over or underflow, it means
5135 // that the sample's position in the output stream is so far out of
5136 // whack that it should just be dropped.
5137 int64_t sampleDelta;
5138 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5139 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005140 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5141 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005142 continue;
5143 }
5144 if (!mLocalTimeToSampleTransform.doForwardTransform(
5145 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005146 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005147 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005148 continue;
5149 }
5150
John Grossman1c345192012-03-27 14:00:17 -07005151 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5152 " sampleDelta=[%d.%08x]",
5153 head.pts(), head.position(), pts,
5154 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5155 + (sampleDelta >> 32)),
5156 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005157
5158 // if the delta between the ideal placement for the next input sample and
5159 // the current output position is within this threshold, then we will
5160 // concatenate the next input samples to the previous output
5161 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005162 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005163
5164 // if this is the first buffer of audio that we're emitting from this track
5165 // then it should be almost exactly on time.
5166 const int64_t kSampleStartupThreshold = 1LL << 32;
5167
5168 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005169 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005170 // the next input is close enough to being on time, so concatenate it
5171 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005172 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005173
John Grossman1c345192012-03-27 14:00:17 -07005174 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5175 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005176 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005177 }
5178
5179 // Looks like our output is not on time. Reset our on timed status.
5180 // Next time we mix samples from our input queue, then should be within
5181 // the StartupThreshold.
5182 mTimedAudioOutputOnTime = false;
5183 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005184 // the gap between the current output position and the proper start of
5185 // the next input sample is too big, so fill it with silence
5186 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5187
John Grossman9fbdee12012-03-26 17:51:46 -07005188 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005189 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5190 return NO_ERROR;
5191 } else {
5192 // the next input sample is late
5193 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5194 size_t onTimeSamplePosition =
5195 head.position() + lateFrames * mCblk->frameSize;
5196
5197 if (onTimeSamplePosition > head.buffer()->size()) {
5198 // all the remaining samples in the head are too late, so
5199 // drop it and move on
5200 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005201 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005202 continue;
5203 } else {
5204 // skip over the late samples
5205 head.setPosition(onTimeSamplePosition);
5206
5207 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005208 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005209
5210 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5211 return NO_ERROR;
5212 }
5213 }
5214 }
5215}
5216
5217// Yield samples from the timed buffer queue head up to the given output
5218// buffer's capacity.
5219//
5220// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005221void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005222 AudioBufferProvider::Buffer* buffer) {
5223
5224 const TimedBuffer& head = mTimedBufferQueue[0];
5225
5226 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5227 head.position());
5228
5229 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5230 mCblk->frameSize);
5231 size_t framesRequested = buffer->frameCount;
5232 buffer->frameCount = min(framesLeftInHead, framesRequested);
5233
John Grossman9fbdee12012-03-26 17:51:46 -07005234 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 mTimedAudioOutputOnTime = true;
5236}
5237
5238// Yield samples of silence up to the given output buffer's capacity
5239//
5240// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005241void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005242 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5243
5244 // lazily allocate a buffer filled with silence
5245 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5246 delete [] mTimedSilenceBuffer;
5247 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5248 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5249 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5250 }
5251
5252 buffer->raw = mTimedSilenceBuffer;
5253 size_t framesRequested = buffer->frameCount;
5254 buffer->frameCount = min(numFrames, framesRequested);
5255
5256 mTimedAudioOutputOnTime = false;
5257}
5258
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005259// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005260void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5261 AudioBufferProvider::Buffer* buffer) {
5262
5263 Mutex::Autolock _l(mTimedBufferQueueLock);
5264
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005265 // If the buffer which was just released is part of the buffer at the head
5266 // of the queue, be sure to update the amt of the buffer which has been
5267 // consumed. If the buffer being returned is not part of the head of the
5268 // queue, its either because the buffer is part of the silence buffer, or
5269 // because the head of the timed queue was trimmed after the mixer called
5270 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005271 if (buffer->raw == mTimedSilenceBuffer) {
5272 ALOG_ASSERT(!mQueueHeadInFlight,
5273 "Queue head in flight during release of silence buffer!");
5274 goto done;
5275 }
5276
5277 ALOG_ASSERT(mQueueHeadInFlight,
5278 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5279 " head in flight.");
5280
5281 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005282 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005283
5284 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005285 void* end = reinterpret_cast<void*>(
5286 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5287 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005288
John Grossman9fbdee12012-03-26 17:51:46 -07005289 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5290 "released buffer not within the head of the timed buffer"
5291 " queue; qHead = [%p, %p], released buffer = %p",
5292 start, end, buffer->raw);
5293
5294 head.setPosition(head.position() +
5295 (buffer->frameCount * mCblk->frameSize));
5296 mQueueHeadInFlight = false;
5297
John Grossman1c345192012-03-27 14:00:17 -07005298 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5299 "Bad bookkeeping during releaseBuffer! Should have at"
5300 " least %u queued frames, but we think we have only %u",
5301 buffer->frameCount, mFramesPendingInQueue);
5302
5303 mFramesPendingInQueue -= buffer->frameCount;
5304
John Grossman9fbdee12012-03-26 17:51:46 -07005305 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5306 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005307 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005308 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005309 }
John Grossman9fbdee12012-03-26 17:51:46 -07005310 } else {
5311 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5312 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005313 }
5314
John Grossman9fbdee12012-03-26 17:51:46 -07005315done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005316 buffer->raw = 0;
5317 buffer->frameCount = 0;
5318}
5319
Glenn Kasten288ed212012-04-25 17:52:27 -07005320size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005321 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005322 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005323}
5324
5325AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5326 : mPTS(0), mPosition(0) {}
5327
5328AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5329 const sp<IMemory>& buffer, int64_t pts)
5330 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5331
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332// ----------------------------------------------------------------------------
5333
5334// RecordTrack constructor must be called with AudioFlinger::mLock held
5335AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005336 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 const sp<Client>& client,
5338 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005339 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005340 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005341 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 int sessionId)
5343 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005344 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 mOverflow(false)
5346{
5347 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005348 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5349 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5350 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5351 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5352 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5353 } else {
5354 mCblk->frameSize = sizeof(int8_t);
5355 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 }
5357}
5358
5359AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5360{
5361 sp<ThreadBase> thread = mThread.promote();
5362 if (thread != 0) {
5363 AudioSystem::releaseInput(thread->id());
5364 }
5365}
5366
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005367// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005368status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369{
5370 audio_track_cblk_t* cblk = this->cblk();
5371 uint32_t framesAvail;
5372 uint32_t framesReq = buffer->frameCount;
5373
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005374 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005375 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005377 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005378 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 }
5380
5381 framesAvail = cblk->framesAvailable_l();
5382
Glenn Kastenf6b16782011-12-15 09:51:17 -08005383 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 uint32_t s = cblk->server;
5385 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5386
5387 if (framesReq > framesAvail) {
5388 framesReq = framesAvail;
5389 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005390 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 framesReq = bufferEnd - s;
5392 }
5393
5394 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005395 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396
5397 buffer->frameCount = framesReq;
5398 return NO_ERROR;
5399 }
5400
5401getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005402 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 buffer->frameCount = 0;
5404 return NOT_ENOUGH_DATA;
5405}
5406
Glenn Kasten3acbd052012-02-28 10:39:56 -08005407status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005408 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409{
5410 sp<ThreadBase> thread = mThread.promote();
5411 if (thread != 0) {
5412 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005413 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 } else {
5415 return BAD_VALUE;
5416 }
5417}
5418
5419void AudioFlinger::RecordThread::RecordTrack::stop()
5420{
5421 sp<ThreadBase> thread = mThread.promote();
5422 if (thread != 0) {
5423 RecordThread *recordThread = (RecordThread *)thread.get();
5424 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005425 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005426 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005427 // read from buffer
5428 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 }
5430}
5431
5432void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5433{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005434 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005435 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005437 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 mSessionId,
5439 mFrameCount,
5440 mState,
5441 mCblk->sampleRate,
5442 mCblk->server,
5443 mCblk->user);
5444}
5445
5446
5447// ----------------------------------------------------------------------------
5448
5449AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005450 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 DuplicatingThread *sourceThread,
5452 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005453 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005454 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005456 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5457 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 mActive(false), mSourceThread(sourceThread)
5459{
5460
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 if (mCblk != NULL) {
5462 mCblk->flags |= CBLK_DIRECTION_OUT;
5463 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 mOutBuffer.frameCount = 0;
5465 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005466 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005467 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5468 mCblk, mBuffer, mCblk->buffers,
5469 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005471 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 }
5473}
5474
5475AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5476{
5477 clearBufferQueue();
5478}
5479
Glenn Kasten3acbd052012-02-28 10:39:56 -08005480status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005481 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005483 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 if (status != NO_ERROR) {
5485 return status;
5486 }
5487
5488 mActive = true;
5489 mRetryCount = 127;
5490 return status;
5491}
5492
5493void AudioFlinger::PlaybackThread::OutputTrack::stop()
5494{
5495 Track::stop();
5496 clearBufferQueue();
5497 mOutBuffer.frameCount = 0;
5498 mActive = false;
5499}
5500
5501bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5502{
5503 Buffer *pInBuffer;
5504 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005505 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506 bool outputBufferFull = false;
5507 inBuffer.frameCount = frames;
5508 inBuffer.i16 = data;
5509
5510 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5511
5512 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005513 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 sp<ThreadBase> thread = mThread.promote();
5515 if (thread != 0) {
5516 MixerThread *mixerThread = (MixerThread *)thread.get();
5517 if (mCblk->frameCount > frames){
5518 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5519 uint32_t startFrames = (mCblk->frameCount - frames);
5520 pInBuffer = new Buffer;
5521 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5522 pInBuffer->frameCount = startFrames;
5523 pInBuffer->i16 = pInBuffer->mBuffer;
5524 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5525 mBufferQueue.add(pInBuffer);
5526 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005527 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 }
5529 }
5530 }
5531 }
5532
5533 while (waitTimeLeftMs) {
5534 // First write pending buffers, then new data
5535 if (mBufferQueue.size()) {
5536 pInBuffer = mBufferQueue.itemAt(0);
5537 } else {
5538 pInBuffer = &inBuffer;
5539 }
5540
5541 if (pInBuffer->frameCount == 0) {
5542 break;
5543 }
5544
5545 if (mOutBuffer.frameCount == 0) {
5546 mOutBuffer.frameCount = pInBuffer->frameCount;
5547 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005548 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005549 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 outputBufferFull = true;
5551 break;
5552 }
5553 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5554 if (waitTimeLeftMs >= waitTimeMs) {
5555 waitTimeLeftMs -= waitTimeMs;
5556 } else {
5557 waitTimeLeftMs = 0;
5558 }
5559 }
5560
5561 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5562 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5563 mCblk->stepUser(outFrames);
5564 pInBuffer->frameCount -= outFrames;
5565 pInBuffer->i16 += outFrames * channelCount;
5566 mOutBuffer.frameCount -= outFrames;
5567 mOutBuffer.i16 += outFrames * channelCount;
5568
5569 if (pInBuffer->frameCount == 0) {
5570 if (mBufferQueue.size()) {
5571 mBufferQueue.removeAt(0);
5572 delete [] pInBuffer->mBuffer;
5573 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005574 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 } else {
5576 break;
5577 }
5578 }
5579 }
5580
5581 // If we could not write all frames, allocate a buffer and queue it for next time.
5582 if (inBuffer.frameCount) {
5583 sp<ThreadBase> thread = mThread.promote();
5584 if (thread != 0 && !thread->standby()) {
5585 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5586 pInBuffer = new Buffer;
5587 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5588 pInBuffer->frameCount = inBuffer.frameCount;
5589 pInBuffer->i16 = pInBuffer->mBuffer;
5590 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5591 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005592 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005594 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 }
5597 }
5598
5599 // Calling write() with a 0 length buffer, means that no more data will be written:
5600 // If no more buffers are pending, fill output track buffer to make sure it is started
5601 // by output mixer.
5602 if (frames == 0 && mBufferQueue.size() == 0) {
5603 if (mCblk->user < mCblk->frameCount) {
5604 frames = mCblk->frameCount - mCblk->user;
5605 pInBuffer = new Buffer;
5606 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5607 pInBuffer->frameCount = frames;
5608 pInBuffer->i16 = pInBuffer->mBuffer;
5609 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5610 mBufferQueue.add(pInBuffer);
5611 } else if (mActive) {
5612 stop();
5613 }
5614 }
5615
5616 return outputBufferFull;
5617}
5618
5619status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5620{
5621 int active;
5622 status_t result;
5623 audio_track_cblk_t* cblk = mCblk;
5624 uint32_t framesReq = buffer->frameCount;
5625
Steve Block3856b092011-10-20 11:56:00 +01005626// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 buffer->frameCount = 0;
5628
5629 uint32_t framesAvail = cblk->framesAvailable();
5630
5631
5632 if (framesAvail == 0) {
5633 Mutex::Autolock _l(cblk->lock);
5634 goto start_loop_here;
5635 while (framesAvail == 0) {
5636 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005637 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005638 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005639 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640 }
5641 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5642 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005643 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644 }
5645 // read the server count again
5646 start_loop_here:
5647 framesAvail = cblk->framesAvailable_l();
5648 }
5649 }
5650
5651// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005652// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005653// }
5654
5655 if (framesReq > framesAvail) {
5656 framesReq = framesAvail;
5657 }
5658
5659 uint32_t u = cblk->user;
5660 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5661
Marco Nelissena1472d92012-03-30 14:36:54 -07005662 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 framesReq = bufferEnd - u;
5664 }
5665
5666 buffer->frameCount = framesReq;
5667 buffer->raw = (void *)cblk->buffer(u);
5668 return NO_ERROR;
5669}
5670
5671
5672void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5673{
5674 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675
5676 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005677 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 delete [] pBuffer->mBuffer;
5679 delete pBuffer;
5680 }
5681 mBufferQueue.clear();
5682}
5683
5684// ----------------------------------------------------------------------------
5685
5686AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5687 : RefBase(),
5688 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005689 // 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 -07005690 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005691 mPid(pid),
5692 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693{
5694 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5695}
5696
5697// Client destructor must be called with AudioFlinger::mLock held
5698AudioFlinger::Client::~Client()
5699{
5700 mAudioFlinger->removeClient_l(mPid);
5701}
5702
Glenn Kasten435dbe62012-01-30 10:15:48 -08005703sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704{
5705 return mMemoryDealer;
5706}
5707
John Grossman4ff14ba2012-02-08 16:37:41 -08005708// Reserve one of the limited slots for a timed audio track associated
5709// with this client
5710bool AudioFlinger::Client::reserveTimedTrack()
5711{
5712 const int kMaxTimedTracksPerClient = 4;
5713
5714 Mutex::Autolock _l(mTimedTrackLock);
5715
5716 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5717 ALOGW("can not create timed track - pid %d has exceeded the limit",
5718 mPid);
5719 return false;
5720 }
5721
5722 mTimedTrackCount++;
5723 return true;
5724}
5725
5726// Release a slot for a timed audio track
5727void AudioFlinger::Client::releaseTimedTrack()
5728{
5729 Mutex::Autolock _l(mTimedTrackLock);
5730 mTimedTrackCount--;
5731}
5732
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733// ----------------------------------------------------------------------------
5734
5735AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5736 const sp<IAudioFlingerClient>& client,
5737 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005738 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739{
5740}
5741
5742AudioFlinger::NotificationClient::~NotificationClient()
5743{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744}
5745
5746void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5747{
5748 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005749 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750}
5751
5752// ----------------------------------------------------------------------------
5753
5754AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5755 : BnAudioTrack(),
5756 mTrack(track)
5757{
5758}
5759
5760AudioFlinger::TrackHandle::~TrackHandle() {
5761 // just stop the track on deletion, associated resources
5762 // will be freed from the main thread once all pending buffers have
5763 // been played. Unless it's not in the active track list, in which
5764 // case we free everything now...
5765 mTrack->destroy();
5766}
5767
Glenn Kasten90716c52012-01-26 13:40:12 -08005768sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5769 return mTrack->getCblk();
5770}
5771
Glenn Kasten3acbd052012-02-28 10:39:56 -08005772status_t AudioFlinger::TrackHandle::start() {
5773 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774}
5775
5776void AudioFlinger::TrackHandle::stop() {
5777 mTrack->stop();
5778}
5779
5780void AudioFlinger::TrackHandle::flush() {
5781 mTrack->flush();
5782}
5783
5784void AudioFlinger::TrackHandle::mute(bool e) {
5785 mTrack->mute(e);
5786}
5787
5788void AudioFlinger::TrackHandle::pause() {
5789 mTrack->pause();
5790}
5791
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5793{
5794 return mTrack->attachAuxEffect(EffectId);
5795}
5796
John Grossman4ff14ba2012-02-08 16:37:41 -08005797status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5798 sp<IMemory>* buffer) {
5799 if (!mTrack->isTimedTrack())
5800 return INVALID_OPERATION;
5801
5802 PlaybackThread::TimedTrack* tt =
5803 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5804 return tt->allocateTimedBuffer(size, buffer);
5805}
5806
5807status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5808 int64_t pts) {
5809 if (!mTrack->isTimedTrack())
5810 return INVALID_OPERATION;
5811
5812 PlaybackThread::TimedTrack* tt =
5813 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5814 return tt->queueTimedBuffer(buffer, pts);
5815}
5816
5817status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5818 const LinearTransform& xform, int target) {
5819
5820 if (!mTrack->isTimedTrack())
5821 return INVALID_OPERATION;
5822
5823 PlaybackThread::TimedTrack* tt =
5824 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5825 return tt->setMediaTimeTransform(
5826 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5827}
5828
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829status_t AudioFlinger::TrackHandle::onTransact(
5830 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5831{
5832 return BnAudioTrack::onTransact(code, data, reply, flags);
5833}
5834
5835// ----------------------------------------------------------------------------
5836
5837sp<IAudioRecord> AudioFlinger::openRecord(
5838 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005839 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005841 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005842 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005844 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845 int *sessionId,
5846 status_t *status)
5847{
5848 sp<RecordThread::RecordTrack> recordTrack;
5849 sp<RecordHandle> recordHandle;
5850 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 status_t lStatus;
5852 RecordThread *thread;
5853 size_t inFrameCount;
5854 int lSessionId;
5855
5856 // check calling permissions
5857 if (!recordingAllowed()) {
5858 lStatus = PERMISSION_DENIED;
5859 goto Exit;
5860 }
5861
5862 // add client to list
5863 { // scope for mLock
5864 Mutex::Autolock _l(mLock);
5865 thread = checkRecordThread_l(input);
5866 if (thread == NULL) {
5867 lStatus = BAD_VALUE;
5868 goto Exit;
5869 }
5870
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005871 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872
5873 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005874 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 lSessionId = *sessionId;
5876 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005877 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 if (sessionId != NULL) {
5879 *sessionId = lSessionId;
5880 }
5881 }
5882 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005883 recordTrack = thread->createRecordTrack_l(client,
5884 sampleRate,
5885 format,
5886 channelMask,
5887 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005888 lSessionId,
5889 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005891 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5893 // destructor is called by the TrackBase destructor with mLock held
5894 client.clear();
5895 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 goto Exit;
5897 }
5898
5899 // return to handle to client
5900 recordHandle = new RecordHandle(recordTrack);
5901 lStatus = NO_ERROR;
5902
5903Exit:
5904 if (status) {
5905 *status = lStatus;
5906 }
5907 return recordHandle;
5908}
5909
5910// ----------------------------------------------------------------------------
5911
5912AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5913 : BnAudioRecord(),
5914 mRecordTrack(recordTrack)
5915{
5916}
5917
5918AudioFlinger::RecordHandle::~RecordHandle() {
5919 stop();
5920}
5921
Glenn Kasten90716c52012-01-26 13:40:12 -08005922sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5923 return mRecordTrack->getCblk();
5924}
5925
Glenn Kasten3acbd052012-02-28 10:39:56 -08005926status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005927 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005928 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929}
5930
5931void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005932 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 mRecordTrack->stop();
5934}
5935
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936status_t AudioFlinger::RecordHandle::onTransact(
5937 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5938{
5939 return BnAudioRecord::onTransact(code, data, reply, flags);
5940}
5941
5942// ----------------------------------------------------------------------------
5943
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005944AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5945 AudioStreamIn *input,
5946 uint32_t sampleRate,
5947 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005948 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005949 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005950 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005951 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5952 // mRsmpInIndex and mInputBytes set by readInputParameters()
5953 mReqChannelCount(popcount(channels)),
5954 mReqSampleRate(sampleRate)
5955 // mBytesRead is only meaningful while active, and so is cleared in start()
5956 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957{
Glenn Kasten480b4682012-02-28 12:30:08 -08005958 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005959
Mathias Agopian65ab4712010-07-14 17:59:35 -07005960 readInputParameters();
5961}
5962
5963
5964AudioFlinger::RecordThread::~RecordThread()
5965{
5966 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005967 delete mResampler;
5968 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969}
5970
5971void AudioFlinger::RecordThread::onFirstRef()
5972{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005973 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974}
5975
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005976status_t AudioFlinger::RecordThread::readyToRun()
5977{
5978 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005979 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005980 return status;
5981}
5982
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983bool AudioFlinger::RecordThread::threadLoop()
5984{
5985 AudioBufferProvider::Buffer buffer;
5986 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005987 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988
Eric Laurent44d98482010-09-30 16:12:31 -07005989 nsecs_t lastWarning = 0;
5990
Eric Laurentfeb0db62011-07-22 09:04:31 -07005991 acquireWakeLock();
5992
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 // start recording
5994 while (!exitPending()) {
5995
5996 processConfigEvents();
5997
5998 { // scope for mLock
5999 Mutex::Autolock _l(mLock);
6000 checkForNewParameters_l();
6001 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
6002 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006003 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 mStandby = true;
6005 }
6006
6007 if (exitPending()) break;
6008
Eric Laurentfeb0db62011-07-22 09:04:31 -07006009 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006010 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 // go to sleep
6012 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006013 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006014 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 continue;
6016 }
6017 if (mActiveTrack != 0) {
6018 if (mActiveTrack->mState == TrackBase::PAUSING) {
6019 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006020 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 mStandby = true;
6022 }
6023 mActiveTrack.clear();
6024 mStartStopCond.broadcast();
6025 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6026 if (mReqChannelCount != mActiveTrack->channelCount()) {
6027 mActiveTrack.clear();
6028 mStartStopCond.broadcast();
6029 } else if (mBytesRead != 0) {
6030 // record start succeeds only if first read from audio input
6031 // succeeds
6032 if (mBytesRead > 0) {
6033 mActiveTrack->mState = TrackBase::ACTIVE;
6034 } else {
6035 mActiveTrack.clear();
6036 }
6037 mStartStopCond.broadcast();
6038 }
6039 mStandby = false;
6040 }
6041 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006042 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 }
6044
6045 if (mActiveTrack != 0) {
6046 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6047 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006048 unlockEffectChains(effectChains);
6049 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 continue;
6051 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 for (size_t i = 0; i < effectChains.size(); i ++) {
6053 effectChains[i]->process_l();
6054 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006055
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006057 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006059 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 // no resampling
6061 while (framesOut) {
6062 size_t framesIn = mFrameCount - mRsmpInIndex;
6063 if (framesIn) {
6064 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6065 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6066 if (framesIn > framesOut)
6067 framesIn = framesOut;
6068 mRsmpInIndex += framesIn;
6069 framesOut -= framesIn;
6070 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006071 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 memcpy(dst, src, framesIn * mFrameSize);
6073 } else {
6074 int16_t *src16 = (int16_t *)src;
6075 int16_t *dst16 = (int16_t *)dst;
6076 if (mChannelCount == 1) {
6077 while (framesIn--) {
6078 *dst16++ = *src16;
6079 *dst16++ = *src16++;
6080 }
6081 } else {
6082 while (framesIn--) {
6083 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6084 src16 += 2;
6085 }
6086 }
6087 }
6088 }
6089 if (framesOut && mFrameCount == mRsmpInIndex) {
6090 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006091 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006092 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 framesOut = 0;
6094 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006095 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 mRsmpInIndex = 0;
6097 }
6098 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006099 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6101 // Force input into standby so that it tries to
6102 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006103 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006104 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 }
6106 mRsmpInIndex = mFrameCount;
6107 framesOut = 0;
6108 buffer.frameCount = 0;
6109 }
6110 }
6111 }
6112 } else {
6113 // resampling
6114
6115 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6116 // alter output frame count as if we were expecting stereo samples
6117 if (mChannelCount == 1 && mReqChannelCount == 1) {
6118 framesOut >>= 1;
6119 }
6120 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6121 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6122 // are 32 bit aligned which should be always true.
6123 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006124 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 // the resampler always outputs stereo samples: do post stereo to mono conversion
6126 int16_t *src = (int16_t *)mRsmpOutBuffer;
6127 int16_t *dst = buffer.i16;
6128 while (framesOut--) {
6129 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6130 src += 2;
6131 }
6132 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006133 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
6135
6136 }
Eric Laurenta011e352012-03-29 15:51:43 -07006137 if (mFramestoDrop == 0) {
6138 mActiveTrack->releaseBuffer(&buffer);
6139 } else {
6140 if (mFramestoDrop > 0) {
6141 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006142 if (mFramestoDrop <= 0) {
6143 clearSyncStartEvent();
6144 }
6145 } else {
6146 mFramestoDrop += buffer.frameCount;
6147 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6148 mSyncStartEvent->isCancelled()) {
6149 ALOGW("Synced record %s, session %d, trigger session %d",
6150 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6151 mActiveTrack->sessionId(),
6152 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6153 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006154 }
6155 }
6156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 mActiveTrack->overflow();
6158 }
6159 // client isn't retrieving buffers fast enough
6160 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006161 if (!mActiveTrack->setOverflow()) {
6162 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006163 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006164 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006165 lastWarning = now;
6166 }
6167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 // Release the processor for a while before asking for a new buffer.
6169 // This will give the application more chance to read from the buffer and
6170 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 }
6173 }
Eric Laurentec437d82011-07-26 20:54:46 -07006174 // enable changes in effect chain
6175 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 }
6178
6179 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006180 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181 }
6182 mActiveTrack.clear();
6183
6184 mStartStopCond.broadcast();
6185
Eric Laurentfeb0db62011-07-22 09:04:31 -07006186 releaseWakeLock();
6187
Steve Block3856b092011-10-20 11:56:00 +01006188 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189 return false;
6190}
6191
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006192
6193sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6194 const sp<AudioFlinger::Client>& client,
6195 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006196 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006197 int channelMask,
6198 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006199 int sessionId,
6200 status_t *status)
6201{
6202 sp<RecordTrack> track;
6203 status_t lStatus;
6204
6205 lStatus = initCheck();
6206 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006207 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006208 goto Exit;
6209 }
6210
6211 { // scope for mLock
6212 Mutex::Autolock _l(mLock);
6213
6214 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006215 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216
Glenn Kasten7378ca52012-01-20 13:44:40 -08006217 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006218 lStatus = NO_MEMORY;
6219 goto Exit;
6220 }
6221
6222 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006223 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6224 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006225 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006226 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6227 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006228 }
6229 lStatus = NO_ERROR;
6230
6231Exit:
6232 if (status) {
6233 *status = lStatus;
6234 }
6235 return track;
6236}
6237
Eric Laurenta011e352012-03-29 15:51:43 -07006238status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006239 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006240 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241{
Glenn Kasten58912562012-04-03 10:45:00 -07006242 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006243 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006245
6246 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006247 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006248 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6249 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6250 triggerSession,
6251 recordTrack->sessionId(),
6252 syncStartEventCallback,
6253 this);
Eric Laurent29864602012-05-08 18:57:51 -07006254 // Sync event can be cancelled by the trigger session if the track is not in a
6255 // compatible state in which case we start record immediately
6256 if (mSyncStartEvent->isCancelled()) {
6257 clearSyncStartEvent();
6258 } else {
6259 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6260 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6261 }
Eric Laurenta011e352012-03-29 15:51:43 -07006262 }
6263
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006265 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 if (mActiveTrack != 0) {
6267 if (recordTrack != mActiveTrack.get()) {
6268 status = -EBUSY;
6269 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6270 mActiveTrack->mState = TrackBase::ACTIVE;
6271 }
6272 return status;
6273 }
6274
6275 recordTrack->mState = TrackBase::IDLE;
6276 mActiveTrack = recordTrack;
6277 mLock.unlock();
6278 status_t status = AudioSystem::startInput(mId);
6279 mLock.lock();
6280 if (status != NO_ERROR) {
6281 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006282 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 return status;
6284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 mRsmpInIndex = mFrameCount;
6286 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006287 if (mResampler != NULL) {
6288 mResampler->reset();
6289 }
6290 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006292 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 mWaitWorkCV.signal();
6294 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006295 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 mActiveTrack.clear();
6297 status = INVALID_OPERATION;
6298 goto startError;
6299 }
6300 mStartStopCond.wait(mLock);
6301 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006302 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 status = BAD_VALUE;
6304 goto startError;
6305 }
Steve Block3856b092011-10-20 11:56:00 +01006306 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 return status;
6308 }
6309startError:
6310 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006311 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 return status;
6313}
6314
Eric Laurenta011e352012-03-29 15:51:43 -07006315void AudioFlinger::RecordThread::clearSyncStartEvent()
6316{
6317 if (mSyncStartEvent != 0) {
6318 mSyncStartEvent->cancel();
6319 }
6320 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006321 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006322}
6323
6324void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6325{
6326 sp<SyncEvent> strongEvent = event.promote();
6327
6328 if (strongEvent != 0) {
6329 RecordThread *me = (RecordThread *)strongEvent->cookie();
6330 me->handleSyncStartEvent(strongEvent);
6331 }
6332}
6333
6334void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6335{
Eric Laurent29864602012-05-08 18:57:51 -07006336 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006337 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6338 // from audio HAL
6339 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006340 }
6341}
6342
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006344 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006345 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006347 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6349 mActiveTrack->mState = TrackBase::PAUSING;
6350 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006351 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 return;
6353 }
6354 mStartStopCond.wait(mLock);
6355 // if we have been restarted, recordTrack == mActiveTrack.get() here
6356 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6357 mLock.unlock();
6358 AudioSystem::stopInput(mId);
6359 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006360 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 }
6362 }
6363 }
6364}
6365
Eric Laurenta011e352012-03-29 15:51:43 -07006366bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6367{
6368 return false;
6369}
6370
6371status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6372{
6373 if (!isValidSyncEvent(event)) {
6374 return BAD_VALUE;
6375 }
6376
6377 Mutex::Autolock _l(mLock);
6378
6379 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6380 mTrack->setSyncEvent(event);
6381 return NO_ERROR;
6382 }
6383 return NAME_NOT_FOUND;
6384}
6385
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6387{
6388 const size_t SIZE = 256;
6389 char buffer[SIZE];
6390 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391
6392 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6393 result.append(buffer);
6394
6395 if (mActiveTrack != 0) {
6396 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006397 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 mActiveTrack->dump(buffer, SIZE);
6399 result.append(buffer);
6400
6401 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6402 result.append(buffer);
6403 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6404 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006405 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 result.append(buffer);
6407 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6408 result.append(buffer);
6409 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6410 result.append(buffer);
6411
6412
6413 } else {
6414 result.append("No record client\n");
6415 }
6416 write(fd, result.string(), result.size());
6417
6418 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006419 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420
6421 return NO_ERROR;
6422}
6423
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006424// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006425status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426{
6427 size_t framesReq = buffer->frameCount;
6428 size_t framesReady = mFrameCount - mRsmpInIndex;
6429 int channelCount;
6430
6431 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006432 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006434 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6436 // Force input into standby so that it tries to
6437 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006438 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006439 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006441 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 buffer->frameCount = 0;
6443 return NOT_ENOUGH_DATA;
6444 }
6445 mRsmpInIndex = 0;
6446 framesReady = mFrameCount;
6447 }
6448
6449 if (framesReq > framesReady) {
6450 framesReq = framesReady;
6451 }
6452
6453 if (mChannelCount == 1 && mReqChannelCount == 2) {
6454 channelCount = 1;
6455 } else {
6456 channelCount = 2;
6457 }
6458 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6459 buffer->frameCount = framesReq;
6460 return NO_ERROR;
6461}
6462
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006463// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6465{
6466 mRsmpInIndex += buffer->frameCount;
6467 buffer->frameCount = 0;
6468}
6469
6470bool AudioFlinger::RecordThread::checkForNewParameters_l()
6471{
6472 bool reconfig = false;
6473
6474 while (!mNewParameters.isEmpty()) {
6475 status_t status = NO_ERROR;
6476 String8 keyValuePair = mNewParameters[0];
6477 AudioParameter param = AudioParameter(keyValuePair);
6478 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006479 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480 int reqSamplingRate = mReqSampleRate;
6481 int reqChannelCount = mReqChannelCount;
6482
6483 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6484 reqSamplingRate = value;
6485 reconfig = true;
6486 }
6487 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006488 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 reconfig = true;
6490 }
6491 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006492 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493 reconfig = true;
6494 }
6495 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6496 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006497 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498 // if frame count is changed after track creation
6499 if (mActiveTrack != 0) {
6500 status = INVALID_OPERATION;
6501 } else {
6502 reconfig = true;
6503 }
6504 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006505 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6506 // forward device change to effects that have requested to be
6507 // aware of attached audio device.
6508 for (size_t i = 0; i < mEffectChains.size(); i++) {
6509 mEffectChains[i]->setDevice_l(value);
6510 }
6511 // store input device and output device but do not forward output device to audio HAL.
6512 // Note that status is ignored by the caller for output device
6513 // (see AudioFlinger::setParameters()
6514 if (value & AUDIO_DEVICE_OUT_ALL) {
6515 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6516 status = BAD_VALUE;
6517 } else {
6518 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006519 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6520 if (mTrack != NULL) {
6521 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006522 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006523 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6524 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6525 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006526 }
6527 mDevice |= (uint32_t)value;
6528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006530 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006532 mInput->stream->common.standby(&mInput->stream->common);
6533 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6534 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 }
6536 if (reconfig) {
6537 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006538 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006539 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006540 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006541 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6542 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 status = NO_ERROR;
6544 }
6545 if (status == NO_ERROR) {
6546 readInputParameters();
6547 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6548 }
6549 }
6550 }
6551
6552 mNewParameters.removeAt(0);
6553
6554 mParamStatus = status;
6555 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006556 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6557 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006558 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 }
6560 return reconfig;
6561}
6562
6563String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6564{
Dima Zavinfce7a472011-04-19 22:30:36 -07006565 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006566 String8 out_s8 = String8();
6567
6568 Mutex::Autolock _l(mLock);
6569 if (initCheck() != NO_ERROR) {
6570 return out_s8;
6571 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006572
Dima Zavin799a70e2011-04-18 16:57:27 -07006573 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006574 out_s8 = String8(s);
6575 free(s);
6576 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577}
6578
6579void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6580 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006581 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582
6583 switch (event) {
6584 case AudioSystem::INPUT_OPENED:
6585 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006586 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 desc.samplingRate = mSampleRate;
6588 desc.format = mFormat;
6589 desc.frameCount = mFrameCount;
6590 desc.latency = 0;
6591 param2 = &desc;
6592 break;
6593
6594 case AudioSystem::INPUT_CLOSED:
6595 default:
6596 break;
6597 }
6598 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6599}
6600
6601void AudioFlinger::RecordThread::readInputParameters()
6602{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006603 delete mRsmpInBuffer;
6604 // mRsmpInBuffer is always assigned a new[] below
6605 delete mRsmpOutBuffer;
6606 mRsmpOutBuffer = NULL;
6607 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006608 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609
Dima Zavin799a70e2011-04-18 16:57:27 -07006610 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006611 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6612 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006613 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006614 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006615 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006617 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6619
Glenn Kasten53d76db2012-03-08 12:32:47 -08006620 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006621 {
6622 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006623 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6624 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625 if (mChannelCount == 1 && mReqChannelCount == 2) {
6626 channelCount = 1;
6627 } else {
6628 channelCount = 2;
6629 }
6630 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6631 mResampler->setSampleRate(mSampleRate);
6632 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6633 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6634
6635 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6636 if (mChannelCount == 1 && mReqChannelCount == 1) {
6637 mFrameCount >>= 1;
6638 }
6639
6640 }
6641 mRsmpInIndex = mFrameCount;
6642}
6643
6644unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6645{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006646 Mutex::Autolock _l(mLock);
6647 if (initCheck() != NO_ERROR) {
6648 return 0;
6649 }
6650
Dima Zavin799a70e2011-04-18 16:57:27 -07006651 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652}
6653
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006654uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6655{
6656 Mutex::Autolock _l(mLock);
6657 uint32_t result = 0;
6658 if (getEffectChain_l(sessionId) != 0) {
6659 result = EFFECT_SESSION;
6660 }
6661
6662 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6663 result |= TRACK_SESSION;
6664 }
6665
6666 return result;
6667}
6668
Eric Laurent59bd0da2011-08-01 09:52:20 -07006669AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6670{
6671 Mutex::Autolock _l(mLock);
6672 return mTrack;
6673}
6674
Glenn Kastenaed850d2012-01-26 09:46:34 -08006675AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006676{
6677 Mutex::Autolock _l(mLock);
6678 return mInput;
6679}
6680
6681AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6682{
6683 Mutex::Autolock _l(mLock);
6684 AudioStreamIn *input = mInput;
6685 mInput = NULL;
6686 return input;
6687}
6688
6689// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006690audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006691{
6692 if (mInput == NULL) {
6693 return NULL;
6694 }
6695 return &mInput->stream->common;
6696}
6697
6698
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699// ----------------------------------------------------------------------------
6700
Eric Laurenta4c5a552012-03-29 10:12:40 -07006701audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6702{
6703 if (!settingsAllowed()) {
6704 return 0;
6705 }
6706 Mutex::Autolock _l(mLock);
6707 return loadHwModule_l(name);
6708}
6709
6710// loadHwModule_l() must be called with AudioFlinger::mLock held
6711audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6712{
6713 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6714 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6715 ALOGW("loadHwModule() module %s already loaded", name);
6716 return mAudioHwDevs.keyAt(i);
6717 }
6718 }
6719
Eric Laurenta4c5a552012-03-29 10:12:40 -07006720 audio_hw_device_t *dev;
6721
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006722 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006723 if (rc) {
6724 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6725 return 0;
6726 }
6727
6728 mHardwareStatus = AUDIO_HW_INIT;
6729 rc = dev->init_check(dev);
6730 mHardwareStatus = AUDIO_HW_IDLE;
6731 if (rc) {
6732 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6733 return 0;
6734 }
6735
6736 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6737 (NULL != dev->set_master_volume)) {
6738 AutoMutex lock(mHardwareLock);
6739 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6740 dev->set_master_volume(dev, mMasterVolume);
6741 mHardwareStatus = AUDIO_HW_IDLE;
6742 }
6743
6744 audio_module_handle_t handle = nextUniqueId();
6745 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6746
6747 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006748 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006749
6750 return handle;
6751
6752}
6753
6754audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6755 audio_devices_t *pDevices,
6756 uint32_t *pSamplingRate,
6757 audio_format_t *pFormat,
6758 audio_channel_mask_t *pChannelMask,
6759 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006760 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761{
6762 status_t status;
6763 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006764 struct audio_config config = {
6765 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6766 channel_mask: pChannelMask ? *pChannelMask : 0,
6767 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6768 };
6769 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006770 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771
Eric Laurenta4c5a552012-03-29 10:12:40 -07006772 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6773 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006774 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006775 config.sample_rate,
6776 config.format,
6777 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006778 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779
6780 if (pDevices == NULL || *pDevices == 0) {
6781 return 0;
6782 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006783
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784 Mutex::Autolock _l(mLock);
6785
Eric Laurenta4c5a552012-03-29 10:12:40 -07006786 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006787 if (outHwDev == NULL)
6788 return 0;
6789
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006790 audio_io_handle_t id = nextUniqueId();
6791
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006792 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006793
6794 status = outHwDev->open_output_stream(outHwDev,
6795 id,
6796 *pDevices,
6797 (audio_output_flags_t)flags,
6798 &config,
6799 &outStream);
6800
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006801 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006802 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006803 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006804 config.sample_rate,
6805 config.format,
6806 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006807 status);
6808
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006809 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006810 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006811
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006812 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006813 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6814 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006816 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 } else {
6818 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006819 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820 }
6821 mPlaybackThreads.add(id, thread);
6822
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006823 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6824 if (pFormat != NULL) *pFormat = config.format;
6825 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006826 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827
6828 // notify client processes of the new output creation
6829 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006830
6831 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006832 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006833 ALOGI("Using module %d has the primary audio interface", module);
6834 mPrimaryHardwareDev = outHwDev;
6835
6836 AutoMutex lock(mHardwareLock);
6837 mHardwareStatus = AUDIO_HW_SET_MODE;
6838 outHwDev->set_mode(outHwDev, mMode);
6839
6840 // Determine the level of master volume support the primary audio HAL has,
6841 // and set the initial master volume at the same time.
6842 float initialVolume = 1.0;
6843 mMasterVolumeSupportLvl = MVS_NONE;
6844
6845 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6846 if ((NULL != outHwDev->get_master_volume) &&
6847 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6848 mMasterVolumeSupportLvl = MVS_FULL;
6849 } else {
6850 mMasterVolumeSupportLvl = MVS_SETONLY;
6851 initialVolume = 1.0;
6852 }
6853
6854 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6855 if ((NULL == outHwDev->set_master_volume) ||
6856 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6857 mMasterVolumeSupportLvl = MVS_NONE;
6858 }
6859 // now that we have a primary device, initialize master volume on other devices
6860 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6861 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6862
6863 if ((dev != mPrimaryHardwareDev) &&
6864 (NULL != dev->set_master_volume)) {
6865 dev->set_master_volume(dev, initialVolume);
6866 }
6867 }
6868 mHardwareStatus = AUDIO_HW_IDLE;
6869 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6870 ? initialVolume
6871 : 1.0;
6872 mMasterVolume = initialVolume;
6873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874 return id;
6875 }
6876
6877 return 0;
6878}
6879
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006880audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6881 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882{
6883 Mutex::Autolock _l(mLock);
6884 MixerThread *thread1 = checkMixerThread_l(output1);
6885 MixerThread *thread2 = checkMixerThread_l(output2);
6886
6887 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006888 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 return 0;
6890 }
6891
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006892 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6894 thread->addOutputTrack(thread2);
6895 mPlaybackThreads.add(id, thread);
6896 // notify client processes of the new output creation
6897 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6898 return id;
6899}
6900
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006901status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902{
6903 // keep strong reference on the playback thread so that
6904 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006905 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 {
6907 Mutex::Autolock _l(mLock);
6908 thread = checkPlaybackThread_l(output);
6909 if (thread == NULL) {
6910 return BAD_VALUE;
6911 }
6912
Steve Block3856b092011-10-20 11:56:00 +01006913 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006915 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006917 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6919 dupThread->removeOutputTrack((MixerThread *)thread.get());
6920 }
6921 }
6922 }
Glenn Kastena1117922012-01-26 10:53:32 -08006923 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924 mPlaybackThreads.removeItem(output);
6925 }
6926 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006927 // The thread entity (active unit of execution) is no longer running here,
6928 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006931 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006932 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006933 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006934 out->hwDev->close_output_stream(out->hwDev, out->stream);
6935 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 }
6937 return NO_ERROR;
6938}
6939
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006940status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941{
6942 Mutex::Autolock _l(mLock);
6943 PlaybackThread *thread = checkPlaybackThread_l(output);
6944
6945 if (thread == NULL) {
6946 return BAD_VALUE;
6947 }
6948
Steve Block3856b092011-10-20 11:56:00 +01006949 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 thread->suspend();
6951
6952 return NO_ERROR;
6953}
6954
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006955status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956{
6957 Mutex::Autolock _l(mLock);
6958 PlaybackThread *thread = checkPlaybackThread_l(output);
6959
6960 if (thread == NULL) {
6961 return BAD_VALUE;
6962 }
6963
Steve Block3856b092011-10-20 11:56:00 +01006964 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965
6966 thread->restore();
6967
6968 return NO_ERROR;
6969}
6970
Eric Laurenta4c5a552012-03-29 10:12:40 -07006971audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6972 audio_devices_t *pDevices,
6973 uint32_t *pSamplingRate,
6974 audio_format_t *pFormat,
6975 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976{
6977 status_t status;
6978 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006979 struct audio_config config = {
6980 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6981 channel_mask: pChannelMask ? *pChannelMask : 0,
6982 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6983 };
6984 uint32_t reqSamplingRate = config.sample_rate;
6985 audio_format_t reqFormat = config.format;
6986 audio_channel_mask_t reqChannels = config.channel_mask;
6987 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006988 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989
6990 if (pDevices == NULL || *pDevices == 0) {
6991 return 0;
6992 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006993
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 Mutex::Autolock _l(mLock);
6995
Eric Laurenta4c5a552012-03-29 10:12:40 -07006996 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006997 if (inHwDev == NULL)
6998 return 0;
6999
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007000 audio_io_handle_t id = nextUniqueId();
7001
7002 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007003 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007004 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007005 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007006 config.sample_rate,
7007 config.format,
7008 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 status);
7010
7011 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7012 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7013 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007014 if (status == BAD_VALUE &&
7015 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7016 (config.sample_rate <= 2 * reqSamplingRate) &&
7017 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01007018 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007019 inStream = NULL;
7020 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 }
7022
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007023 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007024 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7025
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007026 // Start record thread
7027 // RecorThread require both input and output device indication to forward to audio
7028 // pre processing modules
7029 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7030 thread = new RecordThread(this,
7031 input,
7032 reqSamplingRate,
7033 reqChannels,
7034 id,
7035 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007037 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007038 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007039 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007040 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041
Dima Zavin799a70e2011-04-18 16:57:27 -07007042 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
7044 // notify client processes of the new input creation
7045 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7046 return id;
7047 }
7048
7049 return 0;
7050}
7051
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007052status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053{
7054 // keep strong reference on the record thread so that
7055 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007056 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 {
7058 Mutex::Autolock _l(mLock);
7059 thread = checkRecordThread_l(input);
7060 if (thread == NULL) {
7061 return BAD_VALUE;
7062 }
7063
Steve Block3856b092011-10-20 11:56:00 +01007064 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007065 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066 mRecordThreads.removeItem(input);
7067 }
7068 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007069 // The thread entity (active unit of execution) is no longer running here,
7070 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007072 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007073 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007074 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007075 in->hwDev->close_input_stream(in->hwDev, in->stream);
7076 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077
7078 return NO_ERROR;
7079}
7080
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007081status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007082{
7083 Mutex::Autolock _l(mLock);
7084 MixerThread *dstThread = checkMixerThread_l(output);
7085 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007086 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087 return BAD_VALUE;
7088 }
7089
Steve Block3856b092011-10-20 11:56:00 +01007090 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007091 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7092
7093 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7094 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08007095 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007096 MixerThread *srcThread = (MixerThread *)thread;
7097 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 }
Eric Laurentde070132010-07-13 04:45:46 -07007099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100
7101 return NO_ERROR;
7102}
7103
7104
7105int AudioFlinger::newAudioSessionId()
7106{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007107 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108}
7109
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007110void AudioFlinger::acquireAudioSessionId(int audioSession)
7111{
7112 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007113 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007114 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007115 size_t num = mAudioSessionRefs.size();
7116 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007117 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007118 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7119 ref->mCnt++;
7120 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007121 return;
7122 }
7123 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007124 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7125 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007126}
7127
7128void AudioFlinger::releaseAudioSessionId(int audioSession)
7129{
7130 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007131 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007132 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007133 size_t num = mAudioSessionRefs.size();
7134 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007135 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007136 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7137 ref->mCnt--;
7138 ALOGV(" decremented refcount to %d", ref->mCnt);
7139 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007140 mAudioSessionRefs.removeAt(i);
7141 delete ref;
7142 purgeStaleEffects_l();
7143 }
7144 return;
7145 }
7146 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007147 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007148}
7149
7150void AudioFlinger::purgeStaleEffects_l() {
7151
Steve Block3856b092011-10-20 11:56:00 +01007152 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007153
7154 Vector< sp<EffectChain> > chains;
7155
7156 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7157 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7158 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7159 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007160 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7161 chains.push(ec);
7162 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007163 }
7164 }
7165 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7166 sp<RecordThread> t = mRecordThreads.valueAt(i);
7167 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7168 sp<EffectChain> ec = t->mEffectChains[j];
7169 chains.push(ec);
7170 }
7171 }
7172
7173 for (size_t i = 0; i < chains.size(); i++) {
7174 sp<EffectChain> ec = chains[i];
7175 int sessionid = ec->sessionId();
7176 sp<ThreadBase> t = ec->mThread.promote();
7177 if (t == 0) {
7178 continue;
7179 }
7180 size_t numsessionrefs = mAudioSessionRefs.size();
7181 bool found = false;
7182 for (size_t k = 0; k < numsessionrefs; k++) {
7183 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007184 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007185 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007186 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007187 found = true;
7188 break;
7189 }
7190 }
7191 if (!found) {
7192 // remove all effects from the chain
7193 while (ec->mEffects.size()) {
7194 sp<EffectModule> effect = ec->mEffects[0];
7195 effect->unPin();
7196 Mutex::Autolock _l (t->mLock);
7197 t->removeEffect_l(effect);
7198 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7199 sp<EffectHandle> handle = effect->mHandles[j].promote();
7200 if (handle != 0) {
7201 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007202 if (handle->mHasControl && handle->mEnabled) {
7203 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7204 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007205 }
7206 }
7207 AudioSystem::unregisterEffect(effect->id());
7208 }
7209 }
7210 }
7211 return;
7212}
7213
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007215AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216{
Glenn Kastena1117922012-01-26 10:53:32 -08007217 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218}
7219
7220// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007221AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222{
7223 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007224 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007225}
7226
7227// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007228AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007229{
Glenn Kastena1117922012-01-26 10:53:32 -08007230 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231}
7232
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007233uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007234{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007235 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236}
7237
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007238AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007239{
7240 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7241 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007242 AudioStreamOut *output = thread->getOutput();
7243 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007244 return thread;
7245 }
7246 }
7247 return NULL;
7248}
7249
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007250uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007251{
7252 PlaybackThread *thread = primaryPlaybackThread_l();
7253
7254 if (thread == NULL) {
7255 return 0;
7256 }
7257
7258 return thread->device();
7259}
7260
Eric Laurenta011e352012-03-29 15:51:43 -07007261sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7262 int triggerSession,
7263 int listenerSession,
7264 sync_event_callback_t callBack,
7265 void *cookie)
7266{
7267 Mutex::Autolock _l(mLock);
7268
7269 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7270 status_t playStatus = NAME_NOT_FOUND;
7271 status_t recStatus = NAME_NOT_FOUND;
7272 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7273 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7274 if (playStatus == NO_ERROR) {
7275 return event;
7276 }
7277 }
7278 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7279 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7280 if (recStatus == NO_ERROR) {
7281 return event;
7282 }
7283 }
7284 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7285 mPendingSyncEvents.add(event);
7286 } else {
7287 ALOGV("createSyncEvent() invalid event %d", event->type());
7288 event.clear();
7289 }
7290 return event;
7291}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007292
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293// ----------------------------------------------------------------------------
7294// Effect management
7295// ----------------------------------------------------------------------------
7296
7297
Glenn Kastenf587ba52012-01-26 16:25:10 -08007298status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299{
7300 Mutex::Autolock _l(mLock);
7301 return EffectQueryNumberEffects(numEffects);
7302}
7303
Glenn Kastenf587ba52012-01-26 16:25:10 -08007304status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305{
7306 Mutex::Autolock _l(mLock);
7307 return EffectQueryEffect(index, descriptor);
7308}
7309
Glenn Kasten5e92a782012-01-30 07:40:52 -08007310status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007311 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312{
7313 Mutex::Autolock _l(mLock);
7314 return EffectGetDescriptor(pUuid, descriptor);
7315}
7316
7317
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7319 effect_descriptor_t *pDesc,
7320 const sp<IEffectClient>& effectClient,
7321 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007322 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323 int sessionId,
7324 status_t *status,
7325 int *id,
7326 int *enabled)
7327{
7328 status_t lStatus = NO_ERROR;
7329 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007332 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007333 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334
7335 if (pDesc == NULL) {
7336 lStatus = BAD_VALUE;
7337 goto Exit;
7338 }
7339
Eric Laurent84e9a102010-09-23 16:10:16 -07007340 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007341 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007342 lStatus = PERMISSION_DENIED;
7343 goto Exit;
7344 }
7345
Dima Zavinfce7a472011-04-19 22:30:36 -07007346 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007347 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007348 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007349 lStatus = PERMISSION_DENIED;
7350 goto Exit;
7351 }
7352
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007353 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007354 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007355 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007356 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007357 lStatus = BAD_VALUE;
7358 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007359 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007360 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007361 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007362 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007363 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007364 }
7365 }
7366
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 {
7368 Mutex::Autolock _l(mLock);
7369
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370
7371 if (!EffectIsNullUuid(&pDesc->uuid)) {
7372 // if uuid is specified, request effect descriptor
7373 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7374 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007375 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 goto Exit;
7377 }
7378 } else {
7379 // if uuid is not specified, look for an available implementation
7380 // of the required type in effect factory
7381 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007382 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 lStatus = BAD_VALUE;
7384 goto Exit;
7385 }
7386 uint32_t numEffects = 0;
7387 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007388 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 bool found = false;
7390
7391 lStatus = EffectQueryNumberEffects(&numEffects);
7392 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007393 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394 goto Exit;
7395 }
7396 for (uint32_t i = 0; i < numEffects; i++) {
7397 lStatus = EffectQueryEffect(i, &desc);
7398 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007399 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 continue;
7401 }
7402 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7403 // If matching type found save effect descriptor. If the session is
7404 // 0 and the effect is not auxiliary, continue enumeration in case
7405 // an auxiliary version of this effect type is available
7406 found = true;
7407 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007408 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7410 break;
7411 }
7412 }
7413 }
7414 if (!found) {
7415 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007416 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 goto Exit;
7418 }
7419 // For same effect type, chose auxiliary version over insert version if
7420 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007421 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7423 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7424 }
7425 }
7426
7427 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007428 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7430 lStatus = INVALID_OPERATION;
7431 goto Exit;
7432 }
7433
Eric Laurent59255e42011-07-27 19:49:51 -07007434 // check recording permission for visualizer
7435 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7436 !recordingAllowed()) {
7437 lStatus = PERMISSION_DENIED;
7438 goto Exit;
7439 }
7440
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441 // return effect descriptor
7442 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7443
7444 // If output is not specified try to find a matching audio session ID in one of the
7445 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007446 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7447 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007448 // Note: io is never 0 when creating an effect on an input
7449 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007450 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007451 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7452 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007453 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007454 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007455 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007456 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007457 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007458 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7459 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7460 io = mRecordThreads.keyAt(i);
7461 break;
7462 }
7463 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007464 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007465 // If no output thread contains the requested session ID, default to
7466 // first output. The effect chain will be moved to the correct output
7467 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007468 if (io == 0 && mPlaybackThreads.size()) {
7469 io = mPlaybackThreads.keyAt(0);
7470 }
Steve Block3856b092011-10-20 11:56:00 +01007471 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007472 }
7473 ThreadBase *thread = checkRecordThread_l(io);
7474 if (thread == NULL) {
7475 thread = checkPlaybackThread_l(io);
7476 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007477 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007478 lStatus = BAD_VALUE;
7479 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007482
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007483 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007485 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007486 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7487 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 if (handle != 0 && id != NULL) {
7489 *id = handle->id();
7490 }
7491 }
7492
7493Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007494 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 *status = lStatus;
7496 }
7497 return handle;
7498}
7499
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007500status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7501 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007502{
Steve Block3856b092011-10-20 11:56:00 +01007503 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007504 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007505 Mutex::Autolock _l(mLock);
7506 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007507 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007508 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509 }
Eric Laurentde070132010-07-13 04:45:46 -07007510 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7511 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007512 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007513 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514 }
Eric Laurentde070132010-07-13 04:45:46 -07007515 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7516 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007517 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007518 return BAD_VALUE;
7519 }
7520
7521 Mutex::Autolock _dl(dstThread->mLock);
7522 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007523 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007524
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525 return NO_ERROR;
7526}
7527
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007528// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007529status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007530 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007531 AudioFlinger::PlaybackThread *dstThread,
7532 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007533{
Steve Block3856b092011-10-20 11:56:00 +01007534 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007535 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007536
Eric Laurent59255e42011-07-27 19:49:51 -07007537 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007538 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007539 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007540 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007541 return INVALID_OPERATION;
7542 }
7543
Eric Laurent39e94f82010-07-28 01:32:47 -07007544 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007545 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007546 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007547 // removed.
7548 srcThread->removeEffectChain_l(chain);
7549
7550 // transfer all effects one by one so that new effect chain is created on new thread with
7551 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007552 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007553 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007554 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007555 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7556 while (effect != 0) {
7557 srcThread->removeEffect_l(effect);
7558 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007559 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7560 if (effect->state() == EffectModule::ACTIVE ||
7561 effect->state() == EffectModule::STOPPING) {
7562 effect->start();
7563 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007564 // if the move request is not received from audio policy manager, the effect must be
7565 // re-registered with the new strategy and output
7566 if (dstChain == 0) {
7567 dstChain = effect->chain().promote();
7568 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007569 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007570 srcThread->addEffect_l(effect);
7571 return NO_INIT;
7572 }
7573 strategy = dstChain->strategy();
7574 }
7575 if (reRegister) {
7576 AudioSystem::unregisterEffect(effect->id());
7577 AudioSystem::registerEffect(&effect->desc(),
7578 dstOutput,
7579 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007580 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007581 effect->id());
7582 }
Eric Laurentde070132010-07-13 04:45:46 -07007583 effect = chain->getEffectFromId_l(0);
7584 }
7585
7586 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587}
7588
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007589
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007591sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 const sp<AudioFlinger::Client>& client,
7593 const sp<IEffectClient>& effectClient,
7594 int32_t priority,
7595 int sessionId,
7596 effect_descriptor_t *desc,
7597 int *enabled,
7598 status_t *status
7599 )
7600{
7601 sp<EffectModule> effect;
7602 sp<EffectHandle> handle;
7603 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007605 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 bool effectCreated = false;
7607 bool effectRegistered = false;
7608
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007609 lStatus = initCheck();
7610 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007611 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612 goto Exit;
7613 }
7614
7615 // Do not allow effects with session ID 0 on direct output or duplicating threads
7616 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007617 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007618 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007619 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 lStatus = BAD_VALUE;
7621 goto Exit;
7622 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007623 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007624 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007625 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007626 desc->name, desc->flags, mType);
7627 lStatus = BAD_VALUE;
7628 goto Exit;
7629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630
Steve Block3856b092011-10-20 11:56:00 +01007631 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632
7633 { // scope for mLock
7634 Mutex::Autolock _l(mLock);
7635
7636 // check for existing effect chain with the requested audio session
7637 chain = getEffectChain_l(sessionId);
7638 if (chain == 0) {
7639 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007640 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 chain = new EffectChain(this, sessionId);
7642 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007643 chain->setStrategy(getStrategyForSession_l(sessionId));
7644 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007646 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647 }
7648
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007649 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007650
7651 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007654 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007655 if (lStatus != NO_ERROR) {
7656 goto Exit;
7657 }
7658 effectRegistered = true;
7659 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007660 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661 lStatus = effect->status();
7662 if (lStatus != NO_ERROR) {
7663 goto Exit;
7664 }
Eric Laurentcab11242010-07-15 12:50:15 -07007665 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007666 if (lStatus != NO_ERROR) {
7667 goto Exit;
7668 }
7669 effectCreated = true;
7670
7671 effect->setDevice(mDevice);
7672 effect->setMode(mAudioFlinger->getMode());
7673 }
7674 // create effect handle and connect it to effect module
7675 handle = new EffectHandle(effect, client, effectClient, priority);
7676 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007677 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 *enabled = (int)effect->isEnabled();
7679 }
7680 }
7681
7682Exit:
7683 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007684 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007686 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 }
7688 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007689 AudioSystem::unregisterEffect(effect->id());
7690 }
7691 if (chainCreated) {
7692 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007693 }
7694 handle.clear();
7695 }
7696
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007697 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 *status = lStatus;
7699 }
7700 return handle;
7701}
7702
Eric Laurent717e1282012-06-29 16:36:52 -07007703sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7704{
7705 Mutex::Autolock _l(mLock);
7706 return getEffect_l(sessionId, effectId);
7707}
7708
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007709sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7710{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007711 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007712 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007713}
7714
Eric Laurentde070132010-07-13 04:45:46 -07007715// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7716// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007717status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007718{
7719 // check for existing effect chain with the requested audio session
7720 int sessionId = effect->sessionId();
7721 sp<EffectChain> chain = getEffectChain_l(sessionId);
7722 bool chainCreated = false;
7723
7724 if (chain == 0) {
7725 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007727 chain = new EffectChain(this, sessionId);
7728 addEffectChain_l(chain);
7729 chain->setStrategy(getStrategyForSession_l(sessionId));
7730 chainCreated = true;
7731 }
Steve Block3856b092011-10-20 11:56:00 +01007732 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007733
7734 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007735 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007736 this, effect->desc().name, chain.get());
7737 return BAD_VALUE;
7738 }
7739
7740 status_t status = chain->addEffect_l(effect);
7741 if (status != NO_ERROR) {
7742 if (chainCreated) {
7743 removeEffectChain_l(chain);
7744 }
7745 return status;
7746 }
7747
7748 effect->setDevice(mDevice);
7749 effect->setMode(mAudioFlinger->getMode());
7750 return NO_ERROR;
7751}
7752
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007753void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007754
Steve Block3856b092011-10-20 11:56:00 +01007755 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007757 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7758 detachAuxEffect_l(effect->id());
7759 }
7760
7761 sp<EffectChain> chain = effect->chain().promote();
7762 if (chain != 0) {
7763 // remove effect chain if removing last effect
7764 if (chain->removeEffect_l(effect) == 0) {
7765 removeEffectChain_l(chain);
7766 }
7767 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007768 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007769 }
7770}
7771
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007772void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007773 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007774{
7775 effectChains = mEffectChains;
7776 for (size_t i = 0; i < mEffectChains.size(); i++) {
7777 mEffectChains[i]->lock();
7778 }
7779}
7780
7781void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007782 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007783{
7784 for (size_t i = 0; i < effectChains.size(); i++) {
7785 effectChains[i]->unlock();
7786 }
7787}
7788
7789sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7790{
7791 Mutex::Autolock _l(mLock);
7792 return getEffectChain_l(sessionId);
7793}
7794
7795sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7796{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007797 size_t size = mEffectChains.size();
7798 for (size_t i = 0; i < size; i++) {
7799 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007800 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007801 }
7802 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007803 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007804}
7805
Glenn Kastenf78aee72012-01-04 11:00:47 -08007806void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007807{
7808 Mutex::Autolock _l(mLock);
7809 size_t size = mEffectChains.size();
7810 for (size_t i = 0; i < size; i++) {
7811 mEffectChains[i]->setMode_l(mode);
7812 }
7813}
7814
7815void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007816 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007817 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007818
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007820 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007821 // delete the effect module if removing last handle on it
7822 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007823 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007824 removeEffect_l(effect);
7825 AudioSystem::unregisterEffect(effect->id());
7826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007827 }
7828}
7829
7830status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7831{
7832 int session = chain->sessionId();
7833 int16_t *buffer = mMixBuffer;
7834 bool ownsBuffer = false;
7835
Steve Block3856b092011-10-20 11:56:00 +01007836 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837 if (session > 0) {
7838 // Only one effect chain can be present in direct output thread and it uses
7839 // the mix buffer as input
7840 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007841 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842 buffer = new int16_t[numSamples];
7843 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007844 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 ownsBuffer = true;
7846 }
7847
7848 // Attach all tracks with same session ID to this chain.
7849 for (size_t i = 0; i < mTracks.size(); ++i) {
7850 sp<Track> track = mTracks[i];
7851 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007852 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007854 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855 }
7856 }
7857
7858 // indicate all active tracks in the chain
7859 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7860 sp<Track> track = mActiveTracks[i].promote();
7861 if (track == 0) continue;
7862 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007863 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007864 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 }
7866 }
7867 }
7868
7869 chain->setInBuffer(buffer, ownsBuffer);
7870 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007871 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007872 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007873 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7874 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007876 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7877 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007878 // Effect chain for other sessions are inserted at beginning of effect
7879 // chains list to be processed before output mix effects. Relative order between other
7880 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 size_t size = mEffectChains.size();
7882 size_t i = 0;
7883 for (i = 0; i < size; i++) {
7884 if (mEffectChains[i]->sessionId() < session) break;
7885 }
7886 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007887 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007888
7889 return NO_ERROR;
7890}
7891
7892size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7893{
7894 int session = chain->sessionId();
7895
Steve Block3856b092011-10-20 11:56:00 +01007896 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897
7898 for (size_t i = 0; i < mEffectChains.size(); i++) {
7899 if (chain == mEffectChains[i]) {
7900 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007901 // detach all active tracks from the chain
7902 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7903 sp<Track> track = mActiveTracks[i].promote();
7904 if (track == 0) continue;
7905 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007906 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007907 chain.get(), session);
7908 chain->decActiveTrackCnt();
7909 }
7910 }
7911
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912 // detach all tracks with same session ID from this chain
7913 for (size_t i = 0; i < mTracks.size(); ++i) {
7914 sp<Track> track = mTracks[i];
7915 if (session == track->sessionId()) {
7916 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007917 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 }
7919 }
Eric Laurentde070132010-07-13 04:45:46 -07007920 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921 }
7922 }
7923 return mEffectChains.size();
7924}
7925
Eric Laurentde070132010-07-13 04:45:46 -07007926status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7927 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007928{
7929 Mutex::Autolock _l(mLock);
7930 return attachAuxEffect_l(track, EffectId);
7931}
7932
Eric Laurentde070132010-07-13 04:45:46 -07007933status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7934 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935{
7936 status_t status = NO_ERROR;
7937
7938 if (EffectId == 0) {
7939 track->setAuxBuffer(0, NULL);
7940 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007941 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7942 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943 if (effect != 0) {
7944 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7945 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7946 } else {
7947 status = INVALID_OPERATION;
7948 }
7949 } else {
7950 status = BAD_VALUE;
7951 }
7952 }
7953 return status;
7954}
7955
7956void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7957{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007958 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 sp<Track> track = mTracks[i];
7960 if (track->auxEffectId() == effectId) {
7961 attachAuxEffect_l(track, 0);
7962 }
7963 }
7964}
7965
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007966status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7967{
7968 // only one chain per input thread
7969 if (mEffectChains.size() != 0) {
7970 return INVALID_OPERATION;
7971 }
Steve Block3856b092011-10-20 11:56:00 +01007972 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007973
7974 chain->setInBuffer(NULL);
7975 chain->setOutBuffer(NULL);
7976
Eric Laurent59255e42011-07-27 19:49:51 -07007977 checkSuspendOnAddEffectChain_l(chain);
7978
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007979 mEffectChains.add(chain);
7980
7981 return NO_ERROR;
7982}
7983
7984size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7985{
Steve Block3856b092011-10-20 11:56:00 +01007986 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007987 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007988 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7989 chain.get(), mEffectChains.size(), this);
7990 if (mEffectChains.size() == 1) {
7991 mEffectChains.removeAt(0);
7992 }
7993 return 0;
7994}
7995
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996// ----------------------------------------------------------------------------
7997// EffectModule implementation
7998// ----------------------------------------------------------------------------
7999
8000#undef LOG_TAG
8001#define LOG_TAG "AudioFlinger::EffectModule"
8002
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008003AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008004 const wp<AudioFlinger::EffectChain>& chain,
8005 effect_descriptor_t *desc,
8006 int id,
8007 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008008 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008009 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008010{
Steve Block3856b092011-10-20 11:56:00 +01008011 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008013 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014 return;
8015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016
8017 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
8018
8019 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008020 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021
8022 if (mStatus != NO_ERROR) {
8023 return;
8024 }
8025 lStatus = init();
8026 if (lStatus < 0) {
8027 mStatus = lStatus;
8028 goto Error;
8029 }
8030
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008031 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
8032 mPinned = true;
8033 }
Steve Block3856b092011-10-20 11:56:00 +01008034 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 return;
8036Error:
8037 EffectRelease(mEffectInterface);
8038 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008039 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040}
8041
8042AudioFlinger::EffectModule::~EffectModule()
8043{
Steve Block3856b092011-10-20 11:56:00 +01008044 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008046 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8047 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8048 sp<ThreadBase> thread = mThread.promote();
8049 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008050 audio_stream_t *stream = thread->stream();
8051 if (stream != NULL) {
8052 stream->remove_audio_effect(stream, mEffectInterface);
8053 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008054 }
8055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 // release effect engine
8057 EffectRelease(mEffectInterface);
8058 }
8059}
8060
Glenn Kasten435dbe62012-01-30 10:15:48 -08008061status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062{
8063 status_t status;
8064
8065 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 int priority = handle->priority();
8067 size_t size = mHandles.size();
8068 sp<EffectHandle> h;
8069 size_t i;
8070 for (i = 0; i < size; i++) {
8071 h = mHandles[i].promote();
8072 if (h == 0) continue;
8073 if (h->priority() <= priority) break;
8074 }
8075 // if inserted in first place, move effect control from previous owner to this handle
8076 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008077 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008079 enabled = h->enabled();
8080 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008081 }
Eric Laurent59255e42011-07-27 19:49:51 -07008082 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083 status = NO_ERROR;
8084 } else {
8085 status = ALREADY_EXISTS;
8086 }
Steve Block3856b092011-10-20 11:56:00 +01008087 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008088 mHandles.insertAt(handle, i);
8089 return status;
8090}
8091
8092size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8093{
8094 Mutex::Autolock _l(mLock);
8095 size_t size = mHandles.size();
8096 size_t i;
8097 for (i = 0; i < size; i++) {
8098 if (mHandles[i] == handle) break;
8099 }
8100 if (i == size) {
8101 return size;
8102 }
Steve Block3856b092011-10-20 11:56:00 +01008103 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008104
8105 bool enabled = false;
8106 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008107 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008108 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008109 enabled = hdl->enabled();
8110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111 mHandles.removeAt(i);
8112 size = mHandles.size();
8113 // if removed from first place, move effect control from this handle to next in line
8114 if (i == 0 && size != 0) {
8115 sp<EffectHandle> h = mHandles[0].promote();
8116 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008117 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 }
8119 }
8120
Eric Laurentec437d82011-07-26 20:54:46 -07008121 // Prevent calls to process() and other functions on effect interface from now on.
8122 // The effect engine will be released by the destructor when the last strong reference on
8123 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008124 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008125 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008126 }
8127
Mathias Agopian65ab4712010-07-14 17:59:35 -07008128 return size;
8129}
8130
Eric Laurent59255e42011-07-27 19:49:51 -07008131sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8132{
8133 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008134 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008135}
8136
Glenn Kasten58123c32012-02-03 10:32:24 -08008137void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008139 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 // keep a strong reference on this EffectModule to avoid calling the
8141 // destructor before we exit
8142 sp<EffectModule> keep(this);
8143 {
8144 sp<ThreadBase> thread = mThread.promote();
8145 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008146 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008147 }
8148 }
8149}
8150
8151void AudioFlinger::EffectModule::updateState() {
8152 Mutex::Autolock _l(mLock);
8153
8154 switch (mState) {
8155 case RESTART:
8156 reset_l();
8157 // FALL THROUGH
8158
8159 case STARTING:
8160 // clear auxiliary effect input buffer for next accumulation
8161 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8162 memset(mConfig.inputCfg.buffer.raw,
8163 0,
8164 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8165 }
8166 start_l();
8167 mState = ACTIVE;
8168 break;
8169 case STOPPING:
8170 stop_l();
8171 mDisableWaitCnt = mMaxDisableWaitCnt;
8172 mState = STOPPED;
8173 break;
8174 case STOPPED:
8175 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8176 // turn off sequence.
8177 if (--mDisableWaitCnt == 0) {
8178 reset_l();
8179 mState = IDLE;
8180 }
8181 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008182 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 break;
8184 }
8185}
8186
8187void AudioFlinger::EffectModule::process()
8188{
8189 Mutex::Autolock _l(mLock);
8190
Eric Laurentec437d82011-07-26 20:54:46 -07008191 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008192 mConfig.inputCfg.buffer.raw == NULL ||
8193 mConfig.outputCfg.buffer.raw == NULL) {
8194 return;
8195 }
8196
Eric Laurent8f45bd72010-08-31 13:50:07 -07008197 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008198 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8199 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008200 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008201 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008202 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 }
8204
8205 // do the actual processing in the effect engine
8206 int ret = (*mEffectInterface)->process(mEffectInterface,
8207 &mConfig.inputCfg.buffer,
8208 &mConfig.outputCfg.buffer);
8209
8210 // force transition to IDLE state when engine is ready
8211 if (mState == STOPPED && ret == -ENODATA) {
8212 mDisableWaitCnt = 1;
8213 }
8214
8215 // clear auxiliary effect input buffer for next accumulation
8216 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008217 memset(mConfig.inputCfg.buffer.raw, 0,
8218 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 }
8220 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008221 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8222 // If an insert effect is idle and input buffer is different from output buffer,
8223 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008224 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008225 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008226 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8227 int16_t *in = mConfig.inputCfg.buffer.s16;
8228 int16_t *out = mConfig.outputCfg.buffer.s16;
8229 for (size_t i = 0; i < frameCnt; i++) {
8230 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008231 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008232 }
8233 }
8234}
8235
8236void AudioFlinger::EffectModule::reset_l()
8237{
8238 if (mEffectInterface == NULL) {
8239 return;
8240 }
8241 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8242}
8243
8244status_t AudioFlinger::EffectModule::configure()
8245{
8246 uint32_t channels;
8247 if (mEffectInterface == NULL) {
8248 return NO_INIT;
8249 }
8250
8251 sp<ThreadBase> thread = mThread.promote();
8252 if (thread == 0) {
8253 return DEAD_OBJECT;
8254 }
8255
8256 // TODO: handle configuration of effects replacing track process
8257 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008258 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008260 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008261 }
8262
8263 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008264 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008265 } else {
8266 mConfig.inputCfg.channels = channels;
8267 }
8268 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008269 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8270 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 mConfig.inputCfg.samplingRate = thread->sampleRate();
8272 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8273 mConfig.inputCfg.bufferProvider.cookie = NULL;
8274 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8275 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8276 mConfig.outputCfg.bufferProvider.cookie = NULL;
8277 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8278 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8279 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8280 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008281 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008282 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008283 // - in other sessions:
8284 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8285 // other effect: overwrites output buffer: input buffer == output buffer
8286 // Auxiliary effect:
8287 // accumulates in output buffer: input buffer != output buffer
8288 // Therefore: accumulate <=> input buffer != output buffer
8289 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8290 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8291 } else {
8292 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8293 }
8294 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8295 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8296 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8297 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8298
Steve Block3856b092011-10-20 11:56:00 +01008299 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008300 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8301
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008303 uint32_t size = sizeof(int);
8304 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008305 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008306 sizeof(effect_config_t),
8307 &mConfig,
8308 &size,
8309 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310 if (status == 0) {
8311 status = cmdStatus;
8312 }
8313
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008314 if (status == 0 &&
8315 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8316 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8317 effect_param_t *p = (effect_param_t *)buf32;
8318
8319 p->psize = sizeof(uint32_t);
8320 p->vsize = sizeof(uint32_t);
8321 size = sizeof(int);
8322 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8323
8324 uint32_t latency = 0;
8325 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8326 if (pbt != NULL) {
8327 latency = pbt->latency_l();
8328 }
8329
8330 *((int32_t *)p->data + 1)= latency;
8331 (*mEffectInterface)->command(mEffectInterface,
8332 EFFECT_CMD_SET_PARAM,
8333 sizeof(effect_param_t) + 8,
8334 &buf32,
8335 &size,
8336 &cmdStatus);
8337 }
8338
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8340 (1000 * mConfig.outputCfg.buffer.frameCount);
8341
8342 return status;
8343}
8344
8345status_t AudioFlinger::EffectModule::init()
8346{
8347 Mutex::Autolock _l(mLock);
8348 if (mEffectInterface == NULL) {
8349 return NO_INIT;
8350 }
8351 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008352 uint32_t size = sizeof(status_t);
8353 status_t status = (*mEffectInterface)->command(mEffectInterface,
8354 EFFECT_CMD_INIT,
8355 0,
8356 NULL,
8357 &size,
8358 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 if (status == 0) {
8360 status = cmdStatus;
8361 }
8362 return status;
8363}
8364
Eric Laurentec35a142011-10-05 17:42:25 -07008365status_t AudioFlinger::EffectModule::start()
8366{
8367 Mutex::Autolock _l(mLock);
8368 return start_l();
8369}
8370
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371status_t AudioFlinger::EffectModule::start_l()
8372{
8373 if (mEffectInterface == NULL) {
8374 return NO_INIT;
8375 }
8376 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008377 uint32_t size = sizeof(status_t);
8378 status_t status = (*mEffectInterface)->command(mEffectInterface,
8379 EFFECT_CMD_ENABLE,
8380 0,
8381 NULL,
8382 &size,
8383 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384 if (status == 0) {
8385 status = cmdStatus;
8386 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008387 if (status == 0 &&
8388 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8389 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8390 sp<ThreadBase> thread = mThread.promote();
8391 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008392 audio_stream_t *stream = thread->stream();
8393 if (stream != NULL) {
8394 stream->add_audio_effect(stream, mEffectInterface);
8395 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008396 }
8397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008398 return status;
8399}
8400
Eric Laurentec437d82011-07-26 20:54:46 -07008401status_t AudioFlinger::EffectModule::stop()
8402{
8403 Mutex::Autolock _l(mLock);
8404 return stop_l();
8405}
8406
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407status_t AudioFlinger::EffectModule::stop_l()
8408{
8409 if (mEffectInterface == NULL) {
8410 return NO_INIT;
8411 }
8412 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008413 uint32_t size = sizeof(status_t);
8414 status_t status = (*mEffectInterface)->command(mEffectInterface,
8415 EFFECT_CMD_DISABLE,
8416 0,
8417 NULL,
8418 &size,
8419 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420 if (status == 0) {
8421 status = cmdStatus;
8422 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008423 if (status == 0 &&
8424 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8425 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8426 sp<ThreadBase> thread = mThread.promote();
8427 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008428 audio_stream_t *stream = thread->stream();
8429 if (stream != NULL) {
8430 stream->remove_audio_effect(stream, mEffectInterface);
8431 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008432 }
8433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008434 return status;
8435}
8436
Eric Laurent25f43952010-07-28 05:40:18 -07008437status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8438 uint32_t cmdSize,
8439 void *pCmdData,
8440 uint32_t *replySize,
8441 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008442{
8443 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008444// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445
Eric Laurentec437d82011-07-26 20:54:46 -07008446 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008447 return NO_INIT;
8448 }
Eric Laurent25f43952010-07-28 05:40:18 -07008449 status_t status = (*mEffectInterface)->command(mEffectInterface,
8450 cmdCode,
8451 cmdSize,
8452 pCmdData,
8453 replySize,
8454 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008456 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457 for (size_t i = 1; i < mHandles.size(); i++) {
8458 sp<EffectHandle> h = mHandles[i].promote();
8459 if (h != 0) {
8460 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8461 }
8462 }
8463 }
8464 return status;
8465}
8466
8467status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8468{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008469
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008471 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008472
8473 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008474 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8475 if (enabled && status != NO_ERROR) {
8476 return status;
8477 }
8478
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479 switch (mState) {
8480 // going from disabled to enabled
8481 case IDLE:
8482 mState = STARTING;
8483 break;
8484 case STOPPED:
8485 mState = RESTART;
8486 break;
8487 case STOPPING:
8488 mState = ACTIVE;
8489 break;
8490
8491 // going from enabled to disabled
8492 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008493 mState = STOPPED;
8494 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 case STARTING:
8496 mState = IDLE;
8497 break;
8498 case ACTIVE:
8499 mState = STOPPING;
8500 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008501 case DESTROYED:
8502 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503 }
8504 for (size_t i = 1; i < mHandles.size(); i++) {
8505 sp<EffectHandle> h = mHandles[i].promote();
8506 if (h != 0) {
8507 h->setEnabled(enabled);
8508 }
8509 }
8510 }
8511 return NO_ERROR;
8512}
8513
Glenn Kastenc59c0042012-02-02 14:06:11 -08008514bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008515{
8516 switch (mState) {
8517 case RESTART:
8518 case STARTING:
8519 case ACTIVE:
8520 return true;
8521 case IDLE:
8522 case STOPPING:
8523 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008524 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525 default:
8526 return false;
8527 }
8528}
8529
Glenn Kastenc59c0042012-02-02 14:06:11 -08008530bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008531{
8532 switch (mState) {
8533 case RESTART:
8534 case ACTIVE:
8535 case STOPPING:
8536 case STOPPED:
8537 return true;
8538 case IDLE:
8539 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008540 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008541 default:
8542 return false;
8543 }
8544}
8545
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8547{
8548 Mutex::Autolock _l(mLock);
8549 status_t status = NO_ERROR;
8550
8551 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8552 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008553 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008554 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8555 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556 status_t cmdStatus;
8557 uint32_t volume[2];
8558 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008559 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 volume[0] = *left;
8561 volume[1] = *right;
8562 if (controller) {
8563 pVolume = volume;
8564 }
Eric Laurent25f43952010-07-28 05:40:18 -07008565 status = (*mEffectInterface)->command(mEffectInterface,
8566 EFFECT_CMD_SET_VOLUME,
8567 size,
8568 volume,
8569 &size,
8570 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8572 *left = volume[0];
8573 *right = volume[1];
8574 }
8575 }
8576 return status;
8577}
8578
8579status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8580{
8581 Mutex::Autolock _l(mLock);
8582 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008583 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8584 // audio pre processing modules on RecordThread can receive both output and
8585 // input device indication in the same call
8586 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8587 if (dev) {
8588 status_t cmdStatus;
8589 uint32_t size = sizeof(status_t);
8590
8591 status = (*mEffectInterface)->command(mEffectInterface,
8592 EFFECT_CMD_SET_DEVICE,
8593 sizeof(uint32_t),
8594 &dev,
8595 &size,
8596 &cmdStatus);
8597 if (status == NO_ERROR) {
8598 status = cmdStatus;
8599 }
8600 }
8601 dev = device & AUDIO_DEVICE_IN_ALL;
8602 if (dev) {
8603 status_t cmdStatus;
8604 uint32_t size = sizeof(status_t);
8605
8606 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8607 EFFECT_CMD_SET_INPUT_DEVICE,
8608 sizeof(uint32_t),
8609 &dev,
8610 &size,
8611 &cmdStatus);
8612 if (status2 == NO_ERROR) {
8613 status2 = cmdStatus;
8614 }
8615 if (status == NO_ERROR) {
8616 status = status2;
8617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 }
8619 }
8620 return status;
8621}
8622
Glenn Kastenf78aee72012-01-04 11:00:47 -08008623status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008624{
8625 Mutex::Autolock _l(mLock);
8626 status_t status = NO_ERROR;
8627 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008628 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008629 uint32_t size = sizeof(status_t);
8630 status = (*mEffectInterface)->command(mEffectInterface,
8631 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008632 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008633 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008634 &size,
8635 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008636 if (status == NO_ERROR) {
8637 status = cmdStatus;
8638 }
8639 }
8640 return status;
8641}
8642
Eric Laurent59255e42011-07-27 19:49:51 -07008643void AudioFlinger::EffectModule::setSuspended(bool suspended)
8644{
8645 Mutex::Autolock _l(mLock);
8646 mSuspended = suspended;
8647}
Glenn Kastena3a85482012-01-04 11:01:11 -08008648
8649bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008650{
8651 Mutex::Autolock _l(mLock);
8652 return mSuspended;
8653}
8654
Mathias Agopian65ab4712010-07-14 17:59:35 -07008655status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8656{
8657 const size_t SIZE = 256;
8658 char buffer[SIZE];
8659 String8 result;
8660
8661 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8662 result.append(buffer);
8663
8664 bool locked = tryLock(mLock);
8665 // failed to lock - AudioFlinger is probably deadlocked
8666 if (!locked) {
8667 result.append("\t\tCould not lock Fx mutex:\n");
8668 }
8669
8670 result.append("\t\tSession Status State Engine:\n");
8671 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8672 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8673 result.append(buffer);
8674
8675 result.append("\t\tDescriptor:\n");
8676 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8677 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8678 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8679 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8680 result.append(buffer);
8681 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8682 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8683 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8684 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8685 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008686 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008687 mDescriptor.apiVersion,
8688 mDescriptor.flags);
8689 result.append(buffer);
8690 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8691 mDescriptor.name);
8692 result.append(buffer);
8693 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8694 mDescriptor.implementor);
8695 result.append(buffer);
8696
8697 result.append("\t\t- Input configuration:\n");
8698 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8699 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8700 (uint32_t)mConfig.inputCfg.buffer.raw,
8701 mConfig.inputCfg.buffer.frameCount,
8702 mConfig.inputCfg.samplingRate,
8703 mConfig.inputCfg.channels,
8704 mConfig.inputCfg.format);
8705 result.append(buffer);
8706
8707 result.append("\t\t- Output configuration:\n");
8708 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8709 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8710 (uint32_t)mConfig.outputCfg.buffer.raw,
8711 mConfig.outputCfg.buffer.frameCount,
8712 mConfig.outputCfg.samplingRate,
8713 mConfig.outputCfg.channels,
8714 mConfig.outputCfg.format);
8715 result.append(buffer);
8716
8717 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8718 result.append(buffer);
8719 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8720 for (size_t i = 0; i < mHandles.size(); ++i) {
8721 sp<EffectHandle> handle = mHandles[i].promote();
8722 if (handle != 0) {
8723 handle->dump(buffer, SIZE);
8724 result.append(buffer);
8725 }
8726 }
8727
8728 result.append("\n");
8729
8730 write(fd, result.string(), result.length());
8731
8732 if (locked) {
8733 mLock.unlock();
8734 }
8735
8736 return NO_ERROR;
8737}
8738
8739// ----------------------------------------------------------------------------
8740// EffectHandle implementation
8741// ----------------------------------------------------------------------------
8742
8743#undef LOG_TAG
8744#define LOG_TAG "AudioFlinger::EffectHandle"
8745
8746AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8747 const sp<AudioFlinger::Client>& client,
8748 const sp<IEffectClient>& effectClient,
8749 int32_t priority)
8750 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008751 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008752 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008753{
Steve Block3856b092011-10-20 11:56:00 +01008754 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008756 if (client == 0) {
8757 return;
8758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8760 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8761 if (mCblkMemory != 0) {
8762 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8763
Glenn Kastena0d68332012-01-27 16:47:15 -08008764 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 new(mCblk) effect_param_cblk_t();
8766 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008769 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770 return;
8771 }
8772}
8773
8774AudioFlinger::EffectHandle::~EffectHandle()
8775{
Steve Block3856b092011-10-20 11:56:00 +01008776 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008777 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008778 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008779}
8780
8781status_t AudioFlinger::EffectHandle::enable()
8782{
Steve Block3856b092011-10-20 11:56:00 +01008783 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008784 if (!mHasControl) return INVALID_OPERATION;
8785 if (mEffect == 0) return DEAD_OBJECT;
8786
Eric Laurentdb7c0792011-08-10 10:37:50 -07008787 if (mEnabled) {
8788 return NO_ERROR;
8789 }
8790
Eric Laurent59255e42011-07-27 19:49:51 -07008791 mEnabled = true;
8792
8793 sp<ThreadBase> thread = mEffect->thread().promote();
8794 if (thread != 0) {
8795 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8796 }
8797
8798 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8799 if (mEffect->suspended()) {
8800 return NO_ERROR;
8801 }
8802
Eric Laurentdb7c0792011-08-10 10:37:50 -07008803 status_t status = mEffect->setEnabled(true);
8804 if (status != NO_ERROR) {
8805 if (thread != 0) {
8806 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8807 }
8808 mEnabled = false;
8809 }
8810 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811}
8812
8813status_t AudioFlinger::EffectHandle::disable()
8814{
Steve Block3856b092011-10-20 11:56:00 +01008815 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008817 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818
Eric Laurentdb7c0792011-08-10 10:37:50 -07008819 if (!mEnabled) {
8820 return NO_ERROR;
8821 }
Eric Laurent59255e42011-07-27 19:49:51 -07008822 mEnabled = false;
8823
8824 if (mEffect->suspended()) {
8825 return NO_ERROR;
8826 }
8827
8828 status_t status = mEffect->setEnabled(false);
8829
8830 sp<ThreadBase> thread = mEffect->thread().promote();
8831 if (thread != 0) {
8832 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8833 }
8834
8835 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836}
8837
8838void AudioFlinger::EffectHandle::disconnect()
8839{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008840 disconnect(true);
8841}
8842
Glenn Kasten58123c32012-02-03 10:32:24 -08008843void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008844{
Glenn Kasten58123c32012-02-03 10:32:24 -08008845 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 if (mEffect == 0) {
8847 return;
8848 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008849 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008850
Eric Laurenta85a74a2011-10-19 11:44:54 -07008851 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008852 sp<ThreadBase> thread = mEffect->thread().promote();
8853 if (thread != 0) {
8854 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8855 }
Eric Laurent59255e42011-07-27 19:49:51 -07008856 }
8857
Mathias Agopian65ab4712010-07-14 17:59:35 -07008858 // release sp on module => module destructor can be called now
8859 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008861 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008862 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008863 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8864 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008865 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008866 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8868 mClient.clear();
8869 }
8870}
8871
Eric Laurent25f43952010-07-28 05:40:18 -07008872status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8873 uint32_t cmdSize,
8874 void *pCmdData,
8875 uint32_t *replySize,
8876 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877{
Steve Block3856b092011-10-20 11:56:00 +01008878// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008879// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008880
8881 // only get parameter command is permitted for applications not controlling the effect
8882 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8883 return INVALID_OPERATION;
8884 }
8885 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008886 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887
8888 // handle commands that are not forwarded transparently to effect engine
8889 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8890 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8891 // no risk to block the whole media server process or mixer threads is we are stuck here
8892 Mutex::Autolock _l(mCblk->lock);
8893 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8894 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8895 mCblk->serverIndex = 0;
8896 mCblk->clientIndex = 0;
8897 return BAD_VALUE;
8898 }
8899 status_t status = NO_ERROR;
8900 while (mCblk->serverIndex < mCblk->clientIndex) {
8901 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008902 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 int *p = (int *)(mBuffer + mCblk->serverIndex);
8904 int size = *p++;
8905 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008906 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008907 break;
8908 }
8909 effect_param_t *param = (effect_param_t *)p;
8910 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008911 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912 mCblk->serverIndex += size;
8913 continue;
8914 }
Eric Laurent25f43952010-07-28 05:40:18 -07008915 uint32_t psize = sizeof(effect_param_t) +
8916 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8917 param->vsize;
8918 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8919 psize,
8920 p,
8921 &rsize,
8922 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008923 // stop at first error encountered
8924 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008925 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008926 *(int *)pReplyData = reply;
8927 break;
8928 } else if (reply != NO_ERROR) {
8929 *(int *)pReplyData = reply;
8930 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008931 }
8932 mCblk->serverIndex += size;
8933 }
8934 mCblk->serverIndex = 0;
8935 mCblk->clientIndex = 0;
8936 return status;
8937 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008938 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939 return enable();
8940 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008941 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008942 return disable();
8943 }
8944
8945 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8946}
8947
Eric Laurent59255e42011-07-27 19:49:51 -07008948void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949{
Steve Block3856b092011-10-20 11:56:00 +01008950 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951
8952 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008953 mEnabled = enabled;
8954
Mathias Agopian65ab4712010-07-14 17:59:35 -07008955 if (signal && mEffectClient != 0) {
8956 mEffectClient->controlStatusChanged(hasControl);
8957 }
8958}
8959
Eric Laurent25f43952010-07-28 05:40:18 -07008960void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8961 uint32_t cmdSize,
8962 void *pCmdData,
8963 uint32_t replySize,
8964 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008965{
8966 if (mEffectClient != 0) {
8967 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8968 }
8969}
8970
8971
8972
8973void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8974{
8975 if (mEffectClient != 0) {
8976 mEffectClient->enableStatusChanged(enabled);
8977 }
8978}
8979
8980status_t AudioFlinger::EffectHandle::onTransact(
8981 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8982{
8983 return BnEffect::onTransact(code, data, reply, flags);
8984}
8985
8986
8987void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8988{
Glenn Kastena0d68332012-01-27 16:47:15 -08008989 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008990
8991 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008992 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993 mPriority,
8994 mHasControl,
8995 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008996 mCblk ? mCblk->clientIndex : 0,
8997 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008998 );
8999
9000 if (locked) {
9001 mCblk->lock.unlock();
9002 }
9003}
9004
9005#undef LOG_TAG
9006#define LOG_TAG "AudioFlinger::EffectChain"
9007
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009008AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009009 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009010 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009011 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9012 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013{
Dima Zavinfce7a472011-04-19 22:30:36 -07009014 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009015 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009016 return;
9017 }
9018 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9019 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009020}
9021
9022AudioFlinger::EffectChain::~EffectChain()
9023{
9024 if (mOwnInBuffer) {
9025 delete mInBuffer;
9026 }
9027
9028}
9029
Eric Laurent59255e42011-07-27 19:49:51 -07009030// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009031sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009033 size_t size = mEffects.size();
9034
9035 for (size_t i = 0; i < size; i++) {
9036 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009037 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038 }
9039 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009040 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009041}
9042
Eric Laurent59255e42011-07-27 19:49:51 -07009043// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009044sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009045{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009046 size_t size = mEffects.size();
9047
9048 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009049 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9050 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009051 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009052 }
9053 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009054 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055}
9056
Eric Laurent59255e42011-07-27 19:49:51 -07009057// getEffectFromType_l() must be called with ThreadBase::mLock held
9058sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9059 const effect_uuid_t *type)
9060{
Eric Laurent59255e42011-07-27 19:49:51 -07009061 size_t size = mEffects.size();
9062
9063 for (size_t i = 0; i < size; i++) {
9064 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009065 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009066 }
9067 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009068 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009069}
9070
Eric Laurent91b14c42012-05-30 12:30:29 -07009071void AudioFlinger::EffectChain::clearInputBuffer()
9072{
9073 Mutex::Autolock _l(mLock);
9074 sp<ThreadBase> thread = mThread.promote();
9075 if (thread == 0) {
9076 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9077 return;
9078 }
9079 clearInputBuffer_l(thread);
9080}
9081
9082// Must be called with EffectChain::mLock locked
9083void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9084{
9085 size_t numSamples = thread->frameCount() * thread->channelCount();
9086 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9087
9088}
9089
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090// Must be called with EffectChain::mLock locked
9091void AudioFlinger::EffectChain::process_l()
9092{
Eric Laurentdac69112010-09-28 14:09:57 -07009093 sp<ThreadBase> thread = mThread.promote();
9094 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009095 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009096 return;
9097 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009098 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9099 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009100 // always process effects unless no more tracks are on the session and the effect tail
9101 // has been rendered
9102 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009103 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009104 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009105
Eric Laurent544fe9b2011-11-11 15:42:52 -08009106 if (!tracksOnSession && mTailBufferCount == 0) {
9107 doProcess = false;
9108 }
9109
9110 if (activeTrackCnt() == 0) {
9111 // if no track is active and the effect tail has not been rendered,
9112 // the input buffer must be cleared here as the mixer process will not do it
9113 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009114 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009115 if (mTailBufferCount > 0) {
9116 mTailBufferCount--;
9117 }
9118 }
9119 }
Eric Laurentdac69112010-09-28 14:09:57 -07009120 }
9121
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009123 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009124 for (size_t i = 0; i < size; i++) {
9125 mEffects[i]->process();
9126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127 }
9128 for (size_t i = 0; i < size; i++) {
9129 mEffects[i]->updateState();
9130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009131}
9132
Eric Laurentcab11242010-07-15 12:50:15 -07009133// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009134status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009135{
9136 effect_descriptor_t desc = effect->desc();
9137 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9138
9139 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009140 effect->setChain(this);
9141 sp<ThreadBase> thread = mThread.promote();
9142 if (thread == 0) {
9143 return NO_INIT;
9144 }
9145 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146
9147 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9148 // Auxiliary effects are inserted at the beginning of mEffects vector as
9149 // they are processed first and accumulated in chain input buffer
9150 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009151
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152 // the input buffer for auxiliary effect contains mono samples in
9153 // 32 bit format. This is to avoid saturation in AudoMixer
9154 // accumulation stage. Saturation is done in EffectModule::process() before
9155 // calling the process in effect engine
9156 size_t numSamples = thread->frameCount();
9157 int32_t *buffer = new int32_t[numSamples];
9158 memset(buffer, 0, numSamples * sizeof(int32_t));
9159 effect->setInBuffer((int16_t *)buffer);
9160 // auxiliary effects output samples to chain input buffer for further processing
9161 // by insert effects
9162 effect->setOutBuffer(mInBuffer);
9163 } else {
9164 // Insert effects are inserted at the end of mEffects vector as they are processed
9165 // after track and auxiliary effects.
9166 // Insert effect order as a function of indicated preference:
9167 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9168 // another effect is present
9169 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9170 // last effect claiming first position
9171 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9172 // first effect claiming last position
9173 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9174 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9175 // already present
9176
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009177 size_t size = mEffects.size();
9178 size_t idx_insert = size;
9179 ssize_t idx_insert_first = -1;
9180 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009182 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009183 effect_descriptor_t d = mEffects[i]->desc();
9184 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9185 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9186 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9187 // check invalid effect chaining combinations
9188 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9189 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009190 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009191 return INVALID_OPERATION;
9192 }
9193 // remember position of first insert effect and by default
9194 // select this as insert position for new effect
9195 if (idx_insert == size) {
9196 idx_insert = i;
9197 }
9198 // remember position of last insert effect claiming
9199 // first position
9200 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9201 idx_insert_first = i;
9202 }
9203 // remember position of first insert effect claiming
9204 // last position
9205 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9206 idx_insert_last == -1) {
9207 idx_insert_last = i;
9208 }
9209 }
9210 }
9211
9212 // modify idx_insert from first position if needed
9213 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9214 if (idx_insert_last != -1) {
9215 idx_insert = idx_insert_last;
9216 } else {
9217 idx_insert = size;
9218 }
9219 } else {
9220 if (idx_insert_first != -1) {
9221 idx_insert = idx_insert_first + 1;
9222 }
9223 }
9224
9225 // always read samples from chain input buffer
9226 effect->setInBuffer(mInBuffer);
9227
9228 // if last effect in the chain, output samples to chain
9229 // output buffer, otherwise to chain input buffer
9230 if (idx_insert == size) {
9231 if (idx_insert != 0) {
9232 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9233 mEffects[idx_insert-1]->configure();
9234 }
9235 effect->setOutBuffer(mOutBuffer);
9236 } else {
9237 effect->setOutBuffer(mInBuffer);
9238 }
9239 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009240
Steve Block3856b092011-10-20 11:56:00 +01009241 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242 }
9243 effect->configure();
9244 return NO_ERROR;
9245}
9246
Eric Laurentcab11242010-07-15 12:50:15 -07009247// removeEffect_l() must be called with PlaybackThread::mLock held
9248size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009249{
9250 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009251 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9253
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009254 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009256 // calling stop here will remove pre-processing effect from the audio HAL.
9257 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9258 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009259 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9260 mEffects[i]->state() == EffectModule::STOPPING) {
9261 mEffects[i]->stop();
9262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009263 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9264 delete[] effect->inBuffer();
9265 } else {
9266 if (i == size - 1 && i != 0) {
9267 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9268 mEffects[i - 1]->configure();
9269 }
9270 }
9271 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009272 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273 break;
9274 }
9275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009276
9277 return mEffects.size();
9278}
9279
Eric Laurentcab11242010-07-15 12:50:15 -07009280// setDevice_l() must be called with PlaybackThread::mLock held
9281void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282{
9283 size_t size = mEffects.size();
9284 for (size_t i = 0; i < size; i++) {
9285 mEffects[i]->setDevice(device);
9286 }
9287}
9288
Eric Laurentcab11242010-07-15 12:50:15 -07009289// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009290void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009291{
9292 size_t size = mEffects.size();
9293 for (size_t i = 0; i < size; i++) {
9294 mEffects[i]->setMode(mode);
9295 }
9296}
9297
Eric Laurentcab11242010-07-15 12:50:15 -07009298// setVolume_l() must be called with PlaybackThread::mLock held
9299bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009300{
9301 uint32_t newLeft = *left;
9302 uint32_t newRight = *right;
9303 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009304 int ctrlIdx = -1;
9305 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009306
Eric Laurentcab11242010-07-15 12:50:15 -07009307 // first update volume controller
9308 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009309 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009310 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9311 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009312 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009313 break;
9314 }
9315 }
9316
9317 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009318 if (hasControl) {
9319 *left = mNewLeftVolume;
9320 *right = mNewRightVolume;
9321 }
9322 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009323 }
9324
9325 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009326 mLeftVolume = newLeft;
9327 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009328
9329 // second get volume update from volume controller
9330 if (ctrlIdx >= 0) {
9331 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009332 mNewLeftVolume = newLeft;
9333 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009334 }
9335 // then indicate volume to all other effects in chain.
9336 // Pass altered volume to effects before volume controller
9337 // and requested volume to effects after controller
9338 uint32_t lVol = newLeft;
9339 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009340
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009342 if ((int)i == ctrlIdx) continue;
9343 // this also works for ctrlIdx == -1 when there is no volume controller
9344 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009345 lVol = *left;
9346 rVol = *right;
9347 }
9348 mEffects[i]->setVolume(&lVol, &rVol, false);
9349 }
9350 *left = newLeft;
9351 *right = newRight;
9352
9353 return hasControl;
9354}
9355
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9357{
9358 const size_t SIZE = 256;
9359 char buffer[SIZE];
9360 String8 result;
9361
9362 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9363 result.append(buffer);
9364
9365 bool locked = tryLock(mLock);
9366 // failed to lock - AudioFlinger is probably deadlocked
9367 if (!locked) {
9368 result.append("\tCould not lock mutex:\n");
9369 }
9370
Eric Laurentcab11242010-07-15 12:50:15 -07009371 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9372 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373 mEffects.size(),
9374 (uint32_t)mInBuffer,
9375 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009376 mActiveTrackCnt);
9377 result.append(buffer);
9378 write(fd, result.string(), result.size());
9379
9380 for (size_t i = 0; i < mEffects.size(); ++i) {
9381 sp<EffectModule> effect = mEffects[i];
9382 if (effect != 0) {
9383 effect->dump(fd, args);
9384 }
9385 }
9386
9387 if (locked) {
9388 mLock.unlock();
9389 }
9390
9391 return NO_ERROR;
9392}
9393
Eric Laurent59255e42011-07-27 19:49:51 -07009394// must be called with ThreadBase::mLock held
9395void AudioFlinger::EffectChain::setEffectSuspended_l(
9396 const effect_uuid_t *type, bool suspend)
9397{
9398 sp<SuspendedEffectDesc> desc;
9399 // use effect type UUID timelow as key as there is no real risk of identical
9400 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009401 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009402 if (suspend) {
9403 if (index >= 0) {
9404 desc = mSuspendedEffects.valueAt(index);
9405 } else {
9406 desc = new SuspendedEffectDesc();
9407 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9408 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009409 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009410 }
9411 if (desc->mRefCount++ == 0) {
9412 sp<EffectModule> effect = getEffectIfEnabled(type);
9413 if (effect != 0) {
9414 desc->mEffect = effect;
9415 effect->setSuspended(true);
9416 effect->setEnabled(false);
9417 }
9418 }
9419 } else {
9420 if (index < 0) {
9421 return;
9422 }
9423 desc = mSuspendedEffects.valueAt(index);
9424 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009425 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009426 desc->mRefCount = 1;
9427 }
9428 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009429 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009430 if (desc->mEffect != 0) {
9431 sp<EffectModule> effect = desc->mEffect.promote();
9432 if (effect != 0) {
9433 effect->setSuspended(false);
9434 sp<EffectHandle> handle = effect->controlHandle();
9435 if (handle != 0) {
9436 effect->setEnabled(handle->enabled());
9437 }
9438 }
9439 desc->mEffect.clear();
9440 }
9441 mSuspendedEffects.removeItemsAt(index);
9442 }
9443 }
9444}
9445
9446// must be called with ThreadBase::mLock held
9447void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9448{
9449 sp<SuspendedEffectDesc> desc;
9450
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009451 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009452 if (suspend) {
9453 if (index >= 0) {
9454 desc = mSuspendedEffects.valueAt(index);
9455 } else {
9456 desc = new SuspendedEffectDesc();
9457 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009458 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009459 }
9460 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009461 Vector< sp<EffectModule> > effects;
9462 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009463 for (size_t i = 0; i < effects.size(); i++) {
9464 setEffectSuspended_l(&effects[i]->desc().type, true);
9465 }
9466 }
9467 } else {
9468 if (index < 0) {
9469 return;
9470 }
9471 desc = mSuspendedEffects.valueAt(index);
9472 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009473 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009474 desc->mRefCount = 1;
9475 }
9476 if (--desc->mRefCount == 0) {
9477 Vector<const effect_uuid_t *> types;
9478 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9479 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9480 continue;
9481 }
9482 types.add(&mSuspendedEffects.valueAt(i)->mType);
9483 }
9484 for (size_t i = 0; i < types.size(); i++) {
9485 setEffectSuspended_l(types[i], false);
9486 }
Steve Block3856b092011-10-20 11:56:00 +01009487 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009488 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9489 }
9490 }
9491}
9492
Eric Laurent6bffdb82011-09-23 08:40:41 -07009493
9494// The volume effect is used for automated tests only
9495#ifndef OPENSL_ES_H_
9496static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9497 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9498const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9499#endif //OPENSL_ES_H_
9500
Eric Laurentdb7c0792011-08-10 10:37:50 -07009501bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9502{
9503 // auxiliary effects and visualizer are never suspended on output mix
9504 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9505 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009506 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9507 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009508 return false;
9509 }
9510 return true;
9511}
9512
Glenn Kastend0539712012-01-30 12:56:03 -08009513void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009514{
Glenn Kastend0539712012-01-30 12:56:03 -08009515 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009516 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009517 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9518 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009519 }
Eric Laurent59255e42011-07-27 19:49:51 -07009520 }
Eric Laurent59255e42011-07-27 19:49:51 -07009521}
9522
9523sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9524 const effect_uuid_t *type)
9525{
Glenn Kasten090f0192012-01-30 13:00:02 -08009526 sp<EffectModule> effect = getEffectFromType_l(type);
9527 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009528}
9529
9530void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9531 bool enabled)
9532{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009533 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009534 if (enabled) {
9535 if (index < 0) {
9536 // if the effect is not suspend check if all effects are suspended
9537 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9538 if (index < 0) {
9539 return;
9540 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009541 if (!isEffectEligibleForSuspend(effect->desc())) {
9542 return;
9543 }
Eric Laurent59255e42011-07-27 19:49:51 -07009544 setEffectSuspended_l(&effect->desc().type, enabled);
9545 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009546 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009547 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009548 return;
9549 }
Eric Laurent59255e42011-07-27 19:49:51 -07009550 }
Steve Block3856b092011-10-20 11:56:00 +01009551 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009552 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009553 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9554 // if effect is requested to suspended but was not yet enabled, supend it now.
9555 if (desc->mEffect == 0) {
9556 desc->mEffect = effect;
9557 effect->setEnabled(false);
9558 effect->setSuspended(true);
9559 }
9560 } else {
9561 if (index < 0) {
9562 return;
9563 }
Steve Block3856b092011-10-20 11:56:00 +01009564 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009565 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009566 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9567 desc->mEffect.clear();
9568 effect->setSuspended(false);
9569 }
9570}
9571
Mathias Agopian65ab4712010-07-14 17:59:35 -07009572#undef LOG_TAG
9573#define LOG_TAG "AudioFlinger"
9574
9575// ----------------------------------------------------------------------------
9576
9577status_t AudioFlinger::onTransact(
9578 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9579{
9580 return BnAudioFlinger::onTransact(code, data, reply, flags);
9581}
9582
Mathias Agopian65ab4712010-07-14 17:59:35 -07009583}; // namespace android