blob: 586a916eedfd98609be7cc5ef35827939da6b868 [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
1109
1110// ----------------------------------------------------------------------------
1111
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001112AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1113 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001115 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001116 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001117 // mChannelMask
1118 mChannelCount(0),
1119 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1120 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001121 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001122 mDevice(device),
1123 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124{
1125}
1126
1127AudioFlinger::ThreadBase::~ThreadBase()
1128{
1129 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001130 // do not lock the mutex in destructor
1131 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001132 if (mPowerManager != 0) {
1133 sp<IBinder> binder = mPowerManager->asBinder();
1134 binder->unlinkToDeath(mDeathRecipient);
1135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136}
1137
1138void AudioFlinger::ThreadBase::exit()
1139{
Steve Block3856b092011-10-20 11:56:00 +01001140 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001142 // This lock prevents the following race in thread (uniprocessor for illustration):
1143 // if (!exitPending()) {
1144 // // context switch from here to exit()
1145 // // exit() calls requestExit(), what exitPending() observes
1146 // // exit() calls signal(), which is dropped since no waiters
1147 // // context switch back from exit() to here
1148 // mWaitWorkCV.wait(...);
1149 // // now thread is hung
1150 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001151 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 requestExit();
1153 mWaitWorkCV.signal();
1154 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001155 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1156 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 requestExitAndWait();
1158}
1159
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1161{
1162 status_t status;
1163
Steve Block3856b092011-10-20 11:56:00 +01001164 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 Mutex::Autolock _l(mLock);
1166
1167 mNewParameters.add(keyValuePairs);
1168 mWaitWorkCV.signal();
1169 // wait condition with timeout in case the thread loop has exited
1170 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001171 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 status = mParamStatus;
1173 mWaitWorkCV.signal();
1174 } else {
1175 status = TIMED_OUT;
1176 }
1177 return status;
1178}
1179
1180void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1181{
1182 Mutex::Autolock _l(mLock);
1183 sendConfigEvent_l(event, param);
1184}
1185
1186// sendConfigEvent_l() must be called with ThreadBase::mLock held
1187void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1188{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001189 ConfigEvent configEvent;
1190 configEvent.mEvent = event;
1191 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001193 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 mWaitWorkCV.signal();
1195}
1196
1197void AudioFlinger::ThreadBase::processConfigEvents()
1198{
1199 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001200 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001201 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001202 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 mConfigEvents.removeAt(0);
1204 // release mLock before locking AudioFlinger mLock: lock order is always
1205 // AudioFlinger then ThreadBase to avoid cross deadlock
1206 mLock.unlock();
1207 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001208 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 mLock.lock();
1211 }
1212 mLock.unlock();
1213}
1214
1215status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1216{
1217 const size_t SIZE = 256;
1218 char buffer[SIZE];
1219 String8 result;
1220
1221 bool locked = tryLock(mLock);
1222 if (!locked) {
1223 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1224 write(fd, buffer, strlen(buffer));
1225 }
1226
Eric Laurent612bbb52012-03-14 15:03:26 -07001227 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1228 result.append(buffer);
1229 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1230 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1232 result.append(buffer);
1233 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1234 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001235 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1236 result.append(buffer);
1237 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238 result.append(buffer);
1239 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1240 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001241 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1242 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1244 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001245 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 result.append(buffer);
1247
1248 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1249 result.append(buffer);
1250 result.append(" Index Command");
1251 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1252 snprintf(buffer, SIZE, "\n %02d ", i);
1253 result.append(buffer);
1254 result.append(mNewParameters[i]);
1255 }
1256
1257 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1258 result.append(buffer);
1259 snprintf(buffer, SIZE, " Index event param\n");
1260 result.append(buffer);
1261 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001262 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 result.append(buffer);
1264 }
1265 result.append("\n");
1266
1267 write(fd, result.string(), result.size());
1268
1269 if (locked) {
1270 mLock.unlock();
1271 }
1272 return NO_ERROR;
1273}
1274
Eric Laurent1d2bff02011-07-24 17:49:51 -07001275status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1276{
1277 const size_t SIZE = 256;
1278 char buffer[SIZE];
1279 String8 result;
1280
1281 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1282 write(fd, buffer, strlen(buffer));
1283
1284 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1285 sp<EffectChain> chain = mEffectChains[i];
1286 if (chain != 0) {
1287 chain->dump(fd, args);
1288 }
1289 }
1290 return NO_ERROR;
1291}
1292
Eric Laurentfeb0db62011-07-22 09:04:31 -07001293void AudioFlinger::ThreadBase::acquireWakeLock()
1294{
1295 Mutex::Autolock _l(mLock);
1296 acquireWakeLock_l();
1297}
1298
1299void AudioFlinger::ThreadBase::acquireWakeLock_l()
1300{
1301 if (mPowerManager == 0) {
1302 // use checkService() to avoid blocking if power service is not up yet
1303 sp<IBinder> binder =
1304 defaultServiceManager()->checkService(String16("power"));
1305 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001306 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001307 } else {
1308 mPowerManager = interface_cast<IPowerManager>(binder);
1309 binder->linkToDeath(mDeathRecipient);
1310 }
1311 }
1312 if (mPowerManager != 0) {
1313 sp<IBinder> binder = new BBinder();
1314 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1315 binder,
1316 String16(mName));
1317 if (status == NO_ERROR) {
1318 mWakeLockToken = binder;
1319 }
Steve Block3856b092011-10-20 11:56:00 +01001320 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001321 }
1322}
1323
1324void AudioFlinger::ThreadBase::releaseWakeLock()
1325{
1326 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001327 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001328}
1329
1330void AudioFlinger::ThreadBase::releaseWakeLock_l()
1331{
1332 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001333 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001334 if (mPowerManager != 0) {
1335 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1336 }
1337 mWakeLockToken.clear();
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::clearPowerManager()
1342{
1343 Mutex::Autolock _l(mLock);
1344 releaseWakeLock_l();
1345 mPowerManager.clear();
1346}
1347
1348void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1349{
1350 sp<ThreadBase> thread = mThread.promote();
1351 if (thread != 0) {
1352 thread->clearPowerManager();
1353 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001354 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001355}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001356
Eric Laurent59255e42011-07-27 19:49:51 -07001357void AudioFlinger::ThreadBase::setEffectSuspended(
1358 const effect_uuid_t *type, bool suspend, int sessionId)
1359{
1360 Mutex::Autolock _l(mLock);
1361 setEffectSuspended_l(type, suspend, sessionId);
1362}
1363
1364void AudioFlinger::ThreadBase::setEffectSuspended_l(
1365 const effect_uuid_t *type, bool suspend, int sessionId)
1366{
Glenn Kasten090f0192012-01-30 13:00:02 -08001367 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001368 if (chain != 0) {
1369 if (type != NULL) {
1370 chain->setEffectSuspended_l(type, suspend);
1371 } else {
1372 chain->setEffectSuspendedAll_l(suspend);
1373 }
1374 }
1375
1376 updateSuspendedSessions_l(type, suspend, sessionId);
1377}
1378
1379void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1380{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001381 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001382 if (index < 0) {
1383 return;
1384 }
1385
1386 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1387 mSuspendedSessions.editValueAt(index);
1388
1389 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001390 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001391 for (int j = 0; j < desc->mRefCount; j++) {
1392 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1393 chain->setEffectSuspendedAll_l(true);
1394 } else {
Steve Block3856b092011-10-20 11:56:00 +01001395 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001396 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001397 chain->setEffectSuspended_l(&desc->mType, true);
1398 }
1399 }
1400 }
1401}
1402
Eric Laurent59255e42011-07-27 19:49:51 -07001403void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1404 bool suspend,
1405 int sessionId)
1406{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001407 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001408
1409 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1410
1411 if (suspend) {
1412 if (index >= 0) {
1413 sessionEffects = mSuspendedSessions.editValueAt(index);
1414 } else {
1415 mSuspendedSessions.add(sessionId, sessionEffects);
1416 }
1417 } else {
1418 if (index < 0) {
1419 return;
1420 }
1421 sessionEffects = mSuspendedSessions.editValueAt(index);
1422 }
1423
1424
1425 int key = EffectChain::kKeyForSuspendAll;
1426 if (type != NULL) {
1427 key = type->timeLow;
1428 }
1429 index = sessionEffects.indexOfKey(key);
1430
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001431 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001432 if (suspend) {
1433 if (index >= 0) {
1434 desc = sessionEffects.valueAt(index);
1435 } else {
1436 desc = new SuspendedSessionDesc();
1437 if (type != NULL) {
1438 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1439 }
1440 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001441 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001442 }
1443 desc->mRefCount++;
1444 } else {
1445 if (index < 0) {
1446 return;
1447 }
1448 desc = sessionEffects.valueAt(index);
1449 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001450 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001451 sessionEffects.removeItemsAt(index);
1452 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001453 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001454 sessionId);
1455 mSuspendedSessions.removeItem(sessionId);
1456 }
1457 }
1458 }
1459 if (!sessionEffects.isEmpty()) {
1460 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1461 }
1462}
1463
1464void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1465 bool enabled,
1466 int sessionId)
1467{
1468 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001469 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1470}
Eric Laurent59255e42011-07-27 19:49:51 -07001471
Eric Laurenta85a74a2011-10-19 11:44:54 -07001472void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1473 bool enabled,
1474 int sessionId)
1475{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001476 if (mType != RECORD) {
1477 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1478 // another session. This gives the priority to well behaved effect control panels
1479 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001480 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1481 // global effects
1482 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001483 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1484 }
1485 }
Eric Laurent59255e42011-07-27 19:49:51 -07001486
1487 sp<EffectChain> chain = getEffectChain_l(sessionId);
1488 if (chain != 0) {
1489 chain->checkSuspendOnEffectEnabled(effect, enabled);
1490 }
1491}
1492
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493// ----------------------------------------------------------------------------
1494
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001495AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1496 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001497 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001498 uint32_t device,
1499 type_t type)
1500 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001501 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1502 // Assumes constructor is called by AudioFlinger with it's mLock held,
1503 // but it would be safer to explicitly pass initial masterMute as parameter
1504 mMasterMute(audioFlinger->masterMute_l()),
1505 // mStreamTypes[] initialized in constructor body
1506 mOutput(output),
1507 // Assumes constructor is called by AudioFlinger with it's mLock held,
1508 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001509 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001510 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001511 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001512 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001513 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001514 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001515 // index 0 is reserved for normal mixer's submix
1516 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517{
Glenn Kasten480b4682012-02-28 12:30:08 -08001518 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001519
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 readOutputParameters();
1521
Glenn Kasten263709e2012-01-06 08:40:01 -08001522 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001523 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1524 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1525 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001526 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1527 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001529 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1530 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531}
1532
1533AudioFlinger::PlaybackThread::~PlaybackThread()
1534{
1535 delete [] mMixBuffer;
1536}
1537
1538status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1539{
1540 dumpInternals(fd, args);
1541 dumpTracks(fd, args);
1542 dumpEffectChains(fd, args);
1543 return NO_ERROR;
1544}
1545
1546status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1547{
1548 const size_t SIZE = 256;
1549 char buffer[SIZE];
1550 String8 result;
1551
Glenn Kasten58912562012-04-03 10:45:00 -07001552 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1553 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1554 const stream_type_t *st = &mStreamTypes[i];
1555 if (i > 0) {
1556 result.appendFormat(", ");
1557 }
1558 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1559 if (st->mute) {
1560 result.append("M");
1561 }
1562 }
1563 result.append("\n");
1564 write(fd, result.string(), result.length());
1565 result.clear();
1566
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1568 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001569 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 for (size_t i = 0; i < mTracks.size(); ++i) {
1571 sp<Track> track = mTracks[i];
1572 if (track != 0) {
1573 track->dump(buffer, SIZE);
1574 result.append(buffer);
1575 }
1576 }
1577
1578 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1579 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001580 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001582 sp<Track> track = mActiveTracks[i].promote();
1583 if (track != 0) {
1584 track->dump(buffer, SIZE);
1585 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 }
1587 }
1588 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001589
1590 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1591 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1592 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1593 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1594
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 return NO_ERROR;
1596}
1597
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1599{
1600 const size_t SIZE = 256;
1601 char buffer[SIZE];
1602 String8 result;
1603
1604 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1605 result.append(buffer);
1606 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1607 result.append(buffer);
1608 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1609 result.append(buffer);
1610 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1611 result.append(buffer);
1612 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1613 result.append(buffer);
1614 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1615 result.append(buffer);
1616 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1617 result.append(buffer);
1618 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001619 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620
1621 dumpBase(fd, args);
1622
1623 return NO_ERROR;
1624}
1625
1626// Thread virtuals
1627status_t AudioFlinger::PlaybackThread::readyToRun()
1628{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001629 status_t status = initCheck();
1630 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001631 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001632 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001633 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001635 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636}
1637
1638void AudioFlinger::PlaybackThread::onFirstRef()
1639{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001640 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641}
1642
1643// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001644sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001646 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001648 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001649 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 int frameCount,
1651 const sp<IMemory>& sharedBuffer,
1652 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001653 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001654 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 status_t *status)
1656{
1657 sp<Track> track;
1658 status_t lStatus;
1659
Glenn Kasten73d22752012-03-19 13:38:30 -07001660 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1661
1662 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001663 if (flags & IAudioFlinger::TRACK_FAST) {
1664 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001665 // not timed
1666 (!isTimed) &&
1667 // either of these use cases:
1668 (
1669 // use case 1: shared buffer with any frame count
1670 (
1671 (sharedBuffer != 0)
1672 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001673 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001674 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001675 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001676 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001677 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001678 )
1679 ) &&
1680 // PCM data
1681 audio_is_linear_pcm(format) &&
1682 // mono or stereo
1683 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1684 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001685#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001686 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001687 (sampleRate == mSampleRate) &&
1688#endif
1689 // normal mixer has an associated fast mixer
1690 hasFastMixer() &&
1691 // there are sufficient fast track slots available
1692 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001693 // FIXME test that MixerThread for this fast track has a capable output HAL
1694 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001695 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001696 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1697 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001698 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001700 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001701 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001702 } else {
1703 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001704 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1705 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1706 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1707 audio_is_linear_pcm(format),
1708 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001709 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 // For compatibility with AudioTrack calculation, buffer depth is forced
1711 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1712 // This is probably too conservative, but legacy application code may depend on it.
1713 // If you change this calculation, also review the start threshold which is related.
1714 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1715 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1716 if (minBufCount < 2) {
1717 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001718 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001719 int minFrameCount = mNormalFrameCount * minBufCount;
1720 if (frameCount < minFrameCount) {
1721 frameCount = minFrameCount;
1722 }
1723 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001724 }
1725
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001727 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1728 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001729 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001730 "for output %p with format %d",
1731 sampleRate, format, channelMask, mOutput, mFormat);
1732 lStatus = BAD_VALUE;
1733 goto Exit;
1734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 }
1736 } else {
1737 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1738 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001739 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 lStatus = BAD_VALUE;
1741 goto Exit;
1742 }
1743 }
1744
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001745 lStatus = initCheck();
1746 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001747 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 goto Exit;
1749 }
1750
1751 { // scope for mLock
1752 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001753
1754 // all tracks in same audio session must share the same routing strategy otherwise
1755 // conflicts will happen when tracks are moved from one output to another by audio policy
1756 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001757 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001758 for (size_t i = 0; i < mTracks.size(); ++i) {
1759 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001760 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001761 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001762 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001763 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001764 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001765 lStatus = BAD_VALUE;
1766 goto Exit;
1767 }
1768 }
1769 }
1770
John Grossman4ff14ba2012-02-08 16:37:41 -08001771 if (!isTimed) {
1772 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001773 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001774 } else {
1775 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1776 channelMask, frameCount, sharedBuffer, sessionId);
1777 }
1778 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 lStatus = NO_MEMORY;
1780 goto Exit;
1781 }
1782 mTracks.add(track);
1783
1784 sp<EffectChain> chain = getEffectChain_l(sessionId);
1785 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001786 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001788 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001789 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 }
1791 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001792
1793#ifdef HAVE_REQUEST_PRIORITY
1794 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1795 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1796 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1797 // so ask activity manager to do this on our behalf
1798 int err = requestPriority(callingPid, tid, 1);
1799 if (err != 0) {
1800 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1801 1, callingPid, tid, err);
1802 }
1803 }
1804#endif
1805
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 lStatus = NO_ERROR;
1807
1808Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001809 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 *status = lStatus;
1811 }
1812 return track;
1813}
1814
Eric Laurente737cda2012-05-22 18:55:44 -07001815uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1816{
1817 if (mFastMixer != NULL) {
1818 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1819 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1820 }
1821 return latency;
1822}
1823
1824uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1825{
1826 return latency;
1827}
1828
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829uint32_t AudioFlinger::PlaybackThread::latency() const
1830{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001831 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001832 return latency_l();
1833}
1834uint32_t AudioFlinger::PlaybackThread::latency_l() const
1835{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001836 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001837 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001838 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 return 0;
1840 }
1841}
1842
Glenn Kasten6637baa2012-01-09 09:40:36 -08001843void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001845 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Glenn Kasten6637baa2012-01-09 09:40:36 -08001849void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001851 Mutex::Autolock _l(mLock);
1852 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853}
1854
Glenn Kasten6637baa2012-01-09 09:40:36 -08001855void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859}
1860
Glenn Kasten6637baa2012-01-09 09:40:36 -08001861void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001863 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865}
1866
Glenn Kastenfff6d712012-01-12 16:38:12 -08001867float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 return mStreamTypes[stream].volume;
1871}
1872
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873// addTrack_l() must be called with ThreadBase::mLock held
1874status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1875{
1876 status_t status = ALREADY_EXISTS;
1877
1878 // set retry count for buffer fill
1879 track->mRetryCount = kMaxTrackStartupRetries;
1880 if (mActiveTracks.indexOf(track) < 0) {
1881 // the track is newly added, make sure it fills up all its
1882 // buffers before playing. This is to ensure the client will
1883 // effectively get the latency it requested.
1884 track->mFillingUpStatus = Track::FS_FILLING;
1885 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001886 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 mActiveTracks.add(track);
1888 if (track->mainBuffer() != mMixBuffer) {
1889 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1890 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001891 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001892 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894 }
1895
1896 status = NO_ERROR;
1897 }
1898
Steve Block3856b092011-10-20 11:56:00 +01001899 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 mWaitWorkCV.broadcast();
1901
1902 return status;
1903}
1904
1905// destroyTrack_l() must be called with ThreadBase::mLock held
1906void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1907{
1908 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001909 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001911 removeTrack_l(track);
1912 }
1913}
1914
1915void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1916{
Eric Laurent29864602012-05-08 18:57:51 -07001917 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001918 mTracks.remove(track);
1919 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001920 // redundant as track is about to be destroyed, for dumpsys only
1921 track->mName = -1;
1922 if (track->isFastTrack()) {
1923 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001924 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001925 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1926 mFastTrackAvailMask |= 1 << index;
1927 // redundant as track is about to be destroyed, for dumpsys only
1928 track->mFastIndex = -1;
1929 }
Eric Laurentb469b942011-05-09 12:09:06 -07001930 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1931 if (chain != 0) {
1932 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 }
1934}
1935
1936String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1937{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001938 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001939 char *s;
1940
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001941 Mutex::Autolock _l(mLock);
1942 if (initCheck() != NO_ERROR) {
1943 return out_s8;
1944 }
1945
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001947 out_s8 = String8(s);
1948 free(s);
1949 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950}
1951
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001952// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1954 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001955 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956
Steve Block3856b092011-10-20 11:56:00 +01001957 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958
1959 switch (event) {
1960 case AudioSystem::OUTPUT_OPENED:
1961 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001962 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 desc.samplingRate = mSampleRate;
1964 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001965 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 desc.latency = latency();
1967 param2 = &desc;
1968 break;
1969
1970 case AudioSystem::STREAM_CONFIG_CHANGED:
1971 param2 = &param;
1972 case AudioSystem::OUTPUT_CLOSED:
1973 default:
1974 break;
1975 }
1976 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1977}
1978
1979void AudioFlinger::PlaybackThread::readOutputParameters()
1980{
Dima Zavin799a70e2011-04-18 16:57:27 -07001981 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001982 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1983 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001985 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001986 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001987 if (mFrameCount & 15) {
1988 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1989 mFrameCount);
1990 }
1991
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001992 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07001993 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001994 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001995 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07001996 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1997 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1998 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1999 maxNormalFrameCount = maxNormalFrameCount & ~15;
2000 if (maxNormalFrameCount < minNormalFrameCount) {
2001 maxNormalFrameCount = minNormalFrameCount;
2002 }
2003 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2004 if (multiplier <= 1.0) {
2005 multiplier = 1.0;
2006 } else if (multiplier <= 2.0) {
2007 if (2 * mFrameCount <= maxNormalFrameCount) {
2008 multiplier = 2.0;
2009 } else {
2010 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2011 }
2012 } else {
2013 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2014 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2015 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2016 // FIXME this rounding up should not be done if no HAL SRC
2017 uint32_t truncMult = (uint32_t) multiplier;
2018 if ((truncMult & 1)) {
2019 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2020 ++truncMult;
2021 }
2022 }
2023 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002024 }
Glenn Kasten58912562012-04-03 10:45:00 -07002025 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002026 mNormalFrameCount = multiplier * mFrameCount;
2027 // round up to nearest 16 frames to satisfy AudioMixer
2028 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002029 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030
Glenn Kastene9dd0172012-01-27 18:08:45 -08002031 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002032 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2033 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Eric Laurentde070132010-07-13 04:45:46 -07002035 // force reconfiguration of effect chains and engines to take new buffer size and audio
2036 // parameters into account
2037 // Note that mLock is not held when readOutputParameters() is called from the constructor
2038 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2039 // matter.
2040 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2041 Vector< sp<EffectChain> > effectChains = mEffectChains;
2042 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002043 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045}
2046
Eric Laurente737cda2012-05-22 18:55:44 -07002047
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2049{
Glenn Kastena0d68332012-01-27 16:47:15 -08002050 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 return BAD_VALUE;
2052 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002053 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002054 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 return INVALID_OPERATION;
2056 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002057 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058
Dima Zavin799a70e2011-04-18 16:57:27 -07002059 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060}
2061
Eric Laurent39e94f82010-07-28 01:32:47 -07002062uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063{
2064 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002065 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002067 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 }
2069
2070 for (size_t i = 0; i < mTracks.size(); ++i) {
2071 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002072 if (sessionId == track->sessionId() &&
2073 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002074 result |= TRACK_SESSION;
2075 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 }
2077 }
2078
Eric Laurent39e94f82010-07-28 01:32:47 -07002079 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080}
2081
Eric Laurentde070132010-07-13 04:45:46 -07002082uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2083{
Dima Zavinfce7a472011-04-19 22:30:36 -07002084 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002085 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002086 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2087 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002088 }
2089 for (size_t i = 0; i < mTracks.size(); i++) {
2090 sp<Track> track = mTracks[i];
2091 if (sessionId == track->sessionId() &&
2092 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002093 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002094 }
2095 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002096 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002097}
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099
Glenn Kastenaed850d2012-01-26 09:46:34 -08002100AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002101{
2102 Mutex::Autolock _l(mLock);
2103 return mOutput;
2104}
2105
2106AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2107{
2108 Mutex::Autolock _l(mLock);
2109 AudioStreamOut *output = mOutput;
2110 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002111 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2112 // must push a NULL and wait for ack
2113 mOutputSink.clear();
2114 mPipeSink.clear();
2115 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002116 return output;
2117}
2118
2119// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002120audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002121{
2122 if (mOutput == NULL) {
2123 return NULL;
2124 }
2125 return &mOutput->stream->common;
2126}
2127
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002128uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002129{
Eric Laurentab9071b2012-06-04 13:45:29 -07002130 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002131}
2132
Eric Laurenta011e352012-03-29 15:51:43 -07002133status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2134{
2135 if (!isValidSyncEvent(event)) {
2136 return BAD_VALUE;
2137 }
2138
2139 Mutex::Autolock _l(mLock);
2140
2141 for (size_t i = 0; i < mTracks.size(); ++i) {
2142 sp<Track> track = mTracks[i];
2143 if (event->triggerSession() == track->sessionId()) {
2144 track->setSyncEvent(event);
2145 return NO_ERROR;
2146 }
2147 }
2148
2149 return NAME_NOT_FOUND;
2150}
2151
2152bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2153{
2154 switch (event->type()) {
2155 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2156 return true;
2157 default:
2158 break;
2159 }
2160 return false;
2161}
2162
Eric Laurent44a957f2012-05-15 15:26:05 -07002163void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2164{
2165 size_t count = tracksToRemove.size();
2166 if (CC_UNLIKELY(count)) {
2167 for (size_t i = 0 ; i < count ; i++) {
2168 const sp<Track>& track = tracksToRemove.itemAt(i);
2169 if ((track->sharedBuffer() != 0) &&
2170 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2171 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2172 }
2173 }
2174 }
2175
2176}
2177
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178// ----------------------------------------------------------------------------
2179
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002180AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002181 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002182 : PlaybackThread(audioFlinger, output, id, device, type),
2183 // mAudioMixer below
2184#ifdef SOAKER
2185 mSoaker(NULL),
2186#endif
2187 // mFastMixer below
2188 mFastMixerFutex(0)
2189 // mOutputSink below
2190 // mPipeSink below
2191 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192{
Glenn Kasten58912562012-04-03 10:45:00 -07002193 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2194 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2195 "mFrameCount=%d, mNormalFrameCount=%d",
2196 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2197 mNormalFrameCount);
2198 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2199
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 // FIXME - Current mixer implementation only supports stereo output
2201 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002202 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
Glenn Kasten58912562012-04-03 10:45:00 -07002204
2205 // create an NBAIO sink for the HAL output stream, and negotiate
2206 mOutputSink = new AudioStreamOutSink(output->stream);
2207 size_t numCounterOffers = 0;
2208 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2209 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2210 ALOG_ASSERT(index == 0);
2211
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002212 // initialize fast mixer depending on configuration
2213 bool initFastMixer;
2214 switch (kUseFastMixer) {
2215 case FastMixer_Never:
2216 initFastMixer = false;
2217 break;
2218 case FastMixer_Always:
2219 initFastMixer = true;
2220 break;
2221 case FastMixer_Static:
2222 case FastMixer_Dynamic:
2223 initFastMixer = mFrameCount < mNormalFrameCount;
2224 break;
2225 }
2226 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002227
2228 // create a MonoPipe to connect our submix to FastMixer
2229 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002230 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2231 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2232 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2233 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002234 const NBAIO_Format offers[1] = {format};
2235 size_t numCounterOffers = 0;
2236 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2237 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002238 monoPipe->setAvgFrames((mScreenState & 1) ?
2239 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002240 mPipeSink = monoPipe;
2241
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002242#ifdef TEE_SINK_FRAMES
2243 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2244 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2245 numCounterOffers = 0;
2246 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2247 ALOG_ASSERT(index == 0);
2248 mTeeSink = teeSink;
2249 PipeReader *teeSource = new PipeReader(*teeSink);
2250 numCounterOffers = 0;
2251 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2252 ALOG_ASSERT(index == 0);
2253 mTeeSource = teeSource;
2254#endif
2255
Glenn Kasten58912562012-04-03 10:45:00 -07002256#ifdef SOAKER
2257 // create a soaker as workaround for governor issues
2258 mSoaker = new Soaker();
2259 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2260 mSoaker->run("Soaker", PRIORITY_LOWEST);
2261#endif
2262
2263 // create fast mixer and configure it initially with just one fast track for our submix
2264 mFastMixer = new FastMixer();
2265 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002266#ifdef STATE_QUEUE_DUMP
2267 sq->setObserverDump(&mStateQueueObserverDump);
2268 sq->setMutatorDump(&mStateQueueMutatorDump);
2269#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002270 FastMixerState *state = sq->begin();
2271 FastTrack *fastTrack = &state->mFastTracks[0];
2272 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2273 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2274 fastTrack->mVolumeProvider = NULL;
2275 fastTrack->mGeneration++;
2276 state->mFastTracksGen++;
2277 state->mTrackMask = 1;
2278 // fast mixer will use the HAL output sink
2279 state->mOutputSink = mOutputSink.get();
2280 state->mOutputSinkGen++;
2281 state->mFrameCount = mFrameCount;
2282 state->mCommand = FastMixerState::COLD_IDLE;
2283 // already done in constructor initialization list
2284 //mFastMixerFutex = 0;
2285 state->mColdFutexAddr = &mFastMixerFutex;
2286 state->mColdGen++;
2287 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002288 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002289 sq->end();
2290 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2291
2292 // start the fast mixer
2293 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2294#ifdef HAVE_REQUEST_PRIORITY
2295 pid_t tid = mFastMixer->getTid();
2296 int err = requestPriority(getpid_cached, tid, 2);
2297 if (err != 0) {
2298 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2299 2, getpid_cached, tid, err);
2300 }
2301#endif
2302
Glenn Kastenc15d6652012-05-30 14:52:57 -07002303#ifdef AUDIO_WATCHDOG
2304 // create and start the watchdog
2305 mAudioWatchdog = new AudioWatchdog();
2306 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2307 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2308 tid = mAudioWatchdog->getTid();
2309 err = requestPriority(getpid_cached, tid, 1);
2310 if (err != 0) {
2311 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2312 1, getpid_cached, tid, err);
2313 }
2314#endif
2315
Glenn Kasten58912562012-04-03 10:45:00 -07002316 } else {
2317 mFastMixer = NULL;
2318 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002319
2320 switch (kUseFastMixer) {
2321 case FastMixer_Never:
2322 case FastMixer_Dynamic:
2323 mNormalSink = mOutputSink;
2324 break;
2325 case FastMixer_Always:
2326 mNormalSink = mPipeSink;
2327 break;
2328 case FastMixer_Static:
2329 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2330 break;
2331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332}
2333
2334AudioFlinger::MixerThread::~MixerThread()
2335{
Glenn Kasten58912562012-04-03 10:45:00 -07002336 if (mFastMixer != NULL) {
2337 FastMixerStateQueue *sq = mFastMixer->sq();
2338 FastMixerState *state = sq->begin();
2339 if (state->mCommand == FastMixerState::COLD_IDLE) {
2340 int32_t old = android_atomic_inc(&mFastMixerFutex);
2341 if (old == -1) {
2342 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2343 }
2344 }
2345 state->mCommand = FastMixerState::EXIT;
2346 sq->end();
2347 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2348 mFastMixer->join();
2349 // Though the fast mixer thread has exited, it's state queue is still valid.
2350 // We'll use that extract the final state which contains one remaining fast track
2351 // corresponding to our sub-mix.
2352 state = sq->begin();
2353 ALOG_ASSERT(state->mTrackMask == 1);
2354 FastTrack *fastTrack = &state->mFastTracks[0];
2355 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2356 delete fastTrack->mBufferProvider;
2357 sq->end(false /*didModify*/);
2358 delete mFastMixer;
2359#ifdef SOAKER
2360 if (mSoaker != NULL) {
2361 mSoaker->requestExitAndWait();
2362 }
2363 delete mSoaker;
2364#endif
Glenn Kastenc15d6652012-05-30 14:52:57 -07002365 if (mAudioWatchdog != 0) {
2366 mAudioWatchdog->requestExit();
2367 mAudioWatchdog->requestExitAndWait();
2368 mAudioWatchdog.clear();
2369 }
Glenn Kasten58912562012-04-03 10:45:00 -07002370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 delete mAudioMixer;
2372}
2373
Glenn Kasten83efdd02012-02-24 07:21:32 -08002374class CpuStats {
2375public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002376 CpuStats();
2377 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002378#ifdef DEBUG_CPU_USAGE
2379private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002380 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2381 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2382
2383 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2384
2385 int mCpuNum; // thread's current CPU number
2386 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002387#endif
2388};
2389
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002391#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002392 : mCpuNum(-1), mCpukHz(-1)
2393#endif
2394{
2395}
2396
2397void CpuStats::sample(const String8 &title) {
2398#ifdef DEBUG_CPU_USAGE
2399 // get current thread's delta CPU time in wall clock ns
2400 double wcNs;
2401 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2402
2403 // record sample for wall clock statistics
2404 if (valid) {
2405 mWcStats.sample(wcNs);
2406 }
2407
2408 // get the current CPU number
2409 int cpuNum = sched_getcpu();
2410
2411 // get the current CPU frequency in kHz
2412 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2413
2414 // check if either CPU number or frequency changed
2415 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2416 mCpuNum = cpuNum;
2417 mCpukHz = cpukHz;
2418 // ignore sample for purposes of cycles
2419 valid = false;
2420 }
2421
2422 // if no change in CPU number or frequency, then record sample for cycle statistics
2423 if (valid && mCpukHz > 0) {
2424 double cycles = wcNs * cpukHz * 0.000001;
2425 mHzStats.sample(cycles);
2426 }
2427
2428 unsigned n = mWcStats.n();
2429 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002430 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002431 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002432 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2433 double perLoop = elapsed / (double) n;
2434 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002435 double perLoop1k = perLoop * 0.001;
2436 double mean = mWcStats.mean();
2437 double stddev = mWcStats.stddev();
2438 double minimum = mWcStats.minimum();
2439 double maximum = mWcStats.maximum();
2440 double meanCycles = mHzStats.mean();
2441 double stddevCycles = mHzStats.stddev();
2442 double minCycles = mHzStats.minimum();
2443 double maxCycles = mHzStats.maximum();
2444 mCpuUsage.resetElapsed();
2445 mWcStats.reset();
2446 mHzStats.reset();
2447 ALOGD("CPU usage for %s over past %.1f secs\n"
2448 " (%u mixer loops at %.1f mean ms per loop):\n"
2449 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2450 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2451 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2452 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002453 elapsed * .000000001, n, perLoop * .000001,
2454 mean * .001,
2455 stddev * .001,
2456 minimum * .001,
2457 maximum * .001,
2458 mean / perLoop100,
2459 stddev / perLoop100,
2460 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002461 maximum / perLoop100,
2462 meanCycles / perLoop1k,
2463 stddevCycles / perLoop1k,
2464 minCycles / perLoop1k,
2465 maxCycles / perLoop1k);
2466
Glenn Kasten83efdd02012-02-24 07:21:32 -08002467 }
2468 }
2469#endif
2470};
2471
Glenn Kasten37d825e2012-02-24 07:21:48 -08002472void AudioFlinger::PlaybackThread::checkSilentMode_l()
2473{
2474 if (!mMasterMute) {
2475 char value[PROPERTY_VALUE_MAX];
2476 if (property_get("ro.audio.silent", value, "0") > 0) {
2477 char *endptr;
2478 unsigned long ul = strtoul(value, &endptr, 0);
2479 if (*endptr == '\0' && ul != 0) {
2480 ALOGD("Silence is golden");
2481 // The setprop command will not allow a property to be changed after
2482 // the first time it is set, so we don't have to worry about un-muting.
2483 setMasterMute_l(true);
2484 }
2485 }
2486 }
2487}
2488
Glenn Kasten000f0e32012-03-01 17:10:56 -08002489bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490{
2491 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002492
Glenn Kasten000f0e32012-03-01 17:10:56 -08002493 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002494
2495 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002497if (mType == MIXER) {
2498 longStandbyExit = false;
2499}
Glenn Kasten688a6402012-02-29 07:57:06 -08002500
Glenn Kasten000f0e32012-03-01 17:10:56 -08002501 // DUPLICATING
2502 // FIXME could this be made local to while loop?
2503 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002504
Glenn Kasten66fcab92012-02-24 14:59:21 -08002505 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002506 sleepTime = idleSleepTime;
2507
2508if (mType == MIXER) {
2509 sleepTimeShift = 0;
2510}
2511
Glenn Kasten83efdd02012-02-24 07:21:32 -08002512 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002513 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514
Eric Laurentfeb0db62011-07-22 09:04:31 -07002515 acquireWakeLock();
2516
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 while (!exitPending())
2518 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002519 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002520
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002521 Vector< sp<EffectChain> > effectChains;
2522
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 processConfigEvents();
2524
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 { // scope for mLock
2526
2527 Mutex::Autolock _l(mLock);
2528
2529 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002530 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 }
2532
Glenn Kastenfa26a852012-03-06 11:28:04 -08002533 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002536 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002537 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002539
2540 threadLoop_standby();
2541
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 mStandby = true;
2543 mBytesWritten = 0;
2544 }
2545
Glenn Kasten3e074702012-02-28 18:40:35 -08002546 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 // we're about to wait, flush the binder command buffer
2548 IPCThreadState::self()->flushCommands();
2549
Glenn Kastenfa26a852012-03-06 11:28:04 -08002550 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002551
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 if (exitPending()) break;
2553
Eric Laurentfeb0db62011-07-22 09:04:31 -07002554 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002556 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002558 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002559 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560
Eric Laurentda747442012-04-25 18:53:13 -07002561 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002562 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563
Glenn Kasten37d825e2012-02-24 07:21:48 -08002564 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565
Glenn Kasten000f0e32012-03-01 17:10:56 -08002566 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002568 if (mType == MIXER) {
2569 sleepTimeShift = 0;
2570 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 continue;
2573 }
2574 }
2575
Glenn Kasten81028042012-04-30 18:15:12 -07002576 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002577 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578
2579 // prevent any changes in effect chain list and in each effect chain
2580 // during mixing and effect process as the audio buffers could be deleted
2581 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002582 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584
Glenn Kastenfec279f2012-03-08 07:47:15 -08002585 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002586 threadLoop_mix();
2587 } else {
2588 threadLoop_sleepTime();
2589 }
2590
2591 if (mSuspended > 0) {
2592 sleepTime = suspendSleepTimeUs();
2593 }
2594
2595 // only process effects if we're going to write
2596 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002597 for (size_t i = 0; i < effectChains.size(); i ++) {
2598 effectChains[i]->process_l();
2599 }
2600 }
2601
2602 // enable changes in effect chain
2603 unlockEffectChains(effectChains);
2604
2605 // sleepTime == 0 means we must write to audio hardware
2606 if (sleepTime == 0) {
2607
2608 threadLoop_write();
2609
2610if (mType == MIXER) {
2611 // write blocked detection
2612 nsecs_t now = systemTime();
2613 nsecs_t delta = now - mLastWriteTime;
2614 if (!mStandby && delta > maxPeriod) {
2615 mNumDelayedWrites++;
2616 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002617#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002618 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002619#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2621 ns2ms(delta), mNumDelayedWrites, this);
2622 lastWarning = now;
2623 }
2624 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2625 // a different threshold. Or completely removed for what it is worth anyway...
2626 if (mStandby) {
2627 longStandbyExit = true;
2628 }
2629 }
2630}
2631
2632 mStandby = false;
2633 } else {
2634 usleep(sleepTime);
2635 }
2636
Glenn Kasten58912562012-04-03 10:45:00 -07002637 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002639 // same lock. This will also mutate and push a new fast mixer state.
2640 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002641 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002642
Glenn Kastenfa26a852012-03-06 11:28:04 -08002643 // FIXME I don't understand the need for this here;
2644 // it was in the original code but maybe the
2645 // assignment in saveOutputTracks() makes this unnecessary?
2646 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002647
2648 // Effect chains will be actually deleted here if they were removed from
2649 // mEffectChains list during mixing or effects processing
2650 effectChains.clear();
2651
2652 // FIXME Note that the above .clear() is no longer necessary since effectChains
2653 // is now local to this block, but will keep it for now (at least until merge done).
2654 }
2655
2656if (mType == MIXER || mType == DIRECT) {
2657 // put output stream into standby mode
2658 if (!mStandby) {
2659 mOutput->stream->common.standby(&mOutput->stream->common);
2660 }
2661}
2662if (mType == DUPLICATING) {
2663 // for DuplicatingThread, standby mode is handled by the outputTracks
2664}
2665
2666 releaseWakeLock();
2667
2668 ALOGV("Thread %p type %d exiting", this, mType);
2669 return false;
2670}
2671
Glenn Kasten58912562012-04-03 10:45:00 -07002672void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2673{
Glenn Kasten58912562012-04-03 10:45:00 -07002674 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2675}
2676
2677void AudioFlinger::MixerThread::threadLoop_write()
2678{
2679 // FIXME we should only do one push per cycle; confirm this is true
2680 // Start the fast mixer if it's not already running
2681 if (mFastMixer != NULL) {
2682 FastMixerStateQueue *sq = mFastMixer->sq();
2683 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002684 if (state->mCommand != FastMixerState::MIX_WRITE &&
2685 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002686 if (state->mCommand == FastMixerState::COLD_IDLE) {
2687 int32_t old = android_atomic_inc(&mFastMixerFutex);
2688 if (old == -1) {
2689 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2690 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002691 if (mAudioWatchdog != 0) {
2692 mAudioWatchdog->resume();
2693 }
Glenn Kasten58912562012-04-03 10:45:00 -07002694 }
2695 state->mCommand = FastMixerState::MIX_WRITE;
2696 sq->end();
2697 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002698 if (kUseFastMixer == FastMixer_Dynamic) {
2699 mNormalSink = mPipeSink;
2700 }
Glenn Kasten58912562012-04-03 10:45:00 -07002701 } else {
2702 sq->end(false /*didModify*/);
2703 }
2704 }
2705 PlaybackThread::threadLoop_write();
2706}
2707
Glenn Kasten000f0e32012-03-01 17:10:56 -08002708// shared by MIXER and DIRECT, overridden by DUPLICATING
2709void AudioFlinger::PlaybackThread::threadLoop_write()
2710{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002711 // FIXME rewrite to reduce number of system calls
2712 mLastWriteTime = systemTime();
2713 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002714 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002715
Eric Laurent67c0a582012-05-01 19:31:12 -07002716 // If an NBAIO sink is present, use it to write the normal mixer's submix
2717 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002718#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002719 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002720#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002721 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002722#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002723 // update the setpoint when gScreenState changes
2724 uint32_t screenState = gScreenState;
2725 if (screenState != mScreenState) {
2726 mScreenState = screenState;
2727 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2728 if (pipe != NULL) {
2729 pipe->setAvgFrames((mScreenState & 1) ?
2730 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2731 }
2732 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002733 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
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::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002736#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002737 if (framesWritten > 0) {
2738 bytesWritten = framesWritten << mBitShift;
2739 } else {
2740 bytesWritten = framesWritten;
2741 }
2742 // otherwise use the HAL / AudioStreamOut directly
2743 } else {
2744 // Direct output thread.
2745 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002746 }
2747
Eric Laurent67c0a582012-05-01 19:31:12 -07002748 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002749 mNumWrites++;
2750 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002751}
2752
Glenn Kasten58912562012-04-03 10:45:00 -07002753void AudioFlinger::MixerThread::threadLoop_standby()
2754{
2755 // Idle the fast mixer if it's currently running
2756 if (mFastMixer != NULL) {
2757 FastMixerStateQueue *sq = mFastMixer->sq();
2758 FastMixerState *state = sq->begin();
2759 if (!(state->mCommand & FastMixerState::IDLE)) {
2760 state->mCommand = FastMixerState::COLD_IDLE;
2761 state->mColdFutexAddr = &mFastMixerFutex;
2762 state->mColdGen++;
2763 mFastMixerFutex = 0;
2764 sq->end();
2765 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2766 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002767 if (kUseFastMixer == FastMixer_Dynamic) {
2768 mNormalSink = mOutputSink;
2769 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002770 if (mAudioWatchdog != 0) {
2771 mAudioWatchdog->pause();
2772 }
Glenn Kasten58912562012-04-03 10:45:00 -07002773 } else {
2774 sq->end(false /*didModify*/);
2775 }
2776 }
2777 PlaybackThread::threadLoop_standby();
2778}
2779
Glenn Kasten000f0e32012-03-01 17:10:56 -08002780// shared by MIXER and DIRECT, overridden by DUPLICATING
2781void AudioFlinger::PlaybackThread::threadLoop_standby()
2782{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002783 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2784 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002785}
2786
2787void AudioFlinger::MixerThread::threadLoop_mix()
2788{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002789 // obtain the presentation timestamp of the next output buffer
2790 int64_t pts;
2791 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002792
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 if (NULL != mOutput->stream->get_next_write_timestamp) {
2794 status = mOutput->stream->get_next_write_timestamp(
2795 mOutput->stream, &pts);
2796 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002797
Glenn Kasten952eeb22012-03-06 11:30:57 -08002798 if (status != NO_ERROR) {
2799 pts = AudioBufferProvider::kInvalidPTS;
2800 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002801
Glenn Kasten952eeb22012-03-06 11:30:57 -08002802 // mix buffers...
2803 mAudioMixer->process(pts);
2804 // increase sleep time progressively when application underrun condition clears.
2805 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2806 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2807 // such that we would underrun the audio HAL.
2808 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2809 sleepTimeShift--;
2810 }
2811 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002812 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002813 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002814}
2815
2816void AudioFlinger::MixerThread::threadLoop_sleepTime()
2817{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 // If no tracks are ready, sleep once for the duration of an output
2819 // buffer size, then write 0s to the output
2820 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002821 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002822 sleepTime = activeSleepTime >> sleepTimeShift;
2823 if (sleepTime < kMinThreadSleepTimeUs) {
2824 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002826 // reduce sleep time in case of consecutive application underruns to avoid
2827 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2828 // duration we would end up writing less data than needed by the audio HAL if
2829 // the condition persists.
2830 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2831 sleepTimeShift++;
2832 }
2833 } else {
2834 sleepTime = idleSleepTime;
2835 }
2836 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002837 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002838 memset (mMixBuffer, 0, mixBufferSize);
2839 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002840 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002841 }
2842 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843}
2844
2845// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002846AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002847 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848{
2849
Glenn Kasten29c23c32012-01-26 13:37:52 -08002850 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002852 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 size_t mixedTracks = 0;
2854 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002855 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002856 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002857 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
2859 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002860 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861
Eric Laurent571d49c2010-08-11 05:20:11 -07002862 if (masterMute) {
2863 masterVolume = 0;
2864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002866 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002868 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002869 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 masterVolume = (float)((v + (1 << 23)) >> 24);
2871 chain.clear();
2872 }
2873
Glenn Kasten288ed212012-04-25 17:52:27 -07002874 // prepare a new state to push
2875 FastMixerStateQueue *sq = NULL;
2876 FastMixerState *state = NULL;
2877 bool didModify = false;
2878 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2879 if (mFastMixer != NULL) {
2880 sq = mFastMixer->sq();
2881 state = sq->begin();
2882 }
2883
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002885 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 if (t == 0) continue;
2887
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002888 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002890
Glenn Kasten288ed212012-04-25 17:52:27 -07002891 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002892 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002893
2894 // It's theoretically possible (though unlikely) for a fast track to be created
2895 // and then removed within the same normal mix cycle. This is not a problem, as
2896 // the track never becomes active so it's fast mixer slot is never touched.
2897 // The converse, of removing an (active) track and then creating a new track
2898 // at the identical fast mixer slot within the same normal mix cycle,
2899 // is impossible because the slot isn't marked available until the end of each cycle.
2900 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002901 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2902 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002903 FastTrack *fastTrack = &state->mFastTracks[j];
2904
2905 // Determine whether the track is currently in underrun condition,
2906 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002907 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2908 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002909 uint32_t recentFull = (underruns.mBitFields.mFull -
2910 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2911 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2912 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2913 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2914 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2915 uint32_t recentUnderruns = recentPartial + recentEmpty;
2916 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002918 // or stopped which can occur when flush() is called while active
2919 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002920 track->mUnderrunCount += recentUnderruns;
2921 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002922
Glenn Kastend08f48c2012-05-01 18:14:02 -07002923 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002924 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002925 bool isActive = true;
2926 switch (track->mState) {
2927 case TrackBase::STOPPING_1:
2928 // track stays active in STOPPING_1 state until first underrun
2929 if (recentUnderruns > 0) {
2930 track->mState = TrackBase::STOPPING_2;
2931 }
2932 break;
2933 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002934 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002935 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002936 break;
2937 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002940 break;
2941 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002942 if (recentFull > 0 || recentPartial > 0) {
2943 // track has provided at least some frames recently: reset retry count
2944 track->mRetryCount = kMaxTrackRetries;
2945 }
2946 if (recentUnderruns == 0) {
2947 // no recent underruns: stay active
2948 break;
2949 }
2950 // there has recently been an underrun of some kind
2951 if (track->sharedBuffer() == 0) {
2952 // were any of the recent underruns "empty" (no frames available)?
2953 if (recentEmpty == 0) {
2954 // no, then ignore the partial underruns as they are allowed indefinitely
2955 break;
2956 }
2957 // there has recently been an "empty" underrun: decrement the retry counter
2958 if (--(track->mRetryCount) > 0) {
2959 break;
2960 }
2961 // indicate to client process that the track was disabled because of underrun;
2962 // it will then automatically call start() when data is available
2963 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2964 // remove from active list, but state remains ACTIVE [confusing but true]
2965 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002966 break;
2967 }
2968 // fall through
2969 case TrackBase::STOPPING_2:
2970 case TrackBase::PAUSED:
2971 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002972 case TrackBase::STOPPED:
2973 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002974 // Check for presentation complete if track is inactive
2975 // We have consumed all the buffers of this track.
2976 // This would be incomplete if we auto-paused on underrun
2977 {
2978 size_t audioHALFrames =
2979 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2980 size_t framesWritten =
2981 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2982 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2983 // track stays in active list until presentation is complete
2984 break;
2985 }
2986 }
2987 if (track->isStopping_2()) {
2988 track->mState = TrackBase::STOPPED;
2989 }
2990 if (track->isStopped()) {
2991 // Can't reset directly, as fast mixer is still polling this track
2992 // track->reset();
2993 // So instead mark this track as needing to be reset after push with ack
2994 resetMask |= 1 << i;
2995 }
2996 isActive = false;
2997 break;
2998 case TrackBase::IDLE:
2999 default:
3000 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003001 }
3002
3003 if (isActive) {
3004 // was it previously inactive?
3005 if (!(state->mTrackMask & (1 << j))) {
3006 ExtendedAudioBufferProvider *eabp = track;
3007 VolumeProvider *vp = track;
3008 fastTrack->mBufferProvider = eabp;
3009 fastTrack->mVolumeProvider = vp;
3010 fastTrack->mSampleRate = track->mSampleRate;
3011 fastTrack->mChannelMask = track->mChannelMask;
3012 fastTrack->mGeneration++;
3013 state->mTrackMask |= 1 << j;
3014 didModify = true;
3015 // no acknowledgement required for newly active tracks
3016 }
3017 // cache the combined master volume and stream type volume for fast mixer; this
3018 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3019 track->mCachedVolume = track->isMuted() ?
3020 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3021 ++fastTracks;
3022 } else {
3023 // was it previously active?
3024 if (state->mTrackMask & (1 << j)) {
3025 fastTrack->mBufferProvider = NULL;
3026 fastTrack->mGeneration++;
3027 state->mTrackMask &= ~(1 << j);
3028 didModify = true;
3029 // If any fast tracks were removed, we must wait for acknowledgement
3030 // because we're about to decrement the last sp<> on those tracks.
3031 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003032 } else {
3033 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003034 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003035 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003036 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003037 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003038 }
3039 continue;
3040 }
3041
3042 { // local variable scope to avoid goto warning
3043
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 audio_track_cblk_t* cblk = track->cblk();
3045
3046 // The first time a track is added we wait
3047 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003048 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003049 // make sure that we have enough frames to mix one full buffer.
3050 // enforce this condition only once to enable draining the buffer in case the client
3051 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003052 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003053 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003054 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003055 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003056 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003057 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003058 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003059 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003060 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003061 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003062 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003063 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003064 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3065 // the minimum track buffer size is normally twice the number of frames necessary
3066 // to fill one buffer and the resampler should not leave more than one buffer worth
3067 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003068 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003069 }
3070 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003071 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 !track->isPaused() && !track->isTerminated())
3073 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003074 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075
3076 mixedTracks++;
3077
3078 // track->mainBuffer() != mMixBuffer means there is an effect chain
3079 // connected to the track
3080 chain.clear();
3081 if (track->mainBuffer() != mMixBuffer) {
3082 chain = getEffectChain_l(track->sessionId());
3083 // Delegate volume control to effect in track effect chain if needed
3084 if (chain != 0) {
3085 tracksWithEffect++;
3086 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003087 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003088 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 }
3090 }
3091
3092
3093 int param = AudioMixer::VOLUME;
3094 if (track->mFillingUpStatus == Track::FS_FILLED) {
3095 // no ramp for the first volume setting
3096 track->mFillingUpStatus = Track::FS_ACTIVE;
3097 if (track->mState == TrackBase::RESUMING) {
3098 track->mState = TrackBase::ACTIVE;
3099 param = AudioMixer::RAMP_VOLUME;
3100 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003101 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 } else if (cblk->server != 0) {
3103 // If the track is stopped before the first frame was mixed,
3104 // do not apply ramp
3105 param = AudioMixer::RAMP_VOLUME;
3106 }
3107
3108 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003109 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003110 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003111 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003112 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 if (track->isPausing()) {
3114 track->setPaused();
3115 }
3116 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003117
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003119 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003121 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003122 vl = vlr & 0xFFFF;
3123 vr = vlr >> 16;
3124 // track volumes come from shared memory, so can't be trusted and must be clamped
3125 if (vl > MAX_GAIN_INT) {
3126 ALOGV("Track left volume out of range: %04X", vl);
3127 vl = MAX_GAIN_INT;
3128 }
3129 if (vr > MAX_GAIN_INT) {
3130 ALOGV("Track right volume out of range: %04X", vr);
3131 vr = MAX_GAIN_INT;
3132 }
3133 // now apply the master volume and stream type volume
3134 vl = (uint32_t)(v * vl) << 12;
3135 vr = (uint32_t)(v * vr) << 12;
3136 // assuming master volume and stream type volume each go up to 1.0,
3137 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138
Glenn Kasten05632a52012-01-03 14:22:33 -08003139 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3140 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003141 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003142 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003143 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003144 }
3145 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003147 // Delegate volume control to effect in track effect chain if needed
3148 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3149 // Do not ramp volume if volume is controlled by effect
3150 param = AudioMixer::VOLUME;
3151 track->mHasVolumeController = true;
3152 } else {
3153 // force no volume ramp when volume controller was just disabled or removed
3154 // from effect chain to avoid volume spike
3155 if (track->mHasVolumeController) {
3156 param = AudioMixer::VOLUME;
3157 }
3158 track->mHasVolumeController = false;
3159 }
3160
3161 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003162 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003163 vl = (vl + (1 << 11)) >> 12;
3164 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3165 vr = (vr + (1 << 11)) >> 12;
3166 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003167
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003168 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 -07003169
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003171 mAudioMixer->setBufferProvider(name, track);
3172 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003174 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3175 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3176 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003178 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 AudioMixer::TRACK,
3180 AudioMixer::FORMAT, (void *)track->format());
3181 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003182 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003184 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003186 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 AudioMixer::RESAMPLE,
3188 AudioMixer::SAMPLE_RATE,
3189 (void *)(cblk->sampleRate));
3190 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 AudioMixer::TRACK,
3193 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3194 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003195 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 AudioMixer::TRACK,
3197 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3198
3199 // reset retry count
3200 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003201
Eric Laurent27741442012-01-17 19:20:12 -08003202 // If one track is ready, set the mixer ready if:
3203 // - the mixer was not ready during previous round OR
3204 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003205 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003206 mixerStatus != MIXER_TRACKS_ENABLED) {
3207 mixerStatus = MIXER_TRACKS_READY;
3208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003210 // clear effect chain input buffer if an active track underruns to avoid sending
3211 // previous audio buffer again to effects
3212 chain = getEffectChain_l(track->sessionId());
3213 if (chain != 0) {
3214 chain->clearInputBuffer();
3215 }
3216
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003217 //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 -07003218 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3219 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 // We have consumed all the buffers of this track.
3221 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003222 // TODO: use actual buffer filling status instead of latency when available from
3223 // audio HAL
3224 size_t audioHALFrames =
3225 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3226 size_t framesWritten =
3227 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3228 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003229 if (track->isStopped()) {
3230 track->reset();
3231 }
Eric Laurenta011e352012-03-29 15:51:43 -07003232 tracksToRemove->add(track);
3233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003235 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 // No buffers for this track. Give it a few chances to
3237 // fill a buffer, then remove it from active list.
3238 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003239 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003241 // indicate to client process that the track was disabled because of underrun;
3242 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003243 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003244 // If one track is not ready, mark the mixer also not ready if:
3245 // - the mixer was ready during previous round OR
3246 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003247 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003248 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mixerStatus = MIXER_TRACKS_ENABLED;
3250 }
3251 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003252 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 }
Glenn Kasten58912562012-04-03 10:45:00 -07003254
3255 } // local variable scope to avoid goto warning
3256track_is_ready: ;
3257
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 }
3259
Glenn Kasten288ed212012-04-25 17:52:27 -07003260 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003261 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003262 if (didModify) {
3263 state->mFastTracksGen++;
3264 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3265 if (kUseFastMixer == FastMixer_Dynamic &&
3266 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3267 state->mCommand = FastMixerState::COLD_IDLE;
3268 state->mColdFutexAddr = &mFastMixerFutex;
3269 state->mColdGen++;
3270 mFastMixerFutex = 0;
3271 if (kUseFastMixer == FastMixer_Dynamic) {
3272 mNormalSink = mOutputSink;
3273 }
3274 // If we go into cold idle, need to wait for acknowledgement
3275 // so that fast mixer stops doing I/O.
3276 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003277 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003278 }
3279 sq->end();
3280 }
3281 if (sq != NULL) {
3282 sq->end(didModify);
3283 sq->push(block);
3284 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003285 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3286 mAudioWatchdog->pause();
3287 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003288
3289 // Now perform the deferred reset on fast tracks that have stopped
3290 while (resetMask != 0) {
3291 size_t i = __builtin_ctz(resetMask);
3292 ALOG_ASSERT(i < count);
3293 resetMask &= ~(1 << i);
3294 sp<Track> t = mActiveTracks[i].promote();
3295 if (t == 0) continue;
3296 Track* track = t.get();
3297 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3298 track->reset();
3299 }
Glenn Kasten58912562012-04-03 10:45:00 -07003300
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 // remove all the tracks that need to be...
3302 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003303 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 for (size_t i=0 ; i<count ; i++) {
3305 const sp<Track>& track = tracksToRemove->itemAt(i);
3306 mActiveTracks.remove(track);
3307 if (track->mainBuffer() != mMixBuffer) {
3308 chain = getEffectChain_l(track->sessionId());
3309 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003310 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003311 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 }
3313 }
3314 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003315 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
3317 }
3318 }
3319
3320 // mix buffer must be cleared if all tracks are connected to an
3321 // effect chain as in this case the mixer will not write to
3322 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003323 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3324 // FIXME as a performance optimization, should remember previous zero status
3325 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 }
3327
Glenn Kasten58912562012-04-03 10:45:00 -07003328 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003329 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003330 if (fastTracks > 0) {
3331 mixerStatus = MIXER_TRACKS_READY;
3332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 return mixerStatus;
3334}
3335
Glenn Kasten66fcab92012-02-24 14:59:21 -08003336/*
3337The derived values that are cached:
3338 - mixBufferSize from frame count * frame size
3339 - activeSleepTime from activeSleepTimeUs()
3340 - idleSleepTime from idleSleepTimeUs()
3341 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3342 - maxPeriod from frame count and sample rate (MIXER only)
3343
3344The parameters that affect these derived values are:
3345 - frame count
3346 - frame size
3347 - sample rate
3348 - device type: A2DP or not
3349 - device latency
3350 - format: PCM or not
3351 - active sleep time
3352 - idle sleep time
3353*/
3354
3355void AudioFlinger::PlaybackThread::cacheParameters_l()
3356{
Glenn Kasten58912562012-04-03 10:45:00 -07003357 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003358 activeSleepTime = activeSleepTimeUs();
3359 idleSleepTime = idleSleepTimeUs();
3360}
3361
Glenn Kastenfff6d712012-01-12 16:38:12 -08003362void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363{
Steve Block3856b092011-10-20 11:56:00 +01003364 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003365 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003367
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 size_t size = mTracks.size();
3369 for (size_t i = 0; i < size; i++) {
3370 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003371 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003372 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 }
3375 }
3376}
3377
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003379int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003381 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382}
3383
3384// deleteTrackName_l() must be called with ThreadBase::mLock held
3385void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3386{
Steve Block3856b092011-10-20 11:56:00 +01003387 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 mAudioMixer->deleteTrackName(name);
3389}
3390
3391// checkForNewParameters_l() must be called with ThreadBase::mLock held
3392bool AudioFlinger::MixerThread::checkForNewParameters_l()
3393{
Glenn Kasten58912562012-04-03 10:45:00 -07003394 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3395 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 bool reconfig = false;
3397
3398 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003399
3400 if (mFastMixer != NULL) {
3401 FastMixerStateQueue *sq = mFastMixer->sq();
3402 FastMixerState *state = sq->begin();
3403 if (!(state->mCommand & FastMixerState::IDLE)) {
3404 previousCommand = state->mCommand;
3405 state->mCommand = FastMixerState::HOT_IDLE;
3406 sq->end();
3407 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3408 } else {
3409 sq->end(false /*didModify*/);
3410 }
3411 }
3412
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 status_t status = NO_ERROR;
3414 String8 keyValuePair = mNewParameters[0];
3415 AudioParameter param = AudioParameter(keyValuePair);
3416 int value;
3417
3418 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3419 reconfig = true;
3420 }
3421 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003422 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 status = BAD_VALUE;
3424 } else {
3425 reconfig = true;
3426 }
3427 }
3428 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003429 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 status = BAD_VALUE;
3431 } else {
3432 reconfig = true;
3433 }
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3436 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003437 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 // if frame count is changed after track creation
3439 if (!mTracks.isEmpty()) {
3440 status = INVALID_OPERATION;
3441 } else {
3442 reconfig = true;
3443 }
3444 }
3445 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003446#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003447 // when changing the audio output device, call addBatteryData to notify
3448 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003449 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003450 uint32_t params = 0;
3451 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003452 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003453 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3454 }
3455
3456 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003457 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003458 // check if any other device (except speaker) is on
3459 if (value & deviceWithoutSpeaker ) {
3460 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3461 }
3462
3463 if (params != 0) {
3464 addBatteryData(params);
3465 }
3466 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003467#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003468
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 // forward device change to effects that have requested to be
3470 // aware of attached audio device.
3471 mDevice = (uint32_t)value;
3472 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003473 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 }
3475 }
3476
3477 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003478 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003479 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003481 mOutput->stream->common.standby(&mOutput->stream->common);
3482 mStandby = true;
3483 mBytesWritten = 0;
3484 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003485 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
3487 if (status == NO_ERROR && reconfig) {
3488 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003489 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3490 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003492 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003494 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 if (name < 0) break;
3496 mTracks[i]->mName = name;
3497 // limit track sample rate to 2 x new output sample rate
3498 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3499 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3500 }
3501 }
3502 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3503 }
3504 }
3505
3506 mNewParameters.removeAt(0);
3507
3508 mParamStatus = status;
3509 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003510 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3511 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003512 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 }
Glenn Kasten58912562012-04-03 10:45:00 -07003514
3515 if (!(previousCommand & FastMixerState::IDLE)) {
3516 ALOG_ASSERT(mFastMixer != NULL);
3517 FastMixerStateQueue *sq = mFastMixer->sq();
3518 FastMixerState *state = sq->begin();
3519 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3520 state->mCommand = previousCommand;
3521 sq->end();
3522 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3523 }
3524
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 return reconfig;
3526}
3527
3528status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3529{
3530 const size_t SIZE = 256;
3531 char buffer[SIZE];
3532 String8 result;
3533
3534 PlaybackThread::dumpInternals(fd, args);
3535
3536 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3537 result.append(buffer);
3538 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003539
3540 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3541 FastMixerDumpState copy = mFastMixerDumpState;
3542 copy.dump(fd);
3543
Glenn Kasten39993082012-05-31 13:40:27 -07003544#ifdef STATE_QUEUE_DUMP
3545 // Similar for state queue
3546 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3547 observerCopy.dump(fd);
3548 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3549 mutatorCopy.dump(fd);
3550#endif
3551
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003552 // Write the tee output to a .wav file
3553 NBAIO_Source *teeSource = mTeeSource.get();
3554 if (teeSource != NULL) {
3555 char teePath[64];
3556 struct timeval tv;
3557 gettimeofday(&tv, NULL);
3558 struct tm tm;
3559 localtime_r(&tv.tv_sec, &tm);
3560 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3561 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3562 if (teeFd >= 0) {
3563 char wavHeader[44];
3564 memcpy(wavHeader,
3565 "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",
3566 sizeof(wavHeader));
3567 NBAIO_Format format = teeSource->format();
3568 unsigned channelCount = Format_channelCount(format);
3569 ALOG_ASSERT(channelCount <= FCC_2);
3570 unsigned sampleRate = Format_sampleRate(format);
3571 wavHeader[22] = channelCount; // number of channels
3572 wavHeader[24] = sampleRate; // sample rate
3573 wavHeader[25] = sampleRate >> 8;
3574 wavHeader[32] = channelCount * 2; // block alignment
3575 write(teeFd, wavHeader, sizeof(wavHeader));
3576 size_t total = 0;
3577 bool firstRead = true;
3578 for (;;) {
3579#define TEE_SINK_READ 1024
3580 short buffer[TEE_SINK_READ * FCC_2];
3581 size_t count = TEE_SINK_READ;
3582 ssize_t actual = teeSource->read(buffer, count);
3583 bool wasFirstRead = firstRead;
3584 firstRead = false;
3585 if (actual <= 0) {
3586 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3587 continue;
3588 }
3589 break;
3590 }
3591 ALOG_ASSERT(actual <= count);
3592 write(teeFd, buffer, actual * channelCount * sizeof(short));
3593 total += actual;
3594 }
3595 lseek(teeFd, (off_t) 4, SEEK_SET);
3596 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3597 write(teeFd, &temp, sizeof(temp));
3598 lseek(teeFd, (off_t) 40, SEEK_SET);
3599 temp = total * channelCount * sizeof(short);
3600 write(teeFd, &temp, sizeof(temp));
3601 close(teeFd);
3602 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3603 } else {
3604 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3605 }
3606 }
3607
Glenn Kastenc15d6652012-05-30 14:52:57 -07003608 if (mAudioWatchdog != 0) {
3609 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3610 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3611 wdCopy.dump(fd);
3612 }
3613
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 return NO_ERROR;
3615}
3616
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003617uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618{
Glenn Kasten58912562012-04-03 10:45:00 -07003619 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620}
3621
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003622uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003623{
Glenn Kasten58912562012-04-03 10:45:00 -07003624 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003625}
3626
Glenn Kasten66fcab92012-02-24 14:59:21 -08003627void AudioFlinger::MixerThread::cacheParameters_l()
3628{
3629 PlaybackThread::cacheParameters_l();
3630
3631 // FIXME: Relaxed timing because of a certain device that can't meet latency
3632 // Should be reduced to 2x after the vendor fixes the driver issue
3633 // increase threshold again due to low power audio mode. The way this warning
3634 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003635 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003636}
3637
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003639AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3640 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003641 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003642 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644}
3645
3646AudioFlinger::DirectOutputThread::~DirectOutputThread()
3647{
3648}
3649
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003650AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3651 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003652)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003654 sp<Track> trackToRemove;
3655
Glenn Kastenfec279f2012-03-08 07:47:15 -08003656 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657
Glenn Kasten952eeb22012-03-06 11:30:57 -08003658 // find out which tracks need to be processed
3659 if (mActiveTracks.size() != 0) {
3660 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003661 // The track died recently
3662 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 Track* const track = t.get();
3665 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666
Glenn Kasten952eeb22012-03-06 11:30:57 -08003667 // The first time a track is added we wait
3668 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003669 uint32_t minFrames;
3670 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3671 minFrames = mNormalFrameCount;
3672 } else {
3673 minFrames = 1;
3674 }
3675 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003676 !track->isPaused() && !track->isTerminated())
3677 {
3678 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679
Glenn Kasten952eeb22012-03-06 11:30:57 -08003680 if (track->mFillingUpStatus == Track::FS_FILLED) {
3681 track->mFillingUpStatus = Track::FS_ACTIVE;
3682 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 if (track->mState == TrackBase::RESUMING) {
3684 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003685 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003687
Glenn Kasten952eeb22012-03-06 11:30:57 -08003688 // compute volume for this track
3689 float left, right;
3690 if (track->isMuted() || mMasterMute || track->isPausing() ||
3691 mStreamTypes[track->streamType()].mute) {
3692 left = right = 0;
3693 if (track->isPausing()) {
3694 track->setPaused();
3695 }
3696 } else {
3697 float typeVolume = mStreamTypes[track->streamType()].volume;
3698 float v = mMasterVolume * typeVolume;
3699 uint32_t vlr = cblk->getVolumeLR();
3700 float v_clamped = v * (vlr & 0xFFFF);
3701 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3702 left = v_clamped/MAX_GAIN;
3703 v_clamped = v * (vlr >> 16);
3704 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3705 right = v_clamped/MAX_GAIN;
3706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707
Glenn Kasten952eeb22012-03-06 11:30:57 -08003708 if (left != mLeftVolFloat || right != mRightVolFloat) {
3709 mLeftVolFloat = left;
3710 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 // Convert volumes from float to 8.24
3713 uint32_t vl = (uint32_t)(left * (1 << 24));
3714 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 // Delegate volume control to effect in track effect chain if needed
3717 // only one effect chain can be present on DirectOutputThread, so if
3718 // there is one, the track is connected to it
3719 if (!mEffectChains.isEmpty()) {
3720 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003721 mEffectChains[0]->setVolume_l(&vl, &vr);
3722 left = (float)vl / (1 << 24);
3723 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003724 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003725 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 }
3727
3728 // reset retry count
3729 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003730 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003731 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003732 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003733 // clear effect chain input buffer if an active track underruns to avoid sending
3734 // previous audio buffer again to effects
3735 if (!mEffectChains.isEmpty()) {
3736 mEffectChains[0]->clearInputBuffer();
3737 }
3738
Glenn Kasten952eeb22012-03-06 11:30:57 -08003739 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003740 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3741 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 // We have consumed all the buffers of this track.
3743 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003744 // TODO: implement behavior for compressed audio
3745 size_t audioHALFrames =
3746 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3747 size_t framesWritten =
3748 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3749 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003750 if (track->isStopped()) {
3751 track->reset();
3752 }
Eric Laurenta011e352012-03-29 15:51:43 -07003753 trackToRemove = track;
3754 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003755 } else {
3756 // No buffers for this track. Give it a few chances to
3757 // fill a buffer, then remove it from active list.
3758 if (--(track->mRetryCount) <= 0) {
3759 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3760 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003762 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 }
3764 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003765 }
3766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003768 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 // remove all the tracks that need to be...
3770 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003771 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 mActiveTracks.remove(trackToRemove);
3773 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003774 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 trackToRemove->sessionId());
3776 mEffectChains[0]->decActiveTrackCnt();
3777 }
3778 if (trackToRemove->isTerminated()) {
3779 removeTrack_l(trackToRemove);
3780 }
3781 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782
Glenn Kastenfec279f2012-03-08 07:47:15 -08003783 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003784}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785
Glenn Kasten000f0e32012-03-01 17:10:56 -08003786void AudioFlinger::DirectOutputThread::threadLoop_mix()
3787{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003788 AudioBufferProvider::Buffer buffer;
3789 size_t frameCount = mFrameCount;
3790 int8_t *curBuf = (int8_t *)mMixBuffer;
3791 // output audio to hardware
3792 while (frameCount) {
3793 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003794 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003795 if (CC_UNLIKELY(buffer.raw == NULL)) {
3796 memset(curBuf, 0, frameCount * mFrameSize);
3797 break;
3798 }
3799 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3800 frameCount -= buffer.frameCount;
3801 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003802 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003803 }
3804 sleepTime = 0;
3805 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003806 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003807
Glenn Kasten000f0e32012-03-01 17:10:56 -08003808}
3809
3810void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3811{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003812 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003813 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003814 sleepTime = activeSleepTime;
3815 } else {
3816 sleepTime = idleSleepTime;
3817 }
3818 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003819 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 sleepTime = 0;
3821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822}
3823
3824// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003825int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826{
3827 return 0;
3828}
3829
3830// deleteTrackName_l() must be called with ThreadBase::mLock held
3831void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3832{
3833}
3834
3835// checkForNewParameters_l() must be called with ThreadBase::mLock held
3836bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3837{
3838 bool reconfig = false;
3839
3840 while (!mNewParameters.isEmpty()) {
3841 status_t status = NO_ERROR;
3842 String8 keyValuePair = mNewParameters[0];
3843 AudioParameter param = AudioParameter(keyValuePair);
3844 int value;
3845
3846 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3847 // do not accept frame count changes if tracks are open as the track buffer
3848 // size depends on frame count and correct behavior would not be garantied
3849 // if frame count is changed after track creation
3850 if (!mTracks.isEmpty()) {
3851 status = INVALID_OPERATION;
3852 } else {
3853 reconfig = true;
3854 }
3855 }
3856 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003857 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003858 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003860 mOutput->stream->common.standby(&mOutput->stream->common);
3861 mStandby = true;
3862 mBytesWritten = 0;
3863 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003864 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 }
3866 if (status == NO_ERROR && reconfig) {
3867 readOutputParameters();
3868 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3869 }
3870 }
3871
3872 mNewParameters.removeAt(0);
3873
3874 mParamStatus = status;
3875 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003876 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3877 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003878 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 }
3880 return reconfig;
3881}
3882
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003883uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884{
3885 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003886 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003887 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 } else {
3889 time = 10000;
3890 }
3891 return time;
3892}
3893
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003894uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895{
3896 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003897 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003898 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 } else {
3900 time = 10000;
3901 }
3902 return time;
3903}
3904
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003905uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003906{
3907 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003908 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003909 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3910 } else {
3911 time = 10000;
3912 }
3913 return time;
3914}
3915
Glenn Kasten66fcab92012-02-24 14:59:21 -08003916void AudioFlinger::DirectOutputThread::cacheParameters_l()
3917{
3918 PlaybackThread::cacheParameters_l();
3919
3920 // use shorter standby delay as on normal output to release
3921 // hardware resources as soon as possible
3922 standbyDelay = microseconds(activeSleepTime*2);
3923}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003924
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925// ----------------------------------------------------------------------------
3926
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003927AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003928 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003929 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3930 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 addOutputTrack(mainThread);
3933}
3934
3935AudioFlinger::DuplicatingThread::~DuplicatingThread()
3936{
3937 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3938 mOutputTracks[i]->destroy();
3939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940}
3941
Glenn Kasten000f0e32012-03-01 17:10:56 -08003942void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003944 // mix buffers...
3945 if (outputsReady(outputTracks)) {
3946 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3947 } else {
3948 memset(mMixBuffer, 0, mixBufferSize);
3949 }
3950 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003951 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003952 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003953}
3954
3955void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3956{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003957 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003958 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003959 sleepTime = activeSleepTime;
3960 } else {
3961 sleepTime = idleSleepTime;
3962 }
3963 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003964 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3965 writeFrames = mNormalFrameCount;
3966 memset(mMixBuffer, 0, mixBufferSize);
3967 } else {
3968 // flush remaining overflow buffers in output tracks
3969 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003970 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003971 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003972 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003973}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974
Glenn Kasten000f0e32012-03-01 17:10:56 -08003975void AudioFlinger::DuplicatingThread::threadLoop_write()
3976{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003977 for (size_t i = 0; i < outputTracks.size(); i++) {
3978 outputTracks[i]->write(mMixBuffer, writeFrames);
3979 }
3980 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003981}
Glenn Kasten688a6402012-02-29 07:57:06 -08003982
Glenn Kasten000f0e32012-03-01 17:10:56 -08003983void AudioFlinger::DuplicatingThread::threadLoop_standby()
3984{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003985 // DuplicatingThread implements standby by stopping all tracks
3986 for (size_t i = 0; i < outputTracks.size(); i++) {
3987 outputTracks[i]->stop();
3988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989}
3990
Glenn Kastenfa26a852012-03-06 11:28:04 -08003991void AudioFlinger::DuplicatingThread::saveOutputTracks()
3992{
3993 outputTracks = mOutputTracks;
3994}
3995
3996void AudioFlinger::DuplicatingThread::clearOutputTracks()
3997{
3998 outputTracks.clear();
3999}
4000
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4002{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004003 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004004 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004005 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004006 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007 this,
4008 mSampleRate,
4009 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004010 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 frameCount);
4012 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004013 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004015 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004016 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 }
4018}
4019
4020void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4021{
4022 Mutex::Autolock _l(mLock);
4023 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004024 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 mOutputTracks[i]->destroy();
4026 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004027 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028 return;
4029 }
4030 }
Steve Block3856b092011-10-20 11:56:00 +01004031 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032}
4033
Glenn Kasten438b0362012-03-06 11:24:48 -08004034// caller must hold mLock
4035void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036{
4037 mWaitTimeMs = UINT_MAX;
4038 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4039 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004040 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4042 if (waitTimeMs < mWaitTimeMs) {
4043 mWaitTimeMs = waitTimeMs;
4044 }
4045 }
4046 }
4047}
4048
4049
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004050bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051{
4052 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004053 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004055 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056 return false;
4057 }
4058 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4059 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004060 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 return false;
4062 }
4063 }
4064 return true;
4065}
4066
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004067uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068{
4069 return (mWaitTimeMs * 1000) / 2;
4070}
4071
Glenn Kasten66fcab92012-02-24 14:59:21 -08004072void AudioFlinger::DuplicatingThread::cacheParameters_l()
4073{
4074 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4075 updateWaitTime_l();
4076
4077 MixerThread::cacheParameters_l();
4078}
4079
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080// ----------------------------------------------------------------------------
4081
4082// TrackBase constructor must be called with AudioFlinger::mLock held
4083AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004084 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085 const sp<Client>& client,
4086 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004087 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004088 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 const sp<IMemory>& sharedBuffer,
4091 int sessionId)
4092 : RefBase(),
4093 mThread(thread),
4094 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004095 mCblk(NULL),
4096 // mBuffer
4097 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 mFrameCount(0),
4099 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004100 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004102 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004104 // mChannelCount
4105 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106{
Steve Block3856b092011-10-20 11:56:00 +01004107 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108
Steve Blockb8a80522011-12-20 16:23:08 +00004109 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004110 size_t size = sizeof(audio_track_cblk_t);
4111 uint8_t channelCount = popcount(channelMask);
4112 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4113 if (sharedBuffer == 0) {
4114 size += bufferSize;
4115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004117 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 mCblkMemory = client->heap()->allocate(size);
4119 if (mCblkMemory != 0) {
4120 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004121 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 new(mCblk) audio_track_cblk_t();
4123 // clear all buffers
4124 mCblk->frameCount = frameCount;
4125 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004126// uncomment the following lines to quickly test 32-bit wraparound
4127// mCblk->user = 0xffff0000;
4128// mCblk->server = 0xffff0000;
4129// mCblk->userBase = 0xffff0000;
4130// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004131 mChannelCount = channelCount;
4132 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 if (sharedBuffer == 0) {
4134 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4135 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4136 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004137 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 mCblk->flags = CBLK_UNDERRUN_ON;
4139 } else {
4140 mBuffer = sharedBuffer->pointer();
4141 }
4142 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4143 }
4144 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004145 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 client->heap()->dump("AudioTrack");
4147 return;
4148 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004149 } else {
4150 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004151 // construct the shared structure in-place.
4152 new(mCblk) audio_track_cblk_t();
4153 // clear all buffers
4154 mCblk->frameCount = frameCount;
4155 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004156// uncomment the following lines to quickly test 32-bit wraparound
4157// mCblk->user = 0xffff0000;
4158// mCblk->server = 0xffff0000;
4159// mCblk->userBase = 0xffff0000;
4160// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004161 mChannelCount = channelCount;
4162 mChannelMask = channelMask;
4163 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4164 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4165 // Force underrun condition to avoid false underrun callback until first data is
4166 // written to buffer (other flags are cleared)
4167 mCblk->flags = CBLK_UNDERRUN_ON;
4168 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170}
4171
4172AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4173{
Glenn Kastena0d68332012-01-27 16:47:15 -08004174 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004175 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004177 } else {
4178 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 }
4180 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004181 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004182 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004183 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004185 // If the client's reference count drops to zero, the associated destructor
4186 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4187 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 mClient.clear();
4189 }
4190}
4191
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004192// AudioBufferProvider interface
4193// getNextBuffer() = 0;
4194// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4196{
Glenn Kastene0feee32011-12-13 11:53:26 -08004197 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004199 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004200 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201 buffer->frameCount = 0;
4202}
4203
4204bool AudioFlinger::ThreadBase::TrackBase::step() {
4205 bool result;
4206 audio_track_cblk_t* cblk = this->cblk();
4207
4208 result = cblk->stepServer(mFrameCount);
4209 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004210 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004211 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 }
4213 return result;
4214}
4215
4216void AudioFlinger::ThreadBase::TrackBase::reset() {
4217 audio_track_cblk_t* cblk = this->cblk();
4218
4219 cblk->user = 0;
4220 cblk->server = 0;
4221 cblk->userBase = 0;
4222 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004223 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004224 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225}
4226
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4228 return (int)mCblk->sampleRate;
4229}
4230
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4232 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004233 size_t frameSize = cblk->frameSize;
4234 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4235 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236
4237 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004238 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4239 "TrackBase::getBuffer buffer out of range:\n"
4240 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4241 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004243 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
4245 return bufferStart;
4246}
4247
Eric Laurenta011e352012-03-29 15:51:43 -07004248status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4249{
4250 mSyncEvents.add(event);
4251 return NO_ERROR;
4252}
4253
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254// ----------------------------------------------------------------------------
4255
4256// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4257AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004258 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004260 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004262 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004263 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 int frameCount,
4265 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004266 int sessionId,
4267 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004268 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004269 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004270 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004271 // mRetryCount initialized later when needed
4272 mSharedBuffer(sharedBuffer),
4273 mStreamType(streamType),
4274 mName(-1), // see note below
4275 mMainBuffer(thread->mixBuffer()),
4276 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004277 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004278 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004279 mFlags(flags),
4280 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004281 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004282 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283{
4284 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4286 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004287 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004288 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4289 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
4290 if (mName < 0) {
4291 ALOGE("no more track names available");
4292 return;
4293 }
4294 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004295 if (flags & IAudioFlinger::TRACK_FAST) {
4296 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4297 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4298 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004299 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004300 // FIXME This is too eager. We allocate a fast track index before the
4301 // fast track becomes active. Since fast tracks are a scarce resource,
4302 // this means we are potentially denying other more important fast tracks from
4303 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004304 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004305 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004306 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004307 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004308 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004310 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311}
4312
4313AudioFlinger::PlaybackThread::Track::~Track()
4314{
Steve Block3856b092011-10-20 11:56:00 +01004315 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 sp<ThreadBase> thread = mThread.promote();
4317 if (thread != 0) {
4318 Mutex::Autolock _l(thread->mLock);
4319 mState = TERMINATED;
4320 }
4321}
4322
4323void AudioFlinger::PlaybackThread::Track::destroy()
4324{
4325 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4326 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004327 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 // we must acquire a strong reference on this Track before locking mLock
4329 // here so that the destructor is called only when exiting this function.
4330 // On the other hand, as long as Track::destroy() is only called by
4331 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4332 // this Track with its member mTrack.
4333 sp<Track> keep(this);
4334 { // scope for mLock
4335 sp<ThreadBase> thread = mThread.promote();
4336 if (thread != 0) {
4337 if (!isOutputTrack()) {
4338 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004339 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004340
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004341#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004342 // to track the speaker usage
4343 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004344#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 }
4346 AudioSystem::releaseOutput(thread->id());
4347 }
4348 Mutex::Autolock _l(thread->mLock);
4349 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4350 playbackThread->destroyTrack_l(this);
4351 }
4352 }
4353}
4354
Glenn Kasten288ed212012-04-25 17:52:27 -07004355/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4356{
Glenn Kastene213c862012-04-25 13:46:15 -07004357 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 -07004358 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004359}
4360
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4362{
Glenn Kasten83d86532012-01-17 14:39:34 -08004363 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004364 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004365 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004366 } else {
4367 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4368 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004369 track_state state = mState;
4370 char stateChar;
4371 switch (state) {
4372 case IDLE:
4373 stateChar = 'I';
4374 break;
4375 case TERMINATED:
4376 stateChar = 'T';
4377 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004378 case STOPPING_1:
4379 stateChar = 's';
4380 break;
4381 case STOPPING_2:
4382 stateChar = '5';
4383 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004384 case STOPPED:
4385 stateChar = 'S';
4386 break;
4387 case RESUMING:
4388 stateChar = 'R';
4389 break;
4390 case ACTIVE:
4391 stateChar = 'A';
4392 break;
4393 case PAUSING:
4394 stateChar = 'p';
4395 break;
4396 case PAUSED:
4397 stateChar = 'P';
4398 break;
Eric Laurent29864602012-05-08 18:57:51 -07004399 case FLUSHED:
4400 stateChar = 'F';
4401 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004402 default:
4403 stateChar = '?';
4404 break;
4405 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004406 char nowInUnderrun;
4407 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4408 case UNDERRUN_FULL:
4409 nowInUnderrun = ' ';
4410 break;
4411 case UNDERRUN_PARTIAL:
4412 nowInUnderrun = '<';
4413 break;
4414 case UNDERRUN_EMPTY:
4415 nowInUnderrun = '*';
4416 break;
4417 default:
4418 nowInUnderrun = '?';
4419 break;
4420 }
Glenn Kastene213c862012-04-25 13:46:15 -07004421 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4422 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004423 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 mStreamType,
4425 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004426 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 mSessionId,
4428 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004429 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004430 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 mMute,
4432 mFillingUpStatus,
4433 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004434 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4435 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 mCblk->server,
4437 mCblk->user,
4438 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004439 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004440 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004441 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004442 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443}
4444
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004445// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004446status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004449 audio_track_cblk_t* cblk = this->cblk();
4450 uint32_t framesReady;
4451 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004453 // Check if last stepServer failed, try to step now
4454 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004455 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4456 // Since the fast mixer is higher priority than client callback thread,
4457 // it does not result in priority inversion for client.
4458 // But a non-blocking solution would be preferable to avoid
4459 // fast mixer being unable to tryLock(), and
4460 // to avoid the extra context switches if the client wakes up,
4461 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004462 if (!step()) goto getNextBuffer_exit;
4463 ALOGV("stepServer recovered");
4464 mStepServerFailed = false;
4465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466
Glenn Kasten288ed212012-04-25 17:52:27 -07004467 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004468 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004470 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 uint32_t s = cblk->server;
4472 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4473
4474 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4475 if (framesReq > framesReady) {
4476 framesReq = framesReady;
4477 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004478 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 framesReq = bufferEnd - s;
4480 }
4481
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004482 buffer->raw = getBuffer(s, framesReq);
4483 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004485 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488
4489getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004490 buffer->raw = NULL;
4491 buffer->frameCount = 0;
4492 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4493 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494}
4495
Glenn Kasten288ed212012-04-25 17:52:27 -07004496// Note that framesReady() takes a mutex on the control block using tryLock().
4497// This could result in priority inversion if framesReady() is called by the normal mixer,
4498// as the normal mixer thread runs at lower
4499// priority than the client's callback thread: there is a short window within framesReady()
4500// during which the normal mixer could be preempted, and the client callback would block.
4501// Another problem can occur if framesReady() is called by the fast mixer:
4502// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4503// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4504size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004505 return mCblk->framesReady();
4506}
4507
Glenn Kasten288ed212012-04-25 17:52:27 -07004508// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004510 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511
John Grossman4ff14ba2012-02-08 16:37:41 -08004512 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4514 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004515 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 return true;
4517 }
4518 return false;
4519}
4520
Glenn Kasten3acbd052012-02-28 10:39:56 -08004521status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004522 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523{
4524 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004525 ALOGV("start(%d), calling pid %d session %d",
4526 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004527
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 sp<ThreadBase> thread = mThread.promote();
4529 if (thread != 0) {
4530 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004531 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 // here the track could be either new, or restarted
4533 // in both cases "unstop" the track
4534 if (mState == PAUSED) {
4535 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004536 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 } else {
4538 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 }
4541
4542 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4543 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004544 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004546
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004547#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004548 // to track the speaker usage
4549 if (status == NO_ERROR) {
4550 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4551 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004552#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 }
4554 if (status == NO_ERROR) {
4555 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4556 playbackThread->addTrack_l(this);
4557 } else {
4558 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004559 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 }
4561 } else {
4562 status = BAD_VALUE;
4563 }
4564 return status;
4565}
4566
4567void AudioFlinger::PlaybackThread::Track::stop()
4568{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004569 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 sp<ThreadBase> thread = mThread.promote();
4571 if (thread != 0) {
4572 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004573 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004574 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 // If the track is not active (PAUSED and buffers full), flush buffers
4576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4577 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4578 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004579 mState = STOPPED;
4580 } else if (!isFastTrack()) {
4581 mState = STOPPED;
4582 } else {
4583 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4584 // and then to STOPPED and reset() when presentation is complete
4585 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004587 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 }
4589 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4590 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004591 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004593
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004594#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004595 // to track the speaker usage
4596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004597#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 }
4600}
4601
4602void AudioFlinger::PlaybackThread::Track::pause()
4603{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004604 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 sp<ThreadBase> thread = mThread.promote();
4606 if (thread != 0) {
4607 Mutex::Autolock _l(thread->mLock);
4608 if (mState == ACTIVE || mState == RESUMING) {
4609 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004610 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 if (!isOutputTrack()) {
4612 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004613 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004615
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004616#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004617 // to track the speaker usage
4618 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004619#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621 }
4622 }
4623}
4624
4625void AudioFlinger::PlaybackThread::Track::flush()
4626{
Steve Block3856b092011-10-20 11:56:00 +01004627 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 sp<ThreadBase> thread = mThread.promote();
4629 if (thread != 0) {
4630 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004631 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4632 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 return;
4634 }
4635 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004636 // FLUSHED state
4637 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004638 // do not reset the track if it is still in the process of being stopped or paused.
4639 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004640 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004641 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004642 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4643 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4644 reset();
4645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 }
4647}
4648
4649void AudioFlinger::PlaybackThread::Track::reset()
4650{
4651 // Do not reset twice to avoid discarding data written just after a flush and before
4652 // the audioflinger thread detects the track is stopped.
4653 if (!mResetDone) {
4654 TrackBase::reset();
4655 // Force underrun condition to avoid false underrun callback until first data is
4656 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004657 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4658 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 mFillingUpStatus = FS_FILLING;
4660 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004661 if (mState == FLUSHED) {
4662 mState = IDLE;
4663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004664 }
4665}
4666
4667void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4668{
4669 mMute = muted;
4670}
4671
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4673{
4674 status_t status = DEAD_OBJECT;
4675 sp<ThreadBase> thread = mThread.promote();
4676 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004677 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4678 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 }
4680 return status;
4681}
4682
4683void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4684{
4685 mAuxEffectId = EffectId;
4686 mAuxBuffer = buffer;
4687}
4688
Eric Laurenta011e352012-03-29 15:51:43 -07004689bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4690 size_t audioHalFrames)
4691{
4692 // a track is considered presented when the total number of frames written to audio HAL
4693 // corresponds to the number of frames written when presentationComplete() is called for the
4694 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4695 if (mPresentationCompleteFrames == 0) {
4696 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4697 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4698 mPresentationCompleteFrames, audioHalFrames);
4699 }
4700 if (framesWritten >= mPresentationCompleteFrames) {
4701 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4702 mSessionId, framesWritten);
4703 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004704 return true;
4705 }
4706 return false;
4707}
4708
4709void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4710{
4711 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4712 if (mSyncEvents[i]->type() == type) {
4713 mSyncEvents[i]->trigger();
4714 mSyncEvents.removeAt(i);
4715 i--;
4716 }
4717 }
4718}
4719
Glenn Kasten58912562012-04-03 10:45:00 -07004720// implement VolumeBufferProvider interface
4721
4722uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4723{
4724 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4725 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4726 uint32_t vlr = mCblk->getVolumeLR();
4727 uint32_t vl = vlr & 0xFFFF;
4728 uint32_t vr = vlr >> 16;
4729 // track volumes come from shared memory, so can't be trusted and must be clamped
4730 if (vl > MAX_GAIN_INT) {
4731 vl = MAX_GAIN_INT;
4732 }
4733 if (vr > MAX_GAIN_INT) {
4734 vr = MAX_GAIN_INT;
4735 }
4736 // now apply the cached master volume and stream type volume;
4737 // this is trusted but lacks any synchronization or barrier so may be stale
4738 float v = mCachedVolume;
4739 vl *= v;
4740 vr *= v;
4741 // re-combine into U4.16
4742 vlr = (vr << 16) | (vl & 0xFFFF);
4743 // FIXME look at mute, pause, and stop flags
4744 return vlr;
4745}
Eric Laurenta011e352012-03-29 15:51:43 -07004746
Eric Laurent29864602012-05-08 18:57:51 -07004747status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4748{
4749 if (mState == TERMINATED || mState == PAUSED ||
4750 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4751 (mState == STOPPED)))) {
4752 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4753 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4754 event->cancel();
4755 return INVALID_OPERATION;
4756 }
4757 TrackBase::setSyncEvent(event);
4758 return NO_ERROR;
4759}
4760
John Grossman4ff14ba2012-02-08 16:37:41 -08004761// timed audio tracks
4762
4763sp<AudioFlinger::PlaybackThread::TimedTrack>
4764AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004765 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004766 const sp<Client>& client,
4767 audio_stream_type_t streamType,
4768 uint32_t sampleRate,
4769 audio_format_t format,
4770 uint32_t channelMask,
4771 int frameCount,
4772 const sp<IMemory>& sharedBuffer,
4773 int sessionId) {
4774 if (!client->reserveTimedTrack())
4775 return NULL;
4776
Glenn Kastena0356762012-03-19 10:38:51 -07004777 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004778 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4779 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004780}
4781
4782AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004783 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004784 const sp<Client>& client,
4785 audio_stream_type_t streamType,
4786 uint32_t sampleRate,
4787 audio_format_t format,
4788 uint32_t channelMask,
4789 int frameCount,
4790 const sp<IMemory>& sharedBuffer,
4791 int sessionId)
4792 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004793 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004794 mQueueHeadInFlight(false),
4795 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004796 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004797 mTimedSilenceBuffer(NULL),
4798 mTimedSilenceBufferSize(0),
4799 mTimedAudioOutputOnTime(false),
4800 mMediaTimeTransformValid(false)
4801{
4802 LocalClock lc;
4803 mLocalTimeFreq = lc.getLocalFreq();
4804
4805 mLocalTimeToSampleTransform.a_zero = 0;
4806 mLocalTimeToSampleTransform.b_zero = 0;
4807 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4808 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4809 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4810 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004811
4812 mMediaTimeToSampleTransform.a_zero = 0;
4813 mMediaTimeToSampleTransform.b_zero = 0;
4814 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4815 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4816 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4817 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004818}
4819
4820AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4821 mClient->releaseTimedTrack();
4822 delete [] mTimedSilenceBuffer;
4823}
4824
4825status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4826 size_t size, sp<IMemory>* buffer) {
4827
4828 Mutex::Autolock _l(mTimedBufferQueueLock);
4829
4830 trimTimedBufferQueue_l();
4831
4832 // lazily initialize the shared memory heap for timed buffers
4833 if (mTimedMemoryDealer == NULL) {
4834 const int kTimedBufferHeapSize = 512 << 10;
4835
4836 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4837 "AudioFlingerTimed");
4838 if (mTimedMemoryDealer == NULL)
4839 return NO_MEMORY;
4840 }
4841
4842 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4843 if (newBuffer == NULL) {
4844 newBuffer = mTimedMemoryDealer->allocate(size);
4845 if (newBuffer == NULL)
4846 return NO_MEMORY;
4847 }
4848
4849 *buffer = newBuffer;
4850 return NO_ERROR;
4851}
4852
4853// caller must hold mTimedBufferQueueLock
4854void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4855 int64_t mediaTimeNow;
4856 {
4857 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4858 if (!mMediaTimeTransformValid)
4859 return;
4860
4861 int64_t targetTimeNow;
4862 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4863 ? mCCHelper.getCommonTime(&targetTimeNow)
4864 : mCCHelper.getLocalTime(&targetTimeNow);
4865
4866 if (OK != res)
4867 return;
4868
4869 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4870 &mediaTimeNow)) {
4871 return;
4872 }
4873 }
4874
John Grossman1c345192012-03-27 14:00:17 -07004875 size_t trimEnd;
4876 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004877 int64_t bufEnd;
4878
John Grossmanc95cfbb2012-04-12 11:53:11 -07004879 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4880 // We have a next buffer. Just use its PTS as the PTS of the frame
4881 // following the last frame in this buffer. If the stream is sparse
4882 // (ie, there are deliberate gaps left in the stream which should be
4883 // filled with silence by the TimedAudioTrack), then this can result
4884 // in one extra buffer being left un-trimmed when it could have
4885 // been. In general, this is not typical, and we would rather
4886 // optimized away the TS calculation below for the more common case
4887 // where PTSes are contiguous.
4888 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4889 } else {
4890 // We have no next buffer. Compute the PTS of the frame following
4891 // the last frame in this buffer by computing the duration of of
4892 // this frame in media time units and adding it to the PTS of the
4893 // buffer.
4894 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4895 / mCblk->frameSize;
4896
4897 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4898 &bufEnd)) {
4899 ALOGE("Failed to convert frame count of %lld to media time"
4900 " duration" " (scale factor %d/%u) in %s",
4901 frameCount,
4902 mMediaTimeToSampleTransform.a_to_b_numer,
4903 mMediaTimeToSampleTransform.a_to_b_denom,
4904 __PRETTY_FUNCTION__);
4905 break;
4906 }
4907 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004908 }
John Grossman9fbdee12012-03-26 17:51:46 -07004909
4910 if (bufEnd > mediaTimeNow)
4911 break;
4912
4913 // Is the buffer we want to use in the middle of a mix operation right
4914 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4915 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004916 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004917 mTrimQueueHeadOnRelease = true;
4918 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004919 }
4920
John Grossman9fbdee12012-03-26 17:51:46 -07004921 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004922 if (trimStart < trimEnd) {
4923 // Update the bookkeeping for framesReady()
4924 for (size_t i = trimStart; i < trimEnd; ++i) {
4925 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4926 }
4927
4928 // Now actually remove the buffers from the queue.
4929 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004930 }
4931}
4932
John Grossman1c345192012-03-27 14:00:17 -07004933void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4934 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004935 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4936 "%s called (reason \"%s\"), but timed buffer queue has no"
4937 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004938
4939 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4940 mTimedBufferQueue.removeAt(0);
4941}
4942
4943void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4944 const TimedBuffer& buf,
4945 const char* logTag) {
4946 uint32_t bufBytes = buf.buffer()->size();
4947 uint32_t consumedAlready = buf.position();
4948
Eric Laurentb388e532012-04-14 13:32:48 -07004949 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004950 "Bad bookkeeping while updating frames pending. Timed buffer is"
4951 " only %u bytes long, but claims to have consumed %u"
4952 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004953 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004954
4955 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004956 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4957 "Bad bookkeeping while updating frames pending. Should have at"
4958 " least %u queued frames, but we think we have only %u. (update"
4959 " reason: \"%s\")",
4960 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004961
4962 mFramesPendingInQueue -= bufFrames;
4963}
4964
John Grossman4ff14ba2012-02-08 16:37:41 -08004965status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4966 const sp<IMemory>& buffer, int64_t pts) {
4967
4968 {
4969 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4970 if (!mMediaTimeTransformValid)
4971 return INVALID_OPERATION;
4972 }
4973
4974 Mutex::Autolock _l(mTimedBufferQueueLock);
4975
John Grossman1c345192012-03-27 14:00:17 -07004976 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4977 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004978 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4979
4980 return NO_ERROR;
4981}
4982
4983status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4984 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4985
John Grossman1c345192012-03-27 14:00:17 -07004986 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4987 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4988 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004989
4990 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4991 target == TimedAudioTrack::COMMON_TIME)) {
4992 return BAD_VALUE;
4993 }
4994
4995 Mutex::Autolock lock(mMediaTimeTransformLock);
4996 mMediaTimeTransform = xform;
4997 mMediaTimeTransformTarget = target;
4998 mMediaTimeTransformValid = true;
4999
5000 return NO_ERROR;
5001}
5002
5003#define min(a, b) ((a) < (b) ? (a) : (b))
5004
5005// implementation of getNextBuffer for tracks whose buffers have timestamps
5006status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5007 AudioBufferProvider::Buffer* buffer, int64_t pts)
5008{
5009 if (pts == AudioBufferProvider::kInvalidPTS) {
5010 buffer->raw = 0;
5011 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005012 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005013 return INVALID_OPERATION;
5014 }
5015
John Grossman4ff14ba2012-02-08 16:37:41 -08005016 Mutex::Autolock _l(mTimedBufferQueueLock);
5017
John Grossman9fbdee12012-03-26 17:51:46 -07005018 ALOG_ASSERT(!mQueueHeadInFlight,
5019 "getNextBuffer called without releaseBuffer!");
5020
John Grossman4ff14ba2012-02-08 16:37:41 -08005021 while (true) {
5022
5023 // if we have no timed buffers, then fail
5024 if (mTimedBufferQueue.isEmpty()) {
5025 buffer->raw = 0;
5026 buffer->frameCount = 0;
5027 return NOT_ENOUGH_DATA;
5028 }
5029
5030 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5031
5032 // calculate the PTS of the head of the timed buffer queue expressed in
5033 // local time
5034 int64_t headLocalPTS;
5035 {
5036 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5037
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005038 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005039
5040 if (mMediaTimeTransform.a_to_b_denom == 0) {
5041 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005042 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005043 return NO_ERROR;
5044 }
5045
5046 int64_t transformedPTS;
5047 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5048 &transformedPTS)) {
5049 // the transform failed. this shouldn't happen, but if it does
5050 // then just drop this buffer
5051 ALOGW("timedGetNextBuffer transform failed");
5052 buffer->raw = 0;
5053 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005054 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005055 return NO_ERROR;
5056 }
5057
5058 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5059 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5060 &headLocalPTS)) {
5061 buffer->raw = 0;
5062 buffer->frameCount = 0;
5063 return INVALID_OPERATION;
5064 }
5065 } else {
5066 headLocalPTS = transformedPTS;
5067 }
5068 }
5069
5070 // adjust the head buffer's PTS to reflect the portion of the head buffer
5071 // that has already been consumed
5072 int64_t effectivePTS = headLocalPTS +
5073 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5074
5075 // Calculate the delta in samples between the head of the input buffer
5076 // queue and the start of the next output buffer that will be written.
5077 // If the transformation fails because of over or underflow, it means
5078 // that the sample's position in the output stream is so far out of
5079 // whack that it should just be dropped.
5080 int64_t sampleDelta;
5081 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5082 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005083 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5084 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005085 continue;
5086 }
5087 if (!mLocalTimeToSampleTransform.doForwardTransform(
5088 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005089 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005090 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005091 continue;
5092 }
5093
John Grossman1c345192012-03-27 14:00:17 -07005094 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5095 " sampleDelta=[%d.%08x]",
5096 head.pts(), head.position(), pts,
5097 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5098 + (sampleDelta >> 32)),
5099 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005100
5101 // if the delta between the ideal placement for the next input sample and
5102 // the current output position is within this threshold, then we will
5103 // concatenate the next input samples to the previous output
5104 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005105 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005106
5107 // if this is the first buffer of audio that we're emitting from this track
5108 // then it should be almost exactly on time.
5109 const int64_t kSampleStartupThreshold = 1LL << 32;
5110
5111 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005112 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005113 // the next input is close enough to being on time, so concatenate it
5114 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005115 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005116
John Grossman1c345192012-03-27 14:00:17 -07005117 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5118 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005119 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005120 }
5121
5122 // Looks like our output is not on time. Reset our on timed status.
5123 // Next time we mix samples from our input queue, then should be within
5124 // the StartupThreshold.
5125 mTimedAudioOutputOnTime = false;
5126 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005127 // the gap between the current output position and the proper start of
5128 // the next input sample is too big, so fill it with silence
5129 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5130
John Grossman9fbdee12012-03-26 17:51:46 -07005131 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005132 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5133 return NO_ERROR;
5134 } else {
5135 // the next input sample is late
5136 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5137 size_t onTimeSamplePosition =
5138 head.position() + lateFrames * mCblk->frameSize;
5139
5140 if (onTimeSamplePosition > head.buffer()->size()) {
5141 // all the remaining samples in the head are too late, so
5142 // drop it and move on
5143 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005144 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 continue;
5146 } else {
5147 // skip over the late samples
5148 head.setPosition(onTimeSamplePosition);
5149
5150 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005151 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005152
5153 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5154 return NO_ERROR;
5155 }
5156 }
5157 }
5158}
5159
5160// Yield samples from the timed buffer queue head up to the given output
5161// buffer's capacity.
5162//
5163// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005164void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 AudioBufferProvider::Buffer* buffer) {
5166
5167 const TimedBuffer& head = mTimedBufferQueue[0];
5168
5169 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5170 head.position());
5171
5172 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5173 mCblk->frameSize);
5174 size_t framesRequested = buffer->frameCount;
5175 buffer->frameCount = min(framesLeftInHead, framesRequested);
5176
John Grossman9fbdee12012-03-26 17:51:46 -07005177 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005178 mTimedAudioOutputOnTime = true;
5179}
5180
5181// Yield samples of silence up to the given output buffer's capacity
5182//
5183// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005184void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5186
5187 // lazily allocate a buffer filled with silence
5188 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5189 delete [] mTimedSilenceBuffer;
5190 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5191 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5192 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5193 }
5194
5195 buffer->raw = mTimedSilenceBuffer;
5196 size_t framesRequested = buffer->frameCount;
5197 buffer->frameCount = min(numFrames, framesRequested);
5198
5199 mTimedAudioOutputOnTime = false;
5200}
5201
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005202// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005203void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5204 AudioBufferProvider::Buffer* buffer) {
5205
5206 Mutex::Autolock _l(mTimedBufferQueueLock);
5207
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005208 // If the buffer which was just released is part of the buffer at the head
5209 // of the queue, be sure to update the amt of the buffer which has been
5210 // consumed. If the buffer being returned is not part of the head of the
5211 // queue, its either because the buffer is part of the silence buffer, or
5212 // because the head of the timed queue was trimmed after the mixer called
5213 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005214 if (buffer->raw == mTimedSilenceBuffer) {
5215 ALOG_ASSERT(!mQueueHeadInFlight,
5216 "Queue head in flight during release of silence buffer!");
5217 goto done;
5218 }
5219
5220 ALOG_ASSERT(mQueueHeadInFlight,
5221 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5222 " head in flight.");
5223
5224 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005225 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005226
5227 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005228 void* end = reinterpret_cast<void*>(
5229 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5230 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005231
John Grossman9fbdee12012-03-26 17:51:46 -07005232 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5233 "released buffer not within the head of the timed buffer"
5234 " queue; qHead = [%p, %p], released buffer = %p",
5235 start, end, buffer->raw);
5236
5237 head.setPosition(head.position() +
5238 (buffer->frameCount * mCblk->frameSize));
5239 mQueueHeadInFlight = false;
5240
John Grossman1c345192012-03-27 14:00:17 -07005241 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5242 "Bad bookkeeping during releaseBuffer! Should have at"
5243 " least %u queued frames, but we think we have only %u",
5244 buffer->frameCount, mFramesPendingInQueue);
5245
5246 mFramesPendingInQueue -= buffer->frameCount;
5247
John Grossman9fbdee12012-03-26 17:51:46 -07005248 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5249 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005250 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005251 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005252 }
John Grossman9fbdee12012-03-26 17:51:46 -07005253 } else {
5254 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5255 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005256 }
5257
John Grossman9fbdee12012-03-26 17:51:46 -07005258done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005259 buffer->raw = 0;
5260 buffer->frameCount = 0;
5261}
5262
Glenn Kasten288ed212012-04-25 17:52:27 -07005263size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005264 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005265 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005266}
5267
5268AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5269 : mPTS(0), mPosition(0) {}
5270
5271AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5272 const sp<IMemory>& buffer, int64_t pts)
5273 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5274
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275// ----------------------------------------------------------------------------
5276
5277// RecordTrack constructor must be called with AudioFlinger::mLock held
5278AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005279 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280 const sp<Client>& client,
5281 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005282 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005283 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285 int sessionId)
5286 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005287 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288 mOverflow(false)
5289{
5290 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005291 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5292 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5293 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5294 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5295 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5296 } else {
5297 mCblk->frameSize = sizeof(int8_t);
5298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 }
5300}
5301
5302AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5303{
5304 sp<ThreadBase> thread = mThread.promote();
5305 if (thread != 0) {
5306 AudioSystem::releaseInput(thread->id());
5307 }
5308}
5309
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005310// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005311status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312{
5313 audio_track_cblk_t* cblk = this->cblk();
5314 uint32_t framesAvail;
5315 uint32_t framesReq = buffer->frameCount;
5316
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005317 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005318 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005320 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005321 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 }
5323
5324 framesAvail = cblk->framesAvailable_l();
5325
Glenn Kastenf6b16782011-12-15 09:51:17 -08005326 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327 uint32_t s = cblk->server;
5328 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5329
5330 if (framesReq > framesAvail) {
5331 framesReq = framesAvail;
5332 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005333 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 framesReq = bufferEnd - s;
5335 }
5336
5337 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005338 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339
5340 buffer->frameCount = framesReq;
5341 return NO_ERROR;
5342 }
5343
5344getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005345 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 buffer->frameCount = 0;
5347 return NOT_ENOUGH_DATA;
5348}
5349
Glenn Kasten3acbd052012-02-28 10:39:56 -08005350status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005351 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352{
5353 sp<ThreadBase> thread = mThread.promote();
5354 if (thread != 0) {
5355 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005356 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 } else {
5358 return BAD_VALUE;
5359 }
5360}
5361
5362void AudioFlinger::RecordThread::RecordTrack::stop()
5363{
5364 sp<ThreadBase> thread = mThread.promote();
5365 if (thread != 0) {
5366 RecordThread *recordThread = (RecordThread *)thread.get();
5367 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005368 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005369 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005370 // read from buffer
5371 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 }
5373}
5374
5375void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5376{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005377 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005378 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005380 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381 mSessionId,
5382 mFrameCount,
5383 mState,
5384 mCblk->sampleRate,
5385 mCblk->server,
5386 mCblk->user);
5387}
5388
5389
5390// ----------------------------------------------------------------------------
5391
5392AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005393 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 DuplicatingThread *sourceThread,
5395 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005396 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005397 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005399 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5400 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 mActive(false), mSourceThread(sourceThread)
5402{
5403
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 if (mCblk != NULL) {
5405 mCblk->flags |= CBLK_DIRECTION_OUT;
5406 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 mOutBuffer.frameCount = 0;
5408 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005409 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005410 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5411 mCblk, mBuffer, mCblk->buffers,
5412 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005414 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 }
5416}
5417
5418AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5419{
5420 clearBufferQueue();
5421}
5422
Glenn Kasten3acbd052012-02-28 10:39:56 -08005423status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005424 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005426 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 if (status != NO_ERROR) {
5428 return status;
5429 }
5430
5431 mActive = true;
5432 mRetryCount = 127;
5433 return status;
5434}
5435
5436void AudioFlinger::PlaybackThread::OutputTrack::stop()
5437{
5438 Track::stop();
5439 clearBufferQueue();
5440 mOutBuffer.frameCount = 0;
5441 mActive = false;
5442}
5443
5444bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5445{
5446 Buffer *pInBuffer;
5447 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005448 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 bool outputBufferFull = false;
5450 inBuffer.frameCount = frames;
5451 inBuffer.i16 = data;
5452
5453 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5454
5455 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005456 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 sp<ThreadBase> thread = mThread.promote();
5458 if (thread != 0) {
5459 MixerThread *mixerThread = (MixerThread *)thread.get();
5460 if (mCblk->frameCount > frames){
5461 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5462 uint32_t startFrames = (mCblk->frameCount - frames);
5463 pInBuffer = new Buffer;
5464 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5465 pInBuffer->frameCount = startFrames;
5466 pInBuffer->i16 = pInBuffer->mBuffer;
5467 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5468 mBufferQueue.add(pInBuffer);
5469 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005470 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 }
5472 }
5473 }
5474 }
5475
5476 while (waitTimeLeftMs) {
5477 // First write pending buffers, then new data
5478 if (mBufferQueue.size()) {
5479 pInBuffer = mBufferQueue.itemAt(0);
5480 } else {
5481 pInBuffer = &inBuffer;
5482 }
5483
5484 if (pInBuffer->frameCount == 0) {
5485 break;
5486 }
5487
5488 if (mOutBuffer.frameCount == 0) {
5489 mOutBuffer.frameCount = pInBuffer->frameCount;
5490 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005491 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005492 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 outputBufferFull = true;
5494 break;
5495 }
5496 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5497 if (waitTimeLeftMs >= waitTimeMs) {
5498 waitTimeLeftMs -= waitTimeMs;
5499 } else {
5500 waitTimeLeftMs = 0;
5501 }
5502 }
5503
5504 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5505 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5506 mCblk->stepUser(outFrames);
5507 pInBuffer->frameCount -= outFrames;
5508 pInBuffer->i16 += outFrames * channelCount;
5509 mOutBuffer.frameCount -= outFrames;
5510 mOutBuffer.i16 += outFrames * channelCount;
5511
5512 if (pInBuffer->frameCount == 0) {
5513 if (mBufferQueue.size()) {
5514 mBufferQueue.removeAt(0);
5515 delete [] pInBuffer->mBuffer;
5516 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005517 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 } else {
5519 break;
5520 }
5521 }
5522 }
5523
5524 // If we could not write all frames, allocate a buffer and queue it for next time.
5525 if (inBuffer.frameCount) {
5526 sp<ThreadBase> thread = mThread.promote();
5527 if (thread != 0 && !thread->standby()) {
5528 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5529 pInBuffer = new Buffer;
5530 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5531 pInBuffer->frameCount = inBuffer.frameCount;
5532 pInBuffer->i16 = pInBuffer->mBuffer;
5533 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5534 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005535 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005537 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 }
5539 }
5540 }
5541
5542 // Calling write() with a 0 length buffer, means that no more data will be written:
5543 // If no more buffers are pending, fill output track buffer to make sure it is started
5544 // by output mixer.
5545 if (frames == 0 && mBufferQueue.size() == 0) {
5546 if (mCblk->user < mCblk->frameCount) {
5547 frames = mCblk->frameCount - mCblk->user;
5548 pInBuffer = new Buffer;
5549 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5550 pInBuffer->frameCount = frames;
5551 pInBuffer->i16 = pInBuffer->mBuffer;
5552 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5553 mBufferQueue.add(pInBuffer);
5554 } else if (mActive) {
5555 stop();
5556 }
5557 }
5558
5559 return outputBufferFull;
5560}
5561
5562status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5563{
5564 int active;
5565 status_t result;
5566 audio_track_cblk_t* cblk = mCblk;
5567 uint32_t framesReq = buffer->frameCount;
5568
Steve Block3856b092011-10-20 11:56:00 +01005569// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570 buffer->frameCount = 0;
5571
5572 uint32_t framesAvail = cblk->framesAvailable();
5573
5574
5575 if (framesAvail == 0) {
5576 Mutex::Autolock _l(cblk->lock);
5577 goto start_loop_here;
5578 while (framesAvail == 0) {
5579 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005580 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005581 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005582 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 }
5584 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5585 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005586 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 }
5588 // read the server count again
5589 start_loop_here:
5590 framesAvail = cblk->framesAvailable_l();
5591 }
5592 }
5593
5594// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005595// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005596// }
5597
5598 if (framesReq > framesAvail) {
5599 framesReq = framesAvail;
5600 }
5601
5602 uint32_t u = cblk->user;
5603 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5604
Marco Nelissena1472d92012-03-30 14:36:54 -07005605 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 framesReq = bufferEnd - u;
5607 }
5608
5609 buffer->frameCount = framesReq;
5610 buffer->raw = (void *)cblk->buffer(u);
5611 return NO_ERROR;
5612}
5613
5614
5615void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5616{
5617 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618
5619 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005620 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621 delete [] pBuffer->mBuffer;
5622 delete pBuffer;
5623 }
5624 mBufferQueue.clear();
5625}
5626
5627// ----------------------------------------------------------------------------
5628
5629AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5630 : RefBase(),
5631 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005632 // 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 -07005633 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005634 mPid(pid),
5635 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636{
5637 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5638}
5639
5640// Client destructor must be called with AudioFlinger::mLock held
5641AudioFlinger::Client::~Client()
5642{
5643 mAudioFlinger->removeClient_l(mPid);
5644}
5645
Glenn Kasten435dbe62012-01-30 10:15:48 -08005646sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647{
5648 return mMemoryDealer;
5649}
5650
John Grossman4ff14ba2012-02-08 16:37:41 -08005651// Reserve one of the limited slots for a timed audio track associated
5652// with this client
5653bool AudioFlinger::Client::reserveTimedTrack()
5654{
5655 const int kMaxTimedTracksPerClient = 4;
5656
5657 Mutex::Autolock _l(mTimedTrackLock);
5658
5659 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5660 ALOGW("can not create timed track - pid %d has exceeded the limit",
5661 mPid);
5662 return false;
5663 }
5664
5665 mTimedTrackCount++;
5666 return true;
5667}
5668
5669// Release a slot for a timed audio track
5670void AudioFlinger::Client::releaseTimedTrack()
5671{
5672 Mutex::Autolock _l(mTimedTrackLock);
5673 mTimedTrackCount--;
5674}
5675
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676// ----------------------------------------------------------------------------
5677
5678AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5679 const sp<IAudioFlingerClient>& client,
5680 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005681 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682{
5683}
5684
5685AudioFlinger::NotificationClient::~NotificationClient()
5686{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687}
5688
5689void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5690{
5691 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005692 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693}
5694
5695// ----------------------------------------------------------------------------
5696
5697AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5698 : BnAudioTrack(),
5699 mTrack(track)
5700{
5701}
5702
5703AudioFlinger::TrackHandle::~TrackHandle() {
5704 // just stop the track on deletion, associated resources
5705 // will be freed from the main thread once all pending buffers have
5706 // been played. Unless it's not in the active track list, in which
5707 // case we free everything now...
5708 mTrack->destroy();
5709}
5710
Glenn Kasten90716c52012-01-26 13:40:12 -08005711sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5712 return mTrack->getCblk();
5713}
5714
Glenn Kasten3acbd052012-02-28 10:39:56 -08005715status_t AudioFlinger::TrackHandle::start() {
5716 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717}
5718
5719void AudioFlinger::TrackHandle::stop() {
5720 mTrack->stop();
5721}
5722
5723void AudioFlinger::TrackHandle::flush() {
5724 mTrack->flush();
5725}
5726
5727void AudioFlinger::TrackHandle::mute(bool e) {
5728 mTrack->mute(e);
5729}
5730
5731void AudioFlinger::TrackHandle::pause() {
5732 mTrack->pause();
5733}
5734
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5736{
5737 return mTrack->attachAuxEffect(EffectId);
5738}
5739
John Grossman4ff14ba2012-02-08 16:37:41 -08005740status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5741 sp<IMemory>* buffer) {
5742 if (!mTrack->isTimedTrack())
5743 return INVALID_OPERATION;
5744
5745 PlaybackThread::TimedTrack* tt =
5746 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5747 return tt->allocateTimedBuffer(size, buffer);
5748}
5749
5750status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5751 int64_t pts) {
5752 if (!mTrack->isTimedTrack())
5753 return INVALID_OPERATION;
5754
5755 PlaybackThread::TimedTrack* tt =
5756 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5757 return tt->queueTimedBuffer(buffer, pts);
5758}
5759
5760status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5761 const LinearTransform& xform, int target) {
5762
5763 if (!mTrack->isTimedTrack())
5764 return INVALID_OPERATION;
5765
5766 PlaybackThread::TimedTrack* tt =
5767 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5768 return tt->setMediaTimeTransform(
5769 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5770}
5771
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772status_t AudioFlinger::TrackHandle::onTransact(
5773 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5774{
5775 return BnAudioTrack::onTransact(code, data, reply, flags);
5776}
5777
5778// ----------------------------------------------------------------------------
5779
5780sp<IAudioRecord> AudioFlinger::openRecord(
5781 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005782 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005784 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005785 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005787 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 int *sessionId,
5789 status_t *status)
5790{
5791 sp<RecordThread::RecordTrack> recordTrack;
5792 sp<RecordHandle> recordHandle;
5793 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 status_t lStatus;
5795 RecordThread *thread;
5796 size_t inFrameCount;
5797 int lSessionId;
5798
5799 // check calling permissions
5800 if (!recordingAllowed()) {
5801 lStatus = PERMISSION_DENIED;
5802 goto Exit;
5803 }
5804
5805 // add client to list
5806 { // scope for mLock
5807 Mutex::Autolock _l(mLock);
5808 thread = checkRecordThread_l(input);
5809 if (thread == NULL) {
5810 lStatus = BAD_VALUE;
5811 goto Exit;
5812 }
5813
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005814 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815
5816 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005817 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 lSessionId = *sessionId;
5819 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005820 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 if (sessionId != NULL) {
5822 *sessionId = lSessionId;
5823 }
5824 }
5825 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005826 recordTrack = thread->createRecordTrack_l(client,
5827 sampleRate,
5828 format,
5829 channelMask,
5830 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005831 lSessionId,
5832 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5836 // destructor is called by the TrackBase destructor with mLock held
5837 client.clear();
5838 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 goto Exit;
5840 }
5841
5842 // return to handle to client
5843 recordHandle = new RecordHandle(recordTrack);
5844 lStatus = NO_ERROR;
5845
5846Exit:
5847 if (status) {
5848 *status = lStatus;
5849 }
5850 return recordHandle;
5851}
5852
5853// ----------------------------------------------------------------------------
5854
5855AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5856 : BnAudioRecord(),
5857 mRecordTrack(recordTrack)
5858{
5859}
5860
5861AudioFlinger::RecordHandle::~RecordHandle() {
5862 stop();
5863}
5864
Glenn Kasten90716c52012-01-26 13:40:12 -08005865sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5866 return mRecordTrack->getCblk();
5867}
5868
Glenn Kasten3acbd052012-02-28 10:39:56 -08005869status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005870 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005871 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872}
5873
5874void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005875 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 mRecordTrack->stop();
5877}
5878
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879status_t AudioFlinger::RecordHandle::onTransact(
5880 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5881{
5882 return BnAudioRecord::onTransact(code, data, reply, flags);
5883}
5884
5885// ----------------------------------------------------------------------------
5886
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5888 AudioStreamIn *input,
5889 uint32_t sampleRate,
5890 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005891 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005892 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005893 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005894 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5895 // mRsmpInIndex and mInputBytes set by readInputParameters()
5896 mReqChannelCount(popcount(channels)),
5897 mReqSampleRate(sampleRate)
5898 // mBytesRead is only meaningful while active, and so is cleared in start()
5899 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900{
Glenn Kasten480b4682012-02-28 12:30:08 -08005901 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005902
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 readInputParameters();
5904}
5905
5906
5907AudioFlinger::RecordThread::~RecordThread()
5908{
5909 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005910 delete mResampler;
5911 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912}
5913
5914void AudioFlinger::RecordThread::onFirstRef()
5915{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005916 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917}
5918
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005919status_t AudioFlinger::RecordThread::readyToRun()
5920{
5921 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005922 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005923 return status;
5924}
5925
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926bool AudioFlinger::RecordThread::threadLoop()
5927{
5928 AudioBufferProvider::Buffer buffer;
5929 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005930 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931
Eric Laurent44d98482010-09-30 16:12:31 -07005932 nsecs_t lastWarning = 0;
5933
Eric Laurentfeb0db62011-07-22 09:04:31 -07005934 acquireWakeLock();
5935
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 // start recording
5937 while (!exitPending()) {
5938
5939 processConfigEvents();
5940
5941 { // scope for mLock
5942 Mutex::Autolock _l(mLock);
5943 checkForNewParameters_l();
5944 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5945 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005946 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947 mStandby = true;
5948 }
5949
5950 if (exitPending()) break;
5951
Eric Laurentfeb0db62011-07-22 09:04:31 -07005952 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005953 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 // go to sleep
5955 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005956 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005957 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 continue;
5959 }
5960 if (mActiveTrack != 0) {
5961 if (mActiveTrack->mState == TrackBase::PAUSING) {
5962 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005963 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 mStandby = true;
5965 }
5966 mActiveTrack.clear();
5967 mStartStopCond.broadcast();
5968 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5969 if (mReqChannelCount != mActiveTrack->channelCount()) {
5970 mActiveTrack.clear();
5971 mStartStopCond.broadcast();
5972 } else if (mBytesRead != 0) {
5973 // record start succeeds only if first read from audio input
5974 // succeeds
5975 if (mBytesRead > 0) {
5976 mActiveTrack->mState = TrackBase::ACTIVE;
5977 } else {
5978 mActiveTrack.clear();
5979 }
5980 mStartStopCond.broadcast();
5981 }
5982 mStandby = false;
5983 }
5984 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005985 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986 }
5987
5988 if (mActiveTrack != 0) {
5989 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5990 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005991 unlockEffectChains(effectChains);
5992 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 continue;
5994 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005995 for (size_t i = 0; i < effectChains.size(); i ++) {
5996 effectChains[i]->process_l();
5997 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005998
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006000 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006002 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 // no resampling
6004 while (framesOut) {
6005 size_t framesIn = mFrameCount - mRsmpInIndex;
6006 if (framesIn) {
6007 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6008 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6009 if (framesIn > framesOut)
6010 framesIn = framesOut;
6011 mRsmpInIndex += framesIn;
6012 framesOut -= framesIn;
6013 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006014 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 memcpy(dst, src, framesIn * mFrameSize);
6016 } else {
6017 int16_t *src16 = (int16_t *)src;
6018 int16_t *dst16 = (int16_t *)dst;
6019 if (mChannelCount == 1) {
6020 while (framesIn--) {
6021 *dst16++ = *src16;
6022 *dst16++ = *src16++;
6023 }
6024 } else {
6025 while (framesIn--) {
6026 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6027 src16 += 2;
6028 }
6029 }
6030 }
6031 }
6032 if (framesOut && mFrameCount == mRsmpInIndex) {
6033 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006034 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006035 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 framesOut = 0;
6037 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006038 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 mRsmpInIndex = 0;
6040 }
6041 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006042 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6044 // Force input into standby so that it tries to
6045 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006046 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006047 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048 }
6049 mRsmpInIndex = mFrameCount;
6050 framesOut = 0;
6051 buffer.frameCount = 0;
6052 }
6053 }
6054 }
6055 } else {
6056 // resampling
6057
6058 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6059 // alter output frame count as if we were expecting stereo samples
6060 if (mChannelCount == 1 && mReqChannelCount == 1) {
6061 framesOut >>= 1;
6062 }
6063 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6064 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6065 // are 32 bit aligned which should be always true.
6066 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006067 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 // the resampler always outputs stereo samples: do post stereo to mono conversion
6069 int16_t *src = (int16_t *)mRsmpOutBuffer;
6070 int16_t *dst = buffer.i16;
6071 while (framesOut--) {
6072 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6073 src += 2;
6074 }
6075 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006076 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 }
6078
6079 }
Eric Laurenta011e352012-03-29 15:51:43 -07006080 if (mFramestoDrop == 0) {
6081 mActiveTrack->releaseBuffer(&buffer);
6082 } else {
6083 if (mFramestoDrop > 0) {
6084 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006085 if (mFramestoDrop <= 0) {
6086 clearSyncStartEvent();
6087 }
6088 } else {
6089 mFramestoDrop += buffer.frameCount;
6090 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6091 mSyncStartEvent->isCancelled()) {
6092 ALOGW("Synced record %s, session %d, trigger session %d",
6093 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6094 mActiveTrack->sessionId(),
6095 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6096 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006097 }
6098 }
6099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100 mActiveTrack->overflow();
6101 }
6102 // client isn't retrieving buffers fast enough
6103 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006104 if (!mActiveTrack->setOverflow()) {
6105 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006106 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006107 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006108 lastWarning = now;
6109 }
6110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 // Release the processor for a while before asking for a new buffer.
6112 // This will give the application more chance to read from the buffer and
6113 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006114 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 }
6116 }
Eric Laurentec437d82011-07-26 20:54:46 -07006117 // enable changes in effect chain
6118 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006119 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 }
6121
6122 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006123 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 }
6125 mActiveTrack.clear();
6126
6127 mStartStopCond.broadcast();
6128
Eric Laurentfeb0db62011-07-22 09:04:31 -07006129 releaseWakeLock();
6130
Steve Block3856b092011-10-20 11:56:00 +01006131 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 return false;
6133}
6134
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006135
6136sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6137 const sp<AudioFlinger::Client>& client,
6138 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006139 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006140 int channelMask,
6141 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 int sessionId,
6143 status_t *status)
6144{
6145 sp<RecordTrack> track;
6146 status_t lStatus;
6147
6148 lStatus = initCheck();
6149 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006150 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006151 goto Exit;
6152 }
6153
6154 { // scope for mLock
6155 Mutex::Autolock _l(mLock);
6156
6157 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006158 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006159
Glenn Kasten7378ca52012-01-20 13:44:40 -08006160 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006161 lStatus = NO_MEMORY;
6162 goto Exit;
6163 }
6164
6165 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006166 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6167 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006168 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006169 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6170 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171 }
6172 lStatus = NO_ERROR;
6173
6174Exit:
6175 if (status) {
6176 *status = lStatus;
6177 }
6178 return track;
6179}
6180
Eric Laurenta011e352012-03-29 15:51:43 -07006181status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006182 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006183 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184{
Glenn Kasten58912562012-04-03 10:45:00 -07006185 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006186 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006188
6189 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006190 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006191 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6192 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6193 triggerSession,
6194 recordTrack->sessionId(),
6195 syncStartEventCallback,
6196 this);
Eric Laurent29864602012-05-08 18:57:51 -07006197 // Sync event can be cancelled by the trigger session if the track is not in a
6198 // compatible state in which case we start record immediately
6199 if (mSyncStartEvent->isCancelled()) {
6200 clearSyncStartEvent();
6201 } else {
6202 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6203 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6204 }
Eric Laurenta011e352012-03-29 15:51:43 -07006205 }
6206
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006208 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006209 if (mActiveTrack != 0) {
6210 if (recordTrack != mActiveTrack.get()) {
6211 status = -EBUSY;
6212 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6213 mActiveTrack->mState = TrackBase::ACTIVE;
6214 }
6215 return status;
6216 }
6217
6218 recordTrack->mState = TrackBase::IDLE;
6219 mActiveTrack = recordTrack;
6220 mLock.unlock();
6221 status_t status = AudioSystem::startInput(mId);
6222 mLock.lock();
6223 if (status != NO_ERROR) {
6224 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006225 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 return status;
6227 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 mRsmpInIndex = mFrameCount;
6229 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006230 if (mResampler != NULL) {
6231 mResampler->reset();
6232 }
6233 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006235 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236 mWaitWorkCV.signal();
6237 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006238 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 mActiveTrack.clear();
6240 status = INVALID_OPERATION;
6241 goto startError;
6242 }
6243 mStartStopCond.wait(mLock);
6244 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006245 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 status = BAD_VALUE;
6247 goto startError;
6248 }
Steve Block3856b092011-10-20 11:56:00 +01006249 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 return status;
6251 }
6252startError:
6253 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006254 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 return status;
6256}
6257
Eric Laurenta011e352012-03-29 15:51:43 -07006258void AudioFlinger::RecordThread::clearSyncStartEvent()
6259{
6260 if (mSyncStartEvent != 0) {
6261 mSyncStartEvent->cancel();
6262 }
6263 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006264 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006265}
6266
6267void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6268{
6269 sp<SyncEvent> strongEvent = event.promote();
6270
6271 if (strongEvent != 0) {
6272 RecordThread *me = (RecordThread *)strongEvent->cookie();
6273 me->handleSyncStartEvent(strongEvent);
6274 }
6275}
6276
6277void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6278{
Eric Laurent29864602012-05-08 18:57:51 -07006279 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006280 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6281 // from audio HAL
6282 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006283 }
6284}
6285
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006287 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006288 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006290 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6292 mActiveTrack->mState = TrackBase::PAUSING;
6293 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006294 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 return;
6296 }
6297 mStartStopCond.wait(mLock);
6298 // if we have been restarted, recordTrack == mActiveTrack.get() here
6299 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6300 mLock.unlock();
6301 AudioSystem::stopInput(mId);
6302 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006303 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 }
6305 }
6306 }
6307}
6308
Eric Laurenta011e352012-03-29 15:51:43 -07006309bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6310{
6311 return false;
6312}
6313
6314status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6315{
6316 if (!isValidSyncEvent(event)) {
6317 return BAD_VALUE;
6318 }
6319
6320 Mutex::Autolock _l(mLock);
6321
6322 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6323 mTrack->setSyncEvent(event);
6324 return NO_ERROR;
6325 }
6326 return NAME_NOT_FOUND;
6327}
6328
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6330{
6331 const size_t SIZE = 256;
6332 char buffer[SIZE];
6333 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334
6335 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6336 result.append(buffer);
6337
6338 if (mActiveTrack != 0) {
6339 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006340 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 mActiveTrack->dump(buffer, SIZE);
6342 result.append(buffer);
6343
6344 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6345 result.append(buffer);
6346 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6347 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006348 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 result.append(buffer);
6350 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6351 result.append(buffer);
6352 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6353 result.append(buffer);
6354
6355
6356 } else {
6357 result.append("No record client\n");
6358 }
6359 write(fd, result.string(), result.size());
6360
6361 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006362 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363
6364 return NO_ERROR;
6365}
6366
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006367// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006368status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369{
6370 size_t framesReq = buffer->frameCount;
6371 size_t framesReady = mFrameCount - mRsmpInIndex;
6372 int channelCount;
6373
6374 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006375 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006377 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6379 // Force input into standby so that it tries to
6380 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006381 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006382 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006384 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 buffer->frameCount = 0;
6386 return NOT_ENOUGH_DATA;
6387 }
6388 mRsmpInIndex = 0;
6389 framesReady = mFrameCount;
6390 }
6391
6392 if (framesReq > framesReady) {
6393 framesReq = framesReady;
6394 }
6395
6396 if (mChannelCount == 1 && mReqChannelCount == 2) {
6397 channelCount = 1;
6398 } else {
6399 channelCount = 2;
6400 }
6401 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6402 buffer->frameCount = framesReq;
6403 return NO_ERROR;
6404}
6405
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006406// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6408{
6409 mRsmpInIndex += buffer->frameCount;
6410 buffer->frameCount = 0;
6411}
6412
6413bool AudioFlinger::RecordThread::checkForNewParameters_l()
6414{
6415 bool reconfig = false;
6416
6417 while (!mNewParameters.isEmpty()) {
6418 status_t status = NO_ERROR;
6419 String8 keyValuePair = mNewParameters[0];
6420 AudioParameter param = AudioParameter(keyValuePair);
6421 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006422 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 int reqSamplingRate = mReqSampleRate;
6424 int reqChannelCount = mReqChannelCount;
6425
6426 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6427 reqSamplingRate = value;
6428 reconfig = true;
6429 }
6430 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006431 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 reconfig = true;
6433 }
6434 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006435 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006436 reconfig = true;
6437 }
6438 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6439 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006440 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 // if frame count is changed after track creation
6442 if (mActiveTrack != 0) {
6443 status = INVALID_OPERATION;
6444 } else {
6445 reconfig = true;
6446 }
6447 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006448 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6449 // forward device change to effects that have requested to be
6450 // aware of attached audio device.
6451 for (size_t i = 0; i < mEffectChains.size(); i++) {
6452 mEffectChains[i]->setDevice_l(value);
6453 }
6454 // store input device and output device but do not forward output device to audio HAL.
6455 // Note that status is ignored by the caller for output device
6456 // (see AudioFlinger::setParameters()
6457 if (value & AUDIO_DEVICE_OUT_ALL) {
6458 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6459 status = BAD_VALUE;
6460 } else {
6461 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006462 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6463 if (mTrack != NULL) {
6464 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006465 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006466 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6467 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6468 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006469 }
6470 mDevice |= (uint32_t)value;
6471 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006473 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006475 mInput->stream->common.standby(&mInput->stream->common);
6476 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6477 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006478 }
6479 if (reconfig) {
6480 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006481 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006482 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006483 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006484 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6485 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 status = NO_ERROR;
6487 }
6488 if (status == NO_ERROR) {
6489 readInputParameters();
6490 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6491 }
6492 }
6493 }
6494
6495 mNewParameters.removeAt(0);
6496
6497 mParamStatus = status;
6498 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006499 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6500 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006501 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 }
6503 return reconfig;
6504}
6505
6506String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6507{
Dima Zavinfce7a472011-04-19 22:30:36 -07006508 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006509 String8 out_s8 = String8();
6510
6511 Mutex::Autolock _l(mLock);
6512 if (initCheck() != NO_ERROR) {
6513 return out_s8;
6514 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006515
Dima Zavin799a70e2011-04-18 16:57:27 -07006516 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006517 out_s8 = String8(s);
6518 free(s);
6519 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520}
6521
6522void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6523 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006524 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525
6526 switch (event) {
6527 case AudioSystem::INPUT_OPENED:
6528 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006529 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 desc.samplingRate = mSampleRate;
6531 desc.format = mFormat;
6532 desc.frameCount = mFrameCount;
6533 desc.latency = 0;
6534 param2 = &desc;
6535 break;
6536
6537 case AudioSystem::INPUT_CLOSED:
6538 default:
6539 break;
6540 }
6541 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6542}
6543
6544void AudioFlinger::RecordThread::readInputParameters()
6545{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006546 delete mRsmpInBuffer;
6547 // mRsmpInBuffer is always assigned a new[] below
6548 delete mRsmpOutBuffer;
6549 mRsmpOutBuffer = NULL;
6550 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006551 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552
Dima Zavin799a70e2011-04-18 16:57:27 -07006553 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006554 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6555 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006556 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006557 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006558 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006560 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6562
Glenn Kasten53d76db2012-03-08 12:32:47 -08006563 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 {
6565 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006566 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6567 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 if (mChannelCount == 1 && mReqChannelCount == 2) {
6569 channelCount = 1;
6570 } else {
6571 channelCount = 2;
6572 }
6573 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6574 mResampler->setSampleRate(mSampleRate);
6575 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6576 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6577
6578 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6579 if (mChannelCount == 1 && mReqChannelCount == 1) {
6580 mFrameCount >>= 1;
6581 }
6582
6583 }
6584 mRsmpInIndex = mFrameCount;
6585}
6586
6587unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6588{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006589 Mutex::Autolock _l(mLock);
6590 if (initCheck() != NO_ERROR) {
6591 return 0;
6592 }
6593
Dima Zavin799a70e2011-04-18 16:57:27 -07006594 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595}
6596
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006597uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6598{
6599 Mutex::Autolock _l(mLock);
6600 uint32_t result = 0;
6601 if (getEffectChain_l(sessionId) != 0) {
6602 result = EFFECT_SESSION;
6603 }
6604
6605 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6606 result |= TRACK_SESSION;
6607 }
6608
6609 return result;
6610}
6611
Eric Laurent59bd0da2011-08-01 09:52:20 -07006612AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6613{
6614 Mutex::Autolock _l(mLock);
6615 return mTrack;
6616}
6617
Glenn Kastenaed850d2012-01-26 09:46:34 -08006618AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006619{
6620 Mutex::Autolock _l(mLock);
6621 return mInput;
6622}
6623
6624AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6625{
6626 Mutex::Autolock _l(mLock);
6627 AudioStreamIn *input = mInput;
6628 mInput = NULL;
6629 return input;
6630}
6631
6632// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006633audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006634{
6635 if (mInput == NULL) {
6636 return NULL;
6637 }
6638 return &mInput->stream->common;
6639}
6640
6641
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642// ----------------------------------------------------------------------------
6643
Eric Laurenta4c5a552012-03-29 10:12:40 -07006644audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6645{
6646 if (!settingsAllowed()) {
6647 return 0;
6648 }
6649 Mutex::Autolock _l(mLock);
6650 return loadHwModule_l(name);
6651}
6652
6653// loadHwModule_l() must be called with AudioFlinger::mLock held
6654audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6655{
6656 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6657 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6658 ALOGW("loadHwModule() module %s already loaded", name);
6659 return mAudioHwDevs.keyAt(i);
6660 }
6661 }
6662
Eric Laurenta4c5a552012-03-29 10:12:40 -07006663 audio_hw_device_t *dev;
6664
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006665 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006666 if (rc) {
6667 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6668 return 0;
6669 }
6670
6671 mHardwareStatus = AUDIO_HW_INIT;
6672 rc = dev->init_check(dev);
6673 mHardwareStatus = AUDIO_HW_IDLE;
6674 if (rc) {
6675 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6676 return 0;
6677 }
6678
6679 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6680 (NULL != dev->set_master_volume)) {
6681 AutoMutex lock(mHardwareLock);
6682 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6683 dev->set_master_volume(dev, mMasterVolume);
6684 mHardwareStatus = AUDIO_HW_IDLE;
6685 }
6686
6687 audio_module_handle_t handle = nextUniqueId();
6688 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6689
6690 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006691 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006692
6693 return handle;
6694
6695}
6696
6697audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6698 audio_devices_t *pDevices,
6699 uint32_t *pSamplingRate,
6700 audio_format_t *pFormat,
6701 audio_channel_mask_t *pChannelMask,
6702 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006703 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704{
6705 status_t status;
6706 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006707 struct audio_config config = {
6708 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6709 channel_mask: pChannelMask ? *pChannelMask : 0,
6710 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6711 };
6712 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006713 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714
Eric Laurenta4c5a552012-03-29 10:12:40 -07006715 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6716 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006717 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006718 config.sample_rate,
6719 config.format,
6720 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006721 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722
6723 if (pDevices == NULL || *pDevices == 0) {
6724 return 0;
6725 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006726
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727 Mutex::Autolock _l(mLock);
6728
Eric Laurenta4c5a552012-03-29 10:12:40 -07006729 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006730 if (outHwDev == NULL)
6731 return 0;
6732
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006733 audio_io_handle_t id = nextUniqueId();
6734
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006735 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006736
6737 status = outHwDev->open_output_stream(outHwDev,
6738 id,
6739 *pDevices,
6740 (audio_output_flags_t)flags,
6741 &config,
6742 &outStream);
6743
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006744 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006745 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006746 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006747 config.sample_rate,
6748 config.format,
6749 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750 status);
6751
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006752 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006753 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006754
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006755 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006756 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6757 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006759 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 } else {
6761 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006762 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763 }
6764 mPlaybackThreads.add(id, thread);
6765
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006766 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6767 if (pFormat != NULL) *pFormat = config.format;
6768 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006769 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770
6771 // notify client processes of the new output creation
6772 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006773
6774 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006775 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006776 ALOGI("Using module %d has the primary audio interface", module);
6777 mPrimaryHardwareDev = outHwDev;
6778
6779 AutoMutex lock(mHardwareLock);
6780 mHardwareStatus = AUDIO_HW_SET_MODE;
6781 outHwDev->set_mode(outHwDev, mMode);
6782
6783 // Determine the level of master volume support the primary audio HAL has,
6784 // and set the initial master volume at the same time.
6785 float initialVolume = 1.0;
6786 mMasterVolumeSupportLvl = MVS_NONE;
6787
6788 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6789 if ((NULL != outHwDev->get_master_volume) &&
6790 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6791 mMasterVolumeSupportLvl = MVS_FULL;
6792 } else {
6793 mMasterVolumeSupportLvl = MVS_SETONLY;
6794 initialVolume = 1.0;
6795 }
6796
6797 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6798 if ((NULL == outHwDev->set_master_volume) ||
6799 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6800 mMasterVolumeSupportLvl = MVS_NONE;
6801 }
6802 // now that we have a primary device, initialize master volume on other devices
6803 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6804 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6805
6806 if ((dev != mPrimaryHardwareDev) &&
6807 (NULL != dev->set_master_volume)) {
6808 dev->set_master_volume(dev, initialVolume);
6809 }
6810 }
6811 mHardwareStatus = AUDIO_HW_IDLE;
6812 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6813 ? initialVolume
6814 : 1.0;
6815 mMasterVolume = initialVolume;
6816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 return id;
6818 }
6819
6820 return 0;
6821}
6822
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006823audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6824 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825{
6826 Mutex::Autolock _l(mLock);
6827 MixerThread *thread1 = checkMixerThread_l(output1);
6828 MixerThread *thread2 = checkMixerThread_l(output2);
6829
6830 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006831 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 return 0;
6833 }
6834
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006835 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6837 thread->addOutputTrack(thread2);
6838 mPlaybackThreads.add(id, thread);
6839 // notify client processes of the new output creation
6840 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6841 return id;
6842}
6843
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006844status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845{
6846 // keep strong reference on the playback thread so that
6847 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006848 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849 {
6850 Mutex::Autolock _l(mLock);
6851 thread = checkPlaybackThread_l(output);
6852 if (thread == NULL) {
6853 return BAD_VALUE;
6854 }
6855
Steve Block3856b092011-10-20 11:56:00 +01006856 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006858 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006860 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6862 dupThread->removeOutputTrack((MixerThread *)thread.get());
6863 }
6864 }
6865 }
Glenn Kastena1117922012-01-26 10:53:32 -08006866 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867 mPlaybackThreads.removeItem(output);
6868 }
6869 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006870 // The thread entity (active unit of execution) is no longer running here,
6871 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006873 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006874 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006875 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006876 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006877 out->hwDev->close_output_stream(out->hwDev, out->stream);
6878 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 }
6880 return NO_ERROR;
6881}
6882
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006883status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884{
6885 Mutex::Autolock _l(mLock);
6886 PlaybackThread *thread = checkPlaybackThread_l(output);
6887
6888 if (thread == NULL) {
6889 return BAD_VALUE;
6890 }
6891
Steve Block3856b092011-10-20 11:56:00 +01006892 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 thread->suspend();
6894
6895 return NO_ERROR;
6896}
6897
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006898status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899{
6900 Mutex::Autolock _l(mLock);
6901 PlaybackThread *thread = checkPlaybackThread_l(output);
6902
6903 if (thread == NULL) {
6904 return BAD_VALUE;
6905 }
6906
Steve Block3856b092011-10-20 11:56:00 +01006907 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908
6909 thread->restore();
6910
6911 return NO_ERROR;
6912}
6913
Eric Laurenta4c5a552012-03-29 10:12:40 -07006914audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6915 audio_devices_t *pDevices,
6916 uint32_t *pSamplingRate,
6917 audio_format_t *pFormat,
6918 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919{
6920 status_t status;
6921 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006922 struct audio_config config = {
6923 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6924 channel_mask: pChannelMask ? *pChannelMask : 0,
6925 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6926 };
6927 uint32_t reqSamplingRate = config.sample_rate;
6928 audio_format_t reqFormat = config.format;
6929 audio_channel_mask_t reqChannels = config.channel_mask;
6930 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006931 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932
6933 if (pDevices == NULL || *pDevices == 0) {
6934 return 0;
6935 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006936
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 Mutex::Autolock _l(mLock);
6938
Eric Laurenta4c5a552012-03-29 10:12:40 -07006939 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006940 if (inHwDev == NULL)
6941 return 0;
6942
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006943 audio_io_handle_t id = nextUniqueId();
6944
6945 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006946 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006947 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006948 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006949 config.sample_rate,
6950 config.format,
6951 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 status);
6953
6954 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6955 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6956 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006957 if (status == BAD_VALUE &&
6958 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6959 (config.sample_rate <= 2 * reqSamplingRate) &&
6960 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006961 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006962 inStream = NULL;
6963 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 }
6965
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006966 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006967 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6968
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006969 // Start record thread
6970 // RecorThread require both input and output device indication to forward to audio
6971 // pre processing modules
6972 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6973 thread = new RecordThread(this,
6974 input,
6975 reqSamplingRate,
6976 reqChannels,
6977 id,
6978 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006980 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006981 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006982 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006983 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984
Dima Zavin799a70e2011-04-18 16:57:27 -07006985 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986
6987 // notify client processes of the new input creation
6988 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6989 return id;
6990 }
6991
6992 return 0;
6993}
6994
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006995status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996{
6997 // keep strong reference on the record thread so that
6998 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006999 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007000 {
7001 Mutex::Autolock _l(mLock);
7002 thread = checkRecordThread_l(input);
7003 if (thread == NULL) {
7004 return BAD_VALUE;
7005 }
7006
Steve Block3856b092011-10-20 11:56:00 +01007007 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007008 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 mRecordThreads.removeItem(input);
7010 }
7011 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007012 // The thread entity (active unit of execution) is no longer running here,
7013 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007015 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007016 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007017 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007018 in->hwDev->close_input_stream(in->hwDev, in->stream);
7019 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020
7021 return NO_ERROR;
7022}
7023
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007024status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
7026 Mutex::Autolock _l(mLock);
7027 MixerThread *dstThread = checkMixerThread_l(output);
7028 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007029 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 return BAD_VALUE;
7031 }
7032
Steve Block3856b092011-10-20 11:56:00 +01007033 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7035
7036 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7037 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08007038 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039 MixerThread *srcThread = (MixerThread *)thread;
7040 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 }
Eric Laurentde070132010-07-13 04:45:46 -07007042 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
7044 return NO_ERROR;
7045}
7046
7047
7048int AudioFlinger::newAudioSessionId()
7049{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007050 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051}
7052
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007053void AudioFlinger::acquireAudioSessionId(int audioSession)
7054{
7055 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007056 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007057 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007058 size_t num = mAudioSessionRefs.size();
7059 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007060 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007061 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7062 ref->mCnt++;
7063 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007064 return;
7065 }
7066 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007067 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7068 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007069}
7070
7071void AudioFlinger::releaseAudioSessionId(int audioSession)
7072{
7073 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007074 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007075 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007076 size_t num = mAudioSessionRefs.size();
7077 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007078 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007079 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7080 ref->mCnt--;
7081 ALOGV(" decremented refcount to %d", ref->mCnt);
7082 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007083 mAudioSessionRefs.removeAt(i);
7084 delete ref;
7085 purgeStaleEffects_l();
7086 }
7087 return;
7088 }
7089 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007090 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007091}
7092
7093void AudioFlinger::purgeStaleEffects_l() {
7094
Steve Block3856b092011-10-20 11:56:00 +01007095 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007096
7097 Vector< sp<EffectChain> > chains;
7098
7099 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7100 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7101 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7102 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007103 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7104 chains.push(ec);
7105 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007106 }
7107 }
7108 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7109 sp<RecordThread> t = mRecordThreads.valueAt(i);
7110 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7111 sp<EffectChain> ec = t->mEffectChains[j];
7112 chains.push(ec);
7113 }
7114 }
7115
7116 for (size_t i = 0; i < chains.size(); i++) {
7117 sp<EffectChain> ec = chains[i];
7118 int sessionid = ec->sessionId();
7119 sp<ThreadBase> t = ec->mThread.promote();
7120 if (t == 0) {
7121 continue;
7122 }
7123 size_t numsessionrefs = mAudioSessionRefs.size();
7124 bool found = false;
7125 for (size_t k = 0; k < numsessionrefs; k++) {
7126 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007127 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007128 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007129 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007130 found = true;
7131 break;
7132 }
7133 }
7134 if (!found) {
7135 // remove all effects from the chain
7136 while (ec->mEffects.size()) {
7137 sp<EffectModule> effect = ec->mEffects[0];
7138 effect->unPin();
7139 Mutex::Autolock _l (t->mLock);
7140 t->removeEffect_l(effect);
7141 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7142 sp<EffectHandle> handle = effect->mHandles[j].promote();
7143 if (handle != 0) {
7144 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07007145 if (handle->mHasControl && handle->mEnabled) {
7146 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7147 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007148 }
7149 }
7150 AudioSystem::unregisterEffect(effect->id());
7151 }
7152 }
7153 }
7154 return;
7155}
7156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007158AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
Glenn Kastena1117922012-01-26 10:53:32 -08007160 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161}
7162
7163// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007164AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
7166 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007167 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168}
7169
7170// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007171AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172{
Glenn Kastena1117922012-01-26 10:53:32 -08007173 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174}
7175
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007176uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007178 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179}
7180
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007181AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182{
7183 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7184 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007185 AudioStreamOut *output = thread->getOutput();
7186 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007187 return thread;
7188 }
7189 }
7190 return NULL;
7191}
7192
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007193uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007194{
7195 PlaybackThread *thread = primaryPlaybackThread_l();
7196
7197 if (thread == NULL) {
7198 return 0;
7199 }
7200
7201 return thread->device();
7202}
7203
Eric Laurenta011e352012-03-29 15:51:43 -07007204sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7205 int triggerSession,
7206 int listenerSession,
7207 sync_event_callback_t callBack,
7208 void *cookie)
7209{
7210 Mutex::Autolock _l(mLock);
7211
7212 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7213 status_t playStatus = NAME_NOT_FOUND;
7214 status_t recStatus = NAME_NOT_FOUND;
7215 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7216 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7217 if (playStatus == NO_ERROR) {
7218 return event;
7219 }
7220 }
7221 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7222 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7223 if (recStatus == NO_ERROR) {
7224 return event;
7225 }
7226 }
7227 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7228 mPendingSyncEvents.add(event);
7229 } else {
7230 ALOGV("createSyncEvent() invalid event %d", event->type());
7231 event.clear();
7232 }
7233 return event;
7234}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007235
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236// ----------------------------------------------------------------------------
7237// Effect management
7238// ----------------------------------------------------------------------------
7239
7240
Glenn Kastenf587ba52012-01-26 16:25:10 -08007241status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007242{
7243 Mutex::Autolock _l(mLock);
7244 return EffectQueryNumberEffects(numEffects);
7245}
7246
Glenn Kastenf587ba52012-01-26 16:25:10 -08007247status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248{
7249 Mutex::Autolock _l(mLock);
7250 return EffectQueryEffect(index, descriptor);
7251}
7252
Glenn Kasten5e92a782012-01-30 07:40:52 -08007253status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007254 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
7256 Mutex::Autolock _l(mLock);
7257 return EffectGetDescriptor(pUuid, descriptor);
7258}
7259
7260
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7262 effect_descriptor_t *pDesc,
7263 const sp<IEffectClient>& effectClient,
7264 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007265 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266 int sessionId,
7267 status_t *status,
7268 int *id,
7269 int *enabled)
7270{
7271 status_t lStatus = NO_ERROR;
7272 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007275 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007276 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277
7278 if (pDesc == NULL) {
7279 lStatus = BAD_VALUE;
7280 goto Exit;
7281 }
7282
Eric Laurent84e9a102010-09-23 16:10:16 -07007283 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007284 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007285 lStatus = PERMISSION_DENIED;
7286 goto Exit;
7287 }
7288
Dima Zavinfce7a472011-04-19 22:30:36 -07007289 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007290 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007291 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007292 lStatus = PERMISSION_DENIED;
7293 goto Exit;
7294 }
7295
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007297 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007298 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007299 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007300 lStatus = BAD_VALUE;
7301 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007302 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007303 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007305 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007307 }
7308 }
7309
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 {
7311 Mutex::Autolock _l(mLock);
7312
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313
7314 if (!EffectIsNullUuid(&pDesc->uuid)) {
7315 // if uuid is specified, request effect descriptor
7316 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7317 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007318 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 goto Exit;
7320 }
7321 } else {
7322 // if uuid is not specified, look for an available implementation
7323 // of the required type in effect factory
7324 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007325 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 lStatus = BAD_VALUE;
7327 goto Exit;
7328 }
7329 uint32_t numEffects = 0;
7330 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007331 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 bool found = false;
7333
7334 lStatus = EffectQueryNumberEffects(&numEffects);
7335 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007336 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 goto Exit;
7338 }
7339 for (uint32_t i = 0; i < numEffects; i++) {
7340 lStatus = EffectQueryEffect(i, &desc);
7341 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007342 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 continue;
7344 }
7345 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7346 // If matching type found save effect descriptor. If the session is
7347 // 0 and the effect is not auxiliary, continue enumeration in case
7348 // an auxiliary version of this effect type is available
7349 found = true;
7350 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007351 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7353 break;
7354 }
7355 }
7356 }
7357 if (!found) {
7358 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007359 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 goto Exit;
7361 }
7362 // For same effect type, chose auxiliary version over insert version if
7363 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007364 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7366 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7367 }
7368 }
7369
7370 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007371 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7373 lStatus = INVALID_OPERATION;
7374 goto Exit;
7375 }
7376
Eric Laurent59255e42011-07-27 19:49:51 -07007377 // check recording permission for visualizer
7378 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7379 !recordingAllowed()) {
7380 lStatus = PERMISSION_DENIED;
7381 goto Exit;
7382 }
7383
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 // return effect descriptor
7385 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7386
7387 // If output is not specified try to find a matching audio session ID in one of the
7388 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007389 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7390 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007391 // Note: io is never 0 when creating an effect on an input
7392 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007393 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007394 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7395 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007396 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007397 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007401 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7402 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7403 io = mRecordThreads.keyAt(i);
7404 break;
7405 }
7406 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007407 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007408 // If no output thread contains the requested session ID, default to
7409 // first output. The effect chain will be moved to the correct output
7410 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007411 if (io == 0 && mPlaybackThreads.size()) {
7412 io = mPlaybackThreads.keyAt(0);
7413 }
Steve Block3856b092011-10-20 11:56:00 +01007414 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415 }
7416 ThreadBase *thread = checkRecordThread_l(io);
7417 if (thread == NULL) {
7418 thread = checkPlaybackThread_l(io);
7419 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007420 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007421 lStatus = BAD_VALUE;
7422 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007425
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007426 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007428 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007429 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7430 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 if (handle != 0 && id != NULL) {
7432 *id = handle->id();
7433 }
7434 }
7435
7436Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007437 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 *status = lStatus;
7439 }
7440 return handle;
7441}
7442
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007443status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7444 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007445{
Steve Block3856b092011-10-20 11:56:00 +01007446 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007447 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007448 Mutex::Autolock _l(mLock);
7449 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007450 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007451 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 }
Eric Laurentde070132010-07-13 04:45:46 -07007453 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7454 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007455 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007456 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 }
Eric Laurentde070132010-07-13 04:45:46 -07007458 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7459 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007460 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007461 return BAD_VALUE;
7462 }
7463
7464 Mutex::Autolock _dl(dstThread->mLock);
7465 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007466 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007467
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 return NO_ERROR;
7469}
7470
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007471// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007472status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007473 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007474 AudioFlinger::PlaybackThread *dstThread,
7475 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007476{
Steve Block3856b092011-10-20 11:56:00 +01007477 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007478 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007479
Eric Laurent59255e42011-07-27 19:49:51 -07007480 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007481 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007482 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007483 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007484 return INVALID_OPERATION;
7485 }
7486
Eric Laurent39e94f82010-07-28 01:32:47 -07007487 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007488 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007489 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007490 // removed.
7491 srcThread->removeEffectChain_l(chain);
7492
7493 // transfer all effects one by one so that new effect chain is created on new thread with
7494 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007495 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007496 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007497 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007498 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7499 while (effect != 0) {
7500 srcThread->removeEffect_l(effect);
7501 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007502 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7503 if (effect->state() == EffectModule::ACTIVE ||
7504 effect->state() == EffectModule::STOPPING) {
7505 effect->start();
7506 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007507 // if the move request is not received from audio policy manager, the effect must be
7508 // re-registered with the new strategy and output
7509 if (dstChain == 0) {
7510 dstChain = effect->chain().promote();
7511 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007512 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007513 srcThread->addEffect_l(effect);
7514 return NO_INIT;
7515 }
7516 strategy = dstChain->strategy();
7517 }
7518 if (reRegister) {
7519 AudioSystem::unregisterEffect(effect->id());
7520 AudioSystem::registerEffect(&effect->desc(),
7521 dstOutput,
7522 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007523 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007524 effect->id());
7525 }
Eric Laurentde070132010-07-13 04:45:46 -07007526 effect = chain->getEffectFromId_l(0);
7527 }
7528
7529 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530}
7531
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007532
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007534sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007535 const sp<AudioFlinger::Client>& client,
7536 const sp<IEffectClient>& effectClient,
7537 int32_t priority,
7538 int sessionId,
7539 effect_descriptor_t *desc,
7540 int *enabled,
7541 status_t *status
7542 )
7543{
7544 sp<EffectModule> effect;
7545 sp<EffectHandle> handle;
7546 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007548 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 bool effectCreated = false;
7550 bool effectRegistered = false;
7551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 lStatus = initCheck();
7553 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007554 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 goto Exit;
7556 }
7557
7558 // Do not allow effects with session ID 0 on direct output or duplicating threads
7559 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007560 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007561 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007562 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 lStatus = BAD_VALUE;
7564 goto Exit;
7565 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007566 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007567 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007568 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007569 desc->name, desc->flags, mType);
7570 lStatus = BAD_VALUE;
7571 goto Exit;
7572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573
Steve Block3856b092011-10-20 11:56:00 +01007574 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575
7576 { // scope for mLock
7577 Mutex::Autolock _l(mLock);
7578
7579 // check for existing effect chain with the requested audio session
7580 chain = getEffectChain_l(sessionId);
7581 if (chain == 0) {
7582 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007583 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584 chain = new EffectChain(this, sessionId);
7585 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007586 chain->setStrategy(getStrategyForSession_l(sessionId));
7587 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007589 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 }
7591
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007592 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593
7594 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007595 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007597 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 if (lStatus != NO_ERROR) {
7599 goto Exit;
7600 }
7601 effectRegistered = true;
7602 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007603 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604 lStatus = effect->status();
7605 if (lStatus != NO_ERROR) {
7606 goto Exit;
7607 }
Eric Laurentcab11242010-07-15 12:50:15 -07007608 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 if (lStatus != NO_ERROR) {
7610 goto Exit;
7611 }
7612 effectCreated = true;
7613
7614 effect->setDevice(mDevice);
7615 effect->setMode(mAudioFlinger->getMode());
7616 }
7617 // create effect handle and connect it to effect module
7618 handle = new EffectHandle(effect, client, effectClient, priority);
7619 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007620 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 *enabled = (int)effect->isEnabled();
7622 }
7623 }
7624
7625Exit:
7626 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007627 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007629 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630 }
7631 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007632 AudioSystem::unregisterEffect(effect->id());
7633 }
7634 if (chainCreated) {
7635 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 }
7637 handle.clear();
7638 }
7639
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007640 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 *status = lStatus;
7642 }
7643 return handle;
7644}
7645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007646sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7647{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007649 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007650}
7651
Eric Laurentde070132010-07-13 04:45:46 -07007652// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7653// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007654status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007655{
7656 // check for existing effect chain with the requested audio session
7657 int sessionId = effect->sessionId();
7658 sp<EffectChain> chain = getEffectChain_l(sessionId);
7659 bool chainCreated = false;
7660
7661 if (chain == 0) {
7662 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007663 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007664 chain = new EffectChain(this, sessionId);
7665 addEffectChain_l(chain);
7666 chain->setStrategy(getStrategyForSession_l(sessionId));
7667 chainCreated = true;
7668 }
Steve Block3856b092011-10-20 11:56:00 +01007669 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007670
7671 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007672 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007673 this, effect->desc().name, chain.get());
7674 return BAD_VALUE;
7675 }
7676
7677 status_t status = chain->addEffect_l(effect);
7678 if (status != NO_ERROR) {
7679 if (chainCreated) {
7680 removeEffectChain_l(chain);
7681 }
7682 return status;
7683 }
7684
7685 effect->setDevice(mDevice);
7686 effect->setMode(mAudioFlinger->getMode());
7687 return NO_ERROR;
7688}
7689
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007690void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007691
Steve Block3856b092011-10-20 11:56:00 +01007692 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007693 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007694 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7695 detachAuxEffect_l(effect->id());
7696 }
7697
7698 sp<EffectChain> chain = effect->chain().promote();
7699 if (chain != 0) {
7700 // remove effect chain if removing last effect
7701 if (chain->removeEffect_l(effect) == 0) {
7702 removeEffectChain_l(chain);
7703 }
7704 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007705 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007706 }
7707}
7708
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007709void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007710 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007711{
7712 effectChains = mEffectChains;
7713 for (size_t i = 0; i < mEffectChains.size(); i++) {
7714 mEffectChains[i]->lock();
7715 }
7716}
7717
7718void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007719 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007720{
7721 for (size_t i = 0; i < effectChains.size(); i++) {
7722 effectChains[i]->unlock();
7723 }
7724}
7725
7726sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7727{
7728 Mutex::Autolock _l(mLock);
7729 return getEffectChain_l(sessionId);
7730}
7731
7732sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7733{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007734 size_t size = mEffectChains.size();
7735 for (size_t i = 0; i < size; i++) {
7736 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007737 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738 }
7739 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007740 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007741}
7742
Glenn Kastenf78aee72012-01-04 11:00:47 -08007743void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007744{
7745 Mutex::Autolock _l(mLock);
7746 size_t size = mEffectChains.size();
7747 for (size_t i = 0; i < size; i++) {
7748 mEffectChains[i]->setMode_l(mode);
7749 }
7750}
7751
7752void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007753 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007754 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007755
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007757 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 // delete the effect module if removing last handle on it
7759 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007760 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007761 removeEffect_l(effect);
7762 AudioSystem::unregisterEffect(effect->id());
7763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 }
7765}
7766
7767status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7768{
7769 int session = chain->sessionId();
7770 int16_t *buffer = mMixBuffer;
7771 bool ownsBuffer = false;
7772
Steve Block3856b092011-10-20 11:56:00 +01007773 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 if (session > 0) {
7775 // Only one effect chain can be present in direct output thread and it uses
7776 // the mix buffer as input
7777 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007778 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007779 buffer = new int16_t[numSamples];
7780 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007781 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 ownsBuffer = true;
7783 }
7784
7785 // Attach all tracks with same session ID to this chain.
7786 for (size_t i = 0; i < mTracks.size(); ++i) {
7787 sp<Track> track = mTracks[i];
7788 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007789 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007791 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 }
7793 }
7794
7795 // indicate all active tracks in the chain
7796 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7797 sp<Track> track = mActiveTracks[i].promote();
7798 if (track == 0) continue;
7799 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007800 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007801 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 }
7803 }
7804 }
7805
7806 chain->setInBuffer(buffer, ownsBuffer);
7807 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007808 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007809 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007810 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7811 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007813 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7814 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007815 // Effect chain for other sessions are inserted at beginning of effect
7816 // chains list to be processed before output mix effects. Relative order between other
7817 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 size_t size = mEffectChains.size();
7819 size_t i = 0;
7820 for (i = 0; i < size; i++) {
7821 if (mEffectChains[i]->sessionId() < session) break;
7822 }
7823 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007824 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825
7826 return NO_ERROR;
7827}
7828
7829size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7830{
7831 int session = chain->sessionId();
7832
Steve Block3856b092011-10-20 11:56:00 +01007833 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834
7835 for (size_t i = 0; i < mEffectChains.size(); i++) {
7836 if (chain == mEffectChains[i]) {
7837 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007838 // detach all active tracks from the chain
7839 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7840 sp<Track> track = mActiveTracks[i].promote();
7841 if (track == 0) continue;
7842 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007843 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007844 chain.get(), session);
7845 chain->decActiveTrackCnt();
7846 }
7847 }
7848
Mathias Agopian65ab4712010-07-14 17:59:35 -07007849 // detach all tracks with same session ID from this chain
7850 for (size_t i = 0; i < mTracks.size(); ++i) {
7851 sp<Track> track = mTracks[i];
7852 if (session == track->sessionId()) {
7853 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007854 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855 }
7856 }
Eric Laurentde070132010-07-13 04:45:46 -07007857 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007858 }
7859 }
7860 return mEffectChains.size();
7861}
7862
Eric Laurentde070132010-07-13 04:45:46 -07007863status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7864 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865{
7866 Mutex::Autolock _l(mLock);
7867 return attachAuxEffect_l(track, EffectId);
7868}
7869
Eric Laurentde070132010-07-13 04:45:46 -07007870status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7871 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872{
7873 status_t status = NO_ERROR;
7874
7875 if (EffectId == 0) {
7876 track->setAuxBuffer(0, NULL);
7877 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007878 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7879 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880 if (effect != 0) {
7881 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7882 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7883 } else {
7884 status = INVALID_OPERATION;
7885 }
7886 } else {
7887 status = BAD_VALUE;
7888 }
7889 }
7890 return status;
7891}
7892
7893void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7894{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007895 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007896 sp<Track> track = mTracks[i];
7897 if (track->auxEffectId() == effectId) {
7898 attachAuxEffect_l(track, 0);
7899 }
7900 }
7901}
7902
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007903status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7904{
7905 // only one chain per input thread
7906 if (mEffectChains.size() != 0) {
7907 return INVALID_OPERATION;
7908 }
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007910
7911 chain->setInBuffer(NULL);
7912 chain->setOutBuffer(NULL);
7913
Eric Laurent59255e42011-07-27 19:49:51 -07007914 checkSuspendOnAddEffectChain_l(chain);
7915
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007916 mEffectChains.add(chain);
7917
7918 return NO_ERROR;
7919}
7920
7921size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7922{
Steve Block3856b092011-10-20 11:56:00 +01007923 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007924 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007925 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7926 chain.get(), mEffectChains.size(), this);
7927 if (mEffectChains.size() == 1) {
7928 mEffectChains.removeAt(0);
7929 }
7930 return 0;
7931}
7932
Mathias Agopian65ab4712010-07-14 17:59:35 -07007933// ----------------------------------------------------------------------------
7934// EffectModule implementation
7935// ----------------------------------------------------------------------------
7936
7937#undef LOG_TAG
7938#define LOG_TAG "AudioFlinger::EffectModule"
7939
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007940AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941 const wp<AudioFlinger::EffectChain>& chain,
7942 effect_descriptor_t *desc,
7943 int id,
7944 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007945 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007946 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947{
Steve Block3856b092011-10-20 11:56:00 +01007948 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007950 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 return;
7952 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007953
7954 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7955
7956 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007957 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007958
7959 if (mStatus != NO_ERROR) {
7960 return;
7961 }
7962 lStatus = init();
7963 if (lStatus < 0) {
7964 mStatus = lStatus;
7965 goto Error;
7966 }
7967
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007968 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7969 mPinned = true;
7970 }
Steve Block3856b092011-10-20 11:56:00 +01007971 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007972 return;
7973Error:
7974 EffectRelease(mEffectInterface);
7975 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007976 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977}
7978
7979AudioFlinger::EffectModule::~EffectModule()
7980{
Steve Block3856b092011-10-20 11:56:00 +01007981 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007982 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007983 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7984 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7985 sp<ThreadBase> thread = mThread.promote();
7986 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007987 audio_stream_t *stream = thread->stream();
7988 if (stream != NULL) {
7989 stream->remove_audio_effect(stream, mEffectInterface);
7990 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007991 }
7992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993 // release effect engine
7994 EffectRelease(mEffectInterface);
7995 }
7996}
7997
Glenn Kasten435dbe62012-01-30 10:15:48 -08007998status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999{
8000 status_t status;
8001
8002 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008003 int priority = handle->priority();
8004 size_t size = mHandles.size();
8005 sp<EffectHandle> h;
8006 size_t i;
8007 for (i = 0; i < size; i++) {
8008 h = mHandles[i].promote();
8009 if (h == 0) continue;
8010 if (h->priority() <= priority) break;
8011 }
8012 // if inserted in first place, move effect control from previous owner to this handle
8013 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008014 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008016 enabled = h->enabled();
8017 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 }
Eric Laurent59255e42011-07-27 19:49:51 -07008019 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008020 status = NO_ERROR;
8021 } else {
8022 status = ALREADY_EXISTS;
8023 }
Steve Block3856b092011-10-20 11:56:00 +01008024 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008025 mHandles.insertAt(handle, i);
8026 return status;
8027}
8028
8029size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8030{
8031 Mutex::Autolock _l(mLock);
8032 size_t size = mHandles.size();
8033 size_t i;
8034 for (i = 0; i < size; i++) {
8035 if (mHandles[i] == handle) break;
8036 }
8037 if (i == size) {
8038 return size;
8039 }
Steve Block3856b092011-10-20 11:56:00 +01008040 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07008041
8042 bool enabled = false;
8043 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08008044 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01008045 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07008046 enabled = hdl->enabled();
8047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048 mHandles.removeAt(i);
8049 size = mHandles.size();
8050 // if removed from first place, move effect control from this handle to next in line
8051 if (i == 0 && size != 0) {
8052 sp<EffectHandle> h = mHandles[0].promote();
8053 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008054 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055 }
8056 }
8057
Eric Laurentec437d82011-07-26 20:54:46 -07008058 // Prevent calls to process() and other functions on effect interface from now on.
8059 // The effect engine will be released by the destructor when the last strong reference on
8060 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008061 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008062 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008063 }
8064
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 return size;
8066}
8067
Eric Laurent59255e42011-07-27 19:49:51 -07008068sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8069{
8070 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08008071 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008072}
8073
Glenn Kasten58123c32012-02-03 10:32:24 -08008074void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075{
Glenn Kasten90bebef2012-01-27 15:24:38 -08008076 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077 // keep a strong reference on this EffectModule to avoid calling the
8078 // destructor before we exit
8079 sp<EffectModule> keep(this);
8080 {
8081 sp<ThreadBase> thread = mThread.promote();
8082 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008083 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084 }
8085 }
8086}
8087
8088void AudioFlinger::EffectModule::updateState() {
8089 Mutex::Autolock _l(mLock);
8090
8091 switch (mState) {
8092 case RESTART:
8093 reset_l();
8094 // FALL THROUGH
8095
8096 case STARTING:
8097 // clear auxiliary effect input buffer for next accumulation
8098 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8099 memset(mConfig.inputCfg.buffer.raw,
8100 0,
8101 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8102 }
8103 start_l();
8104 mState = ACTIVE;
8105 break;
8106 case STOPPING:
8107 stop_l();
8108 mDisableWaitCnt = mMaxDisableWaitCnt;
8109 mState = STOPPED;
8110 break;
8111 case STOPPED:
8112 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8113 // turn off sequence.
8114 if (--mDisableWaitCnt == 0) {
8115 reset_l();
8116 mState = IDLE;
8117 }
8118 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008119 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120 break;
8121 }
8122}
8123
8124void AudioFlinger::EffectModule::process()
8125{
8126 Mutex::Autolock _l(mLock);
8127
Eric Laurentec437d82011-07-26 20:54:46 -07008128 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129 mConfig.inputCfg.buffer.raw == NULL ||
8130 mConfig.outputCfg.buffer.raw == NULL) {
8131 return;
8132 }
8133
Eric Laurent8f45bd72010-08-31 13:50:07 -07008134 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8136 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008137 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008139 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 }
8141
8142 // do the actual processing in the effect engine
8143 int ret = (*mEffectInterface)->process(mEffectInterface,
8144 &mConfig.inputCfg.buffer,
8145 &mConfig.outputCfg.buffer);
8146
8147 // force transition to IDLE state when engine is ready
8148 if (mState == STOPPED && ret == -ENODATA) {
8149 mDisableWaitCnt = 1;
8150 }
8151
8152 // clear auxiliary effect input buffer for next accumulation
8153 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008154 memset(mConfig.inputCfg.buffer.raw, 0,
8155 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 }
8157 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008158 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8159 // If an insert effect is idle and input buffer is different from output buffer,
8160 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008162 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008163 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8164 int16_t *in = mConfig.inputCfg.buffer.s16;
8165 int16_t *out = mConfig.outputCfg.buffer.s16;
8166 for (size_t i = 0; i < frameCnt; i++) {
8167 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169 }
8170 }
8171}
8172
8173void AudioFlinger::EffectModule::reset_l()
8174{
8175 if (mEffectInterface == NULL) {
8176 return;
8177 }
8178 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8179}
8180
8181status_t AudioFlinger::EffectModule::configure()
8182{
8183 uint32_t channels;
8184 if (mEffectInterface == NULL) {
8185 return NO_INIT;
8186 }
8187
8188 sp<ThreadBase> thread = mThread.promote();
8189 if (thread == 0) {
8190 return DEAD_OBJECT;
8191 }
8192
8193 // TODO: handle configuration of effects replacing track process
8194 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008195 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008197 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008198 }
8199
8200 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008201 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202 } else {
8203 mConfig.inputCfg.channels = channels;
8204 }
8205 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008206 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8207 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208 mConfig.inputCfg.samplingRate = thread->sampleRate();
8209 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8210 mConfig.inputCfg.bufferProvider.cookie = NULL;
8211 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8212 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8213 mConfig.outputCfg.bufferProvider.cookie = NULL;
8214 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8215 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8216 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8217 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008218 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008219 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220 // - in other sessions:
8221 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8222 // other effect: overwrites output buffer: input buffer == output buffer
8223 // Auxiliary effect:
8224 // accumulates in output buffer: input buffer != output buffer
8225 // Therefore: accumulate <=> input buffer != output buffer
8226 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8227 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8228 } else {
8229 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8230 }
8231 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8232 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8233 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8234 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8235
Steve Block3856b092011-10-20 11:56:00 +01008236 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008237 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8238
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008240 uint32_t size = sizeof(int);
8241 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008242 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008243 sizeof(effect_config_t),
8244 &mConfig,
8245 &size,
8246 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008247 if (status == 0) {
8248 status = cmdStatus;
8249 }
8250
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008251 if (status == 0 &&
8252 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8253 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8254 effect_param_t *p = (effect_param_t *)buf32;
8255
8256 p->psize = sizeof(uint32_t);
8257 p->vsize = sizeof(uint32_t);
8258 size = sizeof(int);
8259 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8260
8261 uint32_t latency = 0;
8262 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8263 if (pbt != NULL) {
8264 latency = pbt->latency_l();
8265 }
8266
8267 *((int32_t *)p->data + 1)= latency;
8268 (*mEffectInterface)->command(mEffectInterface,
8269 EFFECT_CMD_SET_PARAM,
8270 sizeof(effect_param_t) + 8,
8271 &buf32,
8272 &size,
8273 &cmdStatus);
8274 }
8275
Mathias Agopian65ab4712010-07-14 17:59:35 -07008276 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8277 (1000 * mConfig.outputCfg.buffer.frameCount);
8278
8279 return status;
8280}
8281
8282status_t AudioFlinger::EffectModule::init()
8283{
8284 Mutex::Autolock _l(mLock);
8285 if (mEffectInterface == NULL) {
8286 return NO_INIT;
8287 }
8288 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008289 uint32_t size = sizeof(status_t);
8290 status_t status = (*mEffectInterface)->command(mEffectInterface,
8291 EFFECT_CMD_INIT,
8292 0,
8293 NULL,
8294 &size,
8295 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008296 if (status == 0) {
8297 status = cmdStatus;
8298 }
8299 return status;
8300}
8301
Eric Laurentec35a142011-10-05 17:42:25 -07008302status_t AudioFlinger::EffectModule::start()
8303{
8304 Mutex::Autolock _l(mLock);
8305 return start_l();
8306}
8307
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308status_t AudioFlinger::EffectModule::start_l()
8309{
8310 if (mEffectInterface == NULL) {
8311 return NO_INIT;
8312 }
8313 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008314 uint32_t size = sizeof(status_t);
8315 status_t status = (*mEffectInterface)->command(mEffectInterface,
8316 EFFECT_CMD_ENABLE,
8317 0,
8318 NULL,
8319 &size,
8320 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321 if (status == 0) {
8322 status = cmdStatus;
8323 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008324 if (status == 0 &&
8325 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8326 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8327 sp<ThreadBase> thread = mThread.promote();
8328 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008329 audio_stream_t *stream = thread->stream();
8330 if (stream != NULL) {
8331 stream->add_audio_effect(stream, mEffectInterface);
8332 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008333 }
8334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335 return status;
8336}
8337
Eric Laurentec437d82011-07-26 20:54:46 -07008338status_t AudioFlinger::EffectModule::stop()
8339{
8340 Mutex::Autolock _l(mLock);
8341 return stop_l();
8342}
8343
Mathias Agopian65ab4712010-07-14 17:59:35 -07008344status_t AudioFlinger::EffectModule::stop_l()
8345{
8346 if (mEffectInterface == NULL) {
8347 return NO_INIT;
8348 }
8349 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008350 uint32_t size = sizeof(status_t);
8351 status_t status = (*mEffectInterface)->command(mEffectInterface,
8352 EFFECT_CMD_DISABLE,
8353 0,
8354 NULL,
8355 &size,
8356 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 if (status == 0) {
8358 status = cmdStatus;
8359 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008360 if (status == 0 &&
8361 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8362 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8363 sp<ThreadBase> thread = mThread.promote();
8364 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008365 audio_stream_t *stream = thread->stream();
8366 if (stream != NULL) {
8367 stream->remove_audio_effect(stream, mEffectInterface);
8368 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008369 }
8370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371 return status;
8372}
8373
Eric Laurent25f43952010-07-28 05:40:18 -07008374status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8375 uint32_t cmdSize,
8376 void *pCmdData,
8377 uint32_t *replySize,
8378 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008379{
8380 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008381// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382
Eric Laurentec437d82011-07-26 20:54:46 -07008383 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384 return NO_INIT;
8385 }
Eric Laurent25f43952010-07-28 05:40:18 -07008386 status_t status = (*mEffectInterface)->command(mEffectInterface,
8387 cmdCode,
8388 cmdSize,
8389 pCmdData,
8390 replySize,
8391 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008393 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394 for (size_t i = 1; i < mHandles.size(); i++) {
8395 sp<EffectHandle> h = mHandles[i].promote();
8396 if (h != 0) {
8397 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8398 }
8399 }
8400 }
8401 return status;
8402}
8403
8404status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8405{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008406
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008408 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409
8410 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008411 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8412 if (enabled && status != NO_ERROR) {
8413 return status;
8414 }
8415
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416 switch (mState) {
8417 // going from disabled to enabled
8418 case IDLE:
8419 mState = STARTING;
8420 break;
8421 case STOPPED:
8422 mState = RESTART;
8423 break;
8424 case STOPPING:
8425 mState = ACTIVE;
8426 break;
8427
8428 // going from enabled to disabled
8429 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008430 mState = STOPPED;
8431 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008432 case STARTING:
8433 mState = IDLE;
8434 break;
8435 case ACTIVE:
8436 mState = STOPPING;
8437 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008438 case DESTROYED:
8439 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008440 }
8441 for (size_t i = 1; i < mHandles.size(); i++) {
8442 sp<EffectHandle> h = mHandles[i].promote();
8443 if (h != 0) {
8444 h->setEnabled(enabled);
8445 }
8446 }
8447 }
8448 return NO_ERROR;
8449}
8450
Glenn Kastenc59c0042012-02-02 14:06:11 -08008451bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452{
8453 switch (mState) {
8454 case RESTART:
8455 case STARTING:
8456 case ACTIVE:
8457 return true;
8458 case IDLE:
8459 case STOPPING:
8460 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008461 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008462 default:
8463 return false;
8464 }
8465}
8466
Glenn Kastenc59c0042012-02-02 14:06:11 -08008467bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008468{
8469 switch (mState) {
8470 case RESTART:
8471 case ACTIVE:
8472 case STOPPING:
8473 case STOPPED:
8474 return true;
8475 case IDLE:
8476 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008477 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008478 default:
8479 return false;
8480 }
8481}
8482
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8484{
8485 Mutex::Autolock _l(mLock);
8486 status_t status = NO_ERROR;
8487
8488 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8489 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008490 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008491 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8492 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493 status_t cmdStatus;
8494 uint32_t volume[2];
8495 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008496 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497 volume[0] = *left;
8498 volume[1] = *right;
8499 if (controller) {
8500 pVolume = volume;
8501 }
Eric Laurent25f43952010-07-28 05:40:18 -07008502 status = (*mEffectInterface)->command(mEffectInterface,
8503 EFFECT_CMD_SET_VOLUME,
8504 size,
8505 volume,
8506 &size,
8507 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008508 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8509 *left = volume[0];
8510 *right = volume[1];
8511 }
8512 }
8513 return status;
8514}
8515
8516status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8517{
8518 Mutex::Autolock _l(mLock);
8519 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008520 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8521 // audio pre processing modules on RecordThread can receive both output and
8522 // input device indication in the same call
8523 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8524 if (dev) {
8525 status_t cmdStatus;
8526 uint32_t size = sizeof(status_t);
8527
8528 status = (*mEffectInterface)->command(mEffectInterface,
8529 EFFECT_CMD_SET_DEVICE,
8530 sizeof(uint32_t),
8531 &dev,
8532 &size,
8533 &cmdStatus);
8534 if (status == NO_ERROR) {
8535 status = cmdStatus;
8536 }
8537 }
8538 dev = device & AUDIO_DEVICE_IN_ALL;
8539 if (dev) {
8540 status_t cmdStatus;
8541 uint32_t size = sizeof(status_t);
8542
8543 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8544 EFFECT_CMD_SET_INPUT_DEVICE,
8545 sizeof(uint32_t),
8546 &dev,
8547 &size,
8548 &cmdStatus);
8549 if (status2 == NO_ERROR) {
8550 status2 = cmdStatus;
8551 }
8552 if (status == NO_ERROR) {
8553 status = status2;
8554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008555 }
8556 }
8557 return status;
8558}
8559
Glenn Kastenf78aee72012-01-04 11:00:47 -08008560status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008561{
8562 Mutex::Autolock _l(mLock);
8563 status_t status = NO_ERROR;
8564 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008566 uint32_t size = sizeof(status_t);
8567 status = (*mEffectInterface)->command(mEffectInterface,
8568 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008569 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008570 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008571 &size,
8572 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573 if (status == NO_ERROR) {
8574 status = cmdStatus;
8575 }
8576 }
8577 return status;
8578}
8579
Eric Laurent59255e42011-07-27 19:49:51 -07008580void AudioFlinger::EffectModule::setSuspended(bool suspended)
8581{
8582 Mutex::Autolock _l(mLock);
8583 mSuspended = suspended;
8584}
Glenn Kastena3a85482012-01-04 11:01:11 -08008585
8586bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008587{
8588 Mutex::Autolock _l(mLock);
8589 return mSuspended;
8590}
8591
Mathias Agopian65ab4712010-07-14 17:59:35 -07008592status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8593{
8594 const size_t SIZE = 256;
8595 char buffer[SIZE];
8596 String8 result;
8597
8598 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8599 result.append(buffer);
8600
8601 bool locked = tryLock(mLock);
8602 // failed to lock - AudioFlinger is probably deadlocked
8603 if (!locked) {
8604 result.append("\t\tCould not lock Fx mutex:\n");
8605 }
8606
8607 result.append("\t\tSession Status State Engine:\n");
8608 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8609 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8610 result.append(buffer);
8611
8612 result.append("\t\tDescriptor:\n");
8613 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8614 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8615 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8616 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8617 result.append(buffer);
8618 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8619 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8620 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8621 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8622 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008623 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008624 mDescriptor.apiVersion,
8625 mDescriptor.flags);
8626 result.append(buffer);
8627 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8628 mDescriptor.name);
8629 result.append(buffer);
8630 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8631 mDescriptor.implementor);
8632 result.append(buffer);
8633
8634 result.append("\t\t- Input configuration:\n");
8635 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8636 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8637 (uint32_t)mConfig.inputCfg.buffer.raw,
8638 mConfig.inputCfg.buffer.frameCount,
8639 mConfig.inputCfg.samplingRate,
8640 mConfig.inputCfg.channels,
8641 mConfig.inputCfg.format);
8642 result.append(buffer);
8643
8644 result.append("\t\t- Output configuration:\n");
8645 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8646 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8647 (uint32_t)mConfig.outputCfg.buffer.raw,
8648 mConfig.outputCfg.buffer.frameCount,
8649 mConfig.outputCfg.samplingRate,
8650 mConfig.outputCfg.channels,
8651 mConfig.outputCfg.format);
8652 result.append(buffer);
8653
8654 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8655 result.append(buffer);
8656 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8657 for (size_t i = 0; i < mHandles.size(); ++i) {
8658 sp<EffectHandle> handle = mHandles[i].promote();
8659 if (handle != 0) {
8660 handle->dump(buffer, SIZE);
8661 result.append(buffer);
8662 }
8663 }
8664
8665 result.append("\n");
8666
8667 write(fd, result.string(), result.length());
8668
8669 if (locked) {
8670 mLock.unlock();
8671 }
8672
8673 return NO_ERROR;
8674}
8675
8676// ----------------------------------------------------------------------------
8677// EffectHandle implementation
8678// ----------------------------------------------------------------------------
8679
8680#undef LOG_TAG
8681#define LOG_TAG "AudioFlinger::EffectHandle"
8682
8683AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8684 const sp<AudioFlinger::Client>& client,
8685 const sp<IEffectClient>& effectClient,
8686 int32_t priority)
8687 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008688 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008689 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690{
Steve Block3856b092011-10-20 11:56:00 +01008691 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008692
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008693 if (client == 0) {
8694 return;
8695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8697 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8698 if (mCblkMemory != 0) {
8699 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8700
Glenn Kastena0d68332012-01-27 16:47:15 -08008701 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008702 new(mCblk) effect_param_cblk_t();
8703 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008704 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008705 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008706 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 return;
8708 }
8709}
8710
8711AudioFlinger::EffectHandle::~EffectHandle()
8712{
Steve Block3856b092011-10-20 11:56:00 +01008713 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008714 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008715 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008716}
8717
8718status_t AudioFlinger::EffectHandle::enable()
8719{
Steve Block3856b092011-10-20 11:56:00 +01008720 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721 if (!mHasControl) return INVALID_OPERATION;
8722 if (mEffect == 0) return DEAD_OBJECT;
8723
Eric Laurentdb7c0792011-08-10 10:37:50 -07008724 if (mEnabled) {
8725 return NO_ERROR;
8726 }
8727
Eric Laurent59255e42011-07-27 19:49:51 -07008728 mEnabled = true;
8729
8730 sp<ThreadBase> thread = mEffect->thread().promote();
8731 if (thread != 0) {
8732 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8733 }
8734
8735 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8736 if (mEffect->suspended()) {
8737 return NO_ERROR;
8738 }
8739
Eric Laurentdb7c0792011-08-10 10:37:50 -07008740 status_t status = mEffect->setEnabled(true);
8741 if (status != NO_ERROR) {
8742 if (thread != 0) {
8743 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8744 }
8745 mEnabled = false;
8746 }
8747 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748}
8749
8750status_t AudioFlinger::EffectHandle::disable()
8751{
Steve Block3856b092011-10-20 11:56:00 +01008752 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008753 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008754 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755
Eric Laurentdb7c0792011-08-10 10:37:50 -07008756 if (!mEnabled) {
8757 return NO_ERROR;
8758 }
Eric Laurent59255e42011-07-27 19:49:51 -07008759 mEnabled = false;
8760
8761 if (mEffect->suspended()) {
8762 return NO_ERROR;
8763 }
8764
8765 status_t status = mEffect->setEnabled(false);
8766
8767 sp<ThreadBase> thread = mEffect->thread().promote();
8768 if (thread != 0) {
8769 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8770 }
8771
8772 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008773}
8774
8775void AudioFlinger::EffectHandle::disconnect()
8776{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008777 disconnect(true);
8778}
8779
Glenn Kasten58123c32012-02-03 10:32:24 -08008780void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008781{
Glenn Kasten58123c32012-02-03 10:32:24 -08008782 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008783 if (mEffect == 0) {
8784 return;
8785 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008786 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008787
Eric Laurenta85a74a2011-10-19 11:44:54 -07008788 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008789 sp<ThreadBase> thread = mEffect->thread().promote();
8790 if (thread != 0) {
8791 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8792 }
Eric Laurent59255e42011-07-27 19:49:51 -07008793 }
8794
Mathias Agopian65ab4712010-07-14 17:59:35 -07008795 // release sp on module => module destructor can be called now
8796 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008797 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008798 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008799 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008800 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8801 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008802 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008803 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008804 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8805 mClient.clear();
8806 }
8807}
8808
Eric Laurent25f43952010-07-28 05:40:18 -07008809status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8810 uint32_t cmdSize,
8811 void *pCmdData,
8812 uint32_t *replySize,
8813 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814{
Steve Block3856b092011-10-20 11:56:00 +01008815// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008816// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008817
8818 // only get parameter command is permitted for applications not controlling the effect
8819 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8820 return INVALID_OPERATION;
8821 }
8822 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008823 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824
8825 // handle commands that are not forwarded transparently to effect engine
8826 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8827 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8828 // no risk to block the whole media server process or mixer threads is we are stuck here
8829 Mutex::Autolock _l(mCblk->lock);
8830 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8831 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8832 mCblk->serverIndex = 0;
8833 mCblk->clientIndex = 0;
8834 return BAD_VALUE;
8835 }
8836 status_t status = NO_ERROR;
8837 while (mCblk->serverIndex < mCblk->clientIndex) {
8838 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008839 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840 int *p = (int *)(mBuffer + mCblk->serverIndex);
8841 int size = *p++;
8842 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008843 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008844 break;
8845 }
8846 effect_param_t *param = (effect_param_t *)p;
8847 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008848 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008849 mCblk->serverIndex += size;
8850 continue;
8851 }
Eric Laurent25f43952010-07-28 05:40:18 -07008852 uint32_t psize = sizeof(effect_param_t) +
8853 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8854 param->vsize;
8855 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8856 psize,
8857 p,
8858 &rsize,
8859 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008860 // stop at first error encountered
8861 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008862 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008863 *(int *)pReplyData = reply;
8864 break;
8865 } else if (reply != NO_ERROR) {
8866 *(int *)pReplyData = reply;
8867 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008868 }
8869 mCblk->serverIndex += size;
8870 }
8871 mCblk->serverIndex = 0;
8872 mCblk->clientIndex = 0;
8873 return status;
8874 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008875 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008876 return enable();
8877 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008878 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008879 return disable();
8880 }
8881
8882 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8883}
8884
Eric Laurent59255e42011-07-27 19:49:51 -07008885void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008886{
Steve Block3856b092011-10-20 11:56:00 +01008887 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888
8889 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008890 mEnabled = enabled;
8891
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 if (signal && mEffectClient != 0) {
8893 mEffectClient->controlStatusChanged(hasControl);
8894 }
8895}
8896
Eric Laurent25f43952010-07-28 05:40:18 -07008897void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8898 uint32_t cmdSize,
8899 void *pCmdData,
8900 uint32_t replySize,
8901 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008902{
8903 if (mEffectClient != 0) {
8904 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8905 }
8906}
8907
8908
8909
8910void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8911{
8912 if (mEffectClient != 0) {
8913 mEffectClient->enableStatusChanged(enabled);
8914 }
8915}
8916
8917status_t AudioFlinger::EffectHandle::onTransact(
8918 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8919{
8920 return BnEffect::onTransact(code, data, reply, flags);
8921}
8922
8923
8924void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8925{
Glenn Kastena0d68332012-01-27 16:47:15 -08008926 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008927
8928 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008929 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930 mPriority,
8931 mHasControl,
8932 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008933 mCblk ? mCblk->clientIndex : 0,
8934 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 );
8936
8937 if (locked) {
8938 mCblk->lock.unlock();
8939 }
8940}
8941
8942#undef LOG_TAG
8943#define LOG_TAG "AudioFlinger::EffectChain"
8944
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008945AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008946 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008947 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008948 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8949 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008950{
Dima Zavinfce7a472011-04-19 22:30:36 -07008951 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008952 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008953 return;
8954 }
8955 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8956 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008957}
8958
8959AudioFlinger::EffectChain::~EffectChain()
8960{
8961 if (mOwnInBuffer) {
8962 delete mInBuffer;
8963 }
8964
8965}
8966
Eric Laurent59255e42011-07-27 19:49:51 -07008967// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008968sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970 size_t size = mEffects.size();
8971
8972 for (size_t i = 0; i < size; i++) {
8973 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008974 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 }
8976 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008977 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978}
8979
Eric Laurent59255e42011-07-27 19:49:51 -07008980// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008981sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008983 size_t size = mEffects.size();
8984
8985 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008986 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8987 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008988 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 }
8990 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008991 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008992}
8993
Eric Laurent59255e42011-07-27 19:49:51 -07008994// getEffectFromType_l() must be called with ThreadBase::mLock held
8995sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8996 const effect_uuid_t *type)
8997{
Eric Laurent59255e42011-07-27 19:49:51 -07008998 size_t size = mEffects.size();
8999
9000 for (size_t i = 0; i < size; i++) {
9001 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009002 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009003 }
9004 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009005 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009006}
9007
Eric Laurent91b14c42012-05-30 12:30:29 -07009008void AudioFlinger::EffectChain::clearInputBuffer()
9009{
9010 Mutex::Autolock _l(mLock);
9011 sp<ThreadBase> thread = mThread.promote();
9012 if (thread == 0) {
9013 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9014 return;
9015 }
9016 clearInputBuffer_l(thread);
9017}
9018
9019// Must be called with EffectChain::mLock locked
9020void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9021{
9022 size_t numSamples = thread->frameCount() * thread->channelCount();
9023 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9024
9025}
9026
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027// Must be called with EffectChain::mLock locked
9028void AudioFlinger::EffectChain::process_l()
9029{
Eric Laurentdac69112010-09-28 14:09:57 -07009030 sp<ThreadBase> thread = mThread.promote();
9031 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009032 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009033 return;
9034 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009035 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9036 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009037 // always process effects unless no more tracks are on the session and the effect tail
9038 // has been rendered
9039 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009040 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009041 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009042
Eric Laurent544fe9b2011-11-11 15:42:52 -08009043 if (!tracksOnSession && mTailBufferCount == 0) {
9044 doProcess = false;
9045 }
9046
9047 if (activeTrackCnt() == 0) {
9048 // if no track is active and the effect tail has not been rendered,
9049 // the input buffer must be cleared here as the mixer process will not do it
9050 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009051 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009052 if (mTailBufferCount > 0) {
9053 mTailBufferCount--;
9054 }
9055 }
9056 }
Eric Laurentdac69112010-09-28 14:09:57 -07009057 }
9058
Mathias Agopian65ab4712010-07-14 17:59:35 -07009059 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009060 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009061 for (size_t i = 0; i < size; i++) {
9062 mEffects[i]->process();
9063 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009064 }
9065 for (size_t i = 0; i < size; i++) {
9066 mEffects[i]->updateState();
9067 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009068}
9069
Eric Laurentcab11242010-07-15 12:50:15 -07009070// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009071status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072{
9073 effect_descriptor_t desc = effect->desc();
9074 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9075
9076 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009077 effect->setChain(this);
9078 sp<ThreadBase> thread = mThread.promote();
9079 if (thread == 0) {
9080 return NO_INIT;
9081 }
9082 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083
9084 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9085 // Auxiliary effects are inserted at the beginning of mEffects vector as
9086 // they are processed first and accumulated in chain input buffer
9087 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009088
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089 // the input buffer for auxiliary effect contains mono samples in
9090 // 32 bit format. This is to avoid saturation in AudoMixer
9091 // accumulation stage. Saturation is done in EffectModule::process() before
9092 // calling the process in effect engine
9093 size_t numSamples = thread->frameCount();
9094 int32_t *buffer = new int32_t[numSamples];
9095 memset(buffer, 0, numSamples * sizeof(int32_t));
9096 effect->setInBuffer((int16_t *)buffer);
9097 // auxiliary effects output samples to chain input buffer for further processing
9098 // by insert effects
9099 effect->setOutBuffer(mInBuffer);
9100 } else {
9101 // Insert effects are inserted at the end of mEffects vector as they are processed
9102 // after track and auxiliary effects.
9103 // Insert effect order as a function of indicated preference:
9104 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9105 // another effect is present
9106 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9107 // last effect claiming first position
9108 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9109 // first effect claiming last position
9110 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9111 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9112 // already present
9113
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009114 size_t size = mEffects.size();
9115 size_t idx_insert = size;
9116 ssize_t idx_insert_first = -1;
9117 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009118
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009119 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120 effect_descriptor_t d = mEffects[i]->desc();
9121 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9122 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9123 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9124 // check invalid effect chaining combinations
9125 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9126 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009127 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128 return INVALID_OPERATION;
9129 }
9130 // remember position of first insert effect and by default
9131 // select this as insert position for new effect
9132 if (idx_insert == size) {
9133 idx_insert = i;
9134 }
9135 // remember position of last insert effect claiming
9136 // first position
9137 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9138 idx_insert_first = i;
9139 }
9140 // remember position of first insert effect claiming
9141 // last position
9142 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9143 idx_insert_last == -1) {
9144 idx_insert_last = i;
9145 }
9146 }
9147 }
9148
9149 // modify idx_insert from first position if needed
9150 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9151 if (idx_insert_last != -1) {
9152 idx_insert = idx_insert_last;
9153 } else {
9154 idx_insert = size;
9155 }
9156 } else {
9157 if (idx_insert_first != -1) {
9158 idx_insert = idx_insert_first + 1;
9159 }
9160 }
9161
9162 // always read samples from chain input buffer
9163 effect->setInBuffer(mInBuffer);
9164
9165 // if last effect in the chain, output samples to chain
9166 // output buffer, otherwise to chain input buffer
9167 if (idx_insert == size) {
9168 if (idx_insert != 0) {
9169 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9170 mEffects[idx_insert-1]->configure();
9171 }
9172 effect->setOutBuffer(mOutBuffer);
9173 } else {
9174 effect->setOutBuffer(mInBuffer);
9175 }
9176 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009177
Steve Block3856b092011-10-20 11:56:00 +01009178 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179 }
9180 effect->configure();
9181 return NO_ERROR;
9182}
9183
Eric Laurentcab11242010-07-15 12:50:15 -07009184// removeEffect_l() must be called with PlaybackThread::mLock held
9185size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009186{
9187 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009188 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009189 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9190
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009191 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009193 // calling stop here will remove pre-processing effect from the audio HAL.
9194 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9195 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009196 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9197 mEffects[i]->state() == EffectModule::STOPPING) {
9198 mEffects[i]->stop();
9199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009200 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9201 delete[] effect->inBuffer();
9202 } else {
9203 if (i == size - 1 && i != 0) {
9204 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9205 mEffects[i - 1]->configure();
9206 }
9207 }
9208 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009209 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210 break;
9211 }
9212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213
9214 return mEffects.size();
9215}
9216
Eric Laurentcab11242010-07-15 12:50:15 -07009217// setDevice_l() must be called with PlaybackThread::mLock held
9218void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009219{
9220 size_t size = mEffects.size();
9221 for (size_t i = 0; i < size; i++) {
9222 mEffects[i]->setDevice(device);
9223 }
9224}
9225
Eric Laurentcab11242010-07-15 12:50:15 -07009226// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009227void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228{
9229 size_t size = mEffects.size();
9230 for (size_t i = 0; i < size; i++) {
9231 mEffects[i]->setMode(mode);
9232 }
9233}
9234
Eric Laurentcab11242010-07-15 12:50:15 -07009235// setVolume_l() must be called with PlaybackThread::mLock held
9236bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237{
9238 uint32_t newLeft = *left;
9239 uint32_t newRight = *right;
9240 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009241 int ctrlIdx = -1;
9242 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009243
Eric Laurentcab11242010-07-15 12:50:15 -07009244 // first update volume controller
9245 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009246 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009247 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9248 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009249 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009250 break;
9251 }
9252 }
9253
9254 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009255 if (hasControl) {
9256 *left = mNewLeftVolume;
9257 *right = mNewRightVolume;
9258 }
9259 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009260 }
9261
9262 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009263 mLeftVolume = newLeft;
9264 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009265
9266 // second get volume update from volume controller
9267 if (ctrlIdx >= 0) {
9268 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009269 mNewLeftVolume = newLeft;
9270 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009271 }
9272 // then indicate volume to all other effects in chain.
9273 // Pass altered volume to effects before volume controller
9274 // and requested volume to effects after controller
9275 uint32_t lVol = newLeft;
9276 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009277
Mathias Agopian65ab4712010-07-14 17:59:35 -07009278 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009279 if ((int)i == ctrlIdx) continue;
9280 // this also works for ctrlIdx == -1 when there is no volume controller
9281 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 lVol = *left;
9283 rVol = *right;
9284 }
9285 mEffects[i]->setVolume(&lVol, &rVol, false);
9286 }
9287 *left = newLeft;
9288 *right = newRight;
9289
9290 return hasControl;
9291}
9292
Mathias Agopian65ab4712010-07-14 17:59:35 -07009293status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9294{
9295 const size_t SIZE = 256;
9296 char buffer[SIZE];
9297 String8 result;
9298
9299 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9300 result.append(buffer);
9301
9302 bool locked = tryLock(mLock);
9303 // failed to lock - AudioFlinger is probably deadlocked
9304 if (!locked) {
9305 result.append("\tCould not lock mutex:\n");
9306 }
9307
Eric Laurentcab11242010-07-15 12:50:15 -07009308 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9309 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009310 mEffects.size(),
9311 (uint32_t)mInBuffer,
9312 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009313 mActiveTrackCnt);
9314 result.append(buffer);
9315 write(fd, result.string(), result.size());
9316
9317 for (size_t i = 0; i < mEffects.size(); ++i) {
9318 sp<EffectModule> effect = mEffects[i];
9319 if (effect != 0) {
9320 effect->dump(fd, args);
9321 }
9322 }
9323
9324 if (locked) {
9325 mLock.unlock();
9326 }
9327
9328 return NO_ERROR;
9329}
9330
Eric Laurent59255e42011-07-27 19:49:51 -07009331// must be called with ThreadBase::mLock held
9332void AudioFlinger::EffectChain::setEffectSuspended_l(
9333 const effect_uuid_t *type, bool suspend)
9334{
9335 sp<SuspendedEffectDesc> desc;
9336 // use effect type UUID timelow as key as there is no real risk of identical
9337 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009338 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009339 if (suspend) {
9340 if (index >= 0) {
9341 desc = mSuspendedEffects.valueAt(index);
9342 } else {
9343 desc = new SuspendedEffectDesc();
9344 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9345 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009346 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009347 }
9348 if (desc->mRefCount++ == 0) {
9349 sp<EffectModule> effect = getEffectIfEnabled(type);
9350 if (effect != 0) {
9351 desc->mEffect = effect;
9352 effect->setSuspended(true);
9353 effect->setEnabled(false);
9354 }
9355 }
9356 } else {
9357 if (index < 0) {
9358 return;
9359 }
9360 desc = mSuspendedEffects.valueAt(index);
9361 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009362 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009363 desc->mRefCount = 1;
9364 }
9365 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009366 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009367 if (desc->mEffect != 0) {
9368 sp<EffectModule> effect = desc->mEffect.promote();
9369 if (effect != 0) {
9370 effect->setSuspended(false);
9371 sp<EffectHandle> handle = effect->controlHandle();
9372 if (handle != 0) {
9373 effect->setEnabled(handle->enabled());
9374 }
9375 }
9376 desc->mEffect.clear();
9377 }
9378 mSuspendedEffects.removeItemsAt(index);
9379 }
9380 }
9381}
9382
9383// must be called with ThreadBase::mLock held
9384void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9385{
9386 sp<SuspendedEffectDesc> desc;
9387
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009388 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009389 if (suspend) {
9390 if (index >= 0) {
9391 desc = mSuspendedEffects.valueAt(index);
9392 } else {
9393 desc = new SuspendedEffectDesc();
9394 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009395 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009396 }
9397 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009398 Vector< sp<EffectModule> > effects;
9399 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009400 for (size_t i = 0; i < effects.size(); i++) {
9401 setEffectSuspended_l(&effects[i]->desc().type, true);
9402 }
9403 }
9404 } else {
9405 if (index < 0) {
9406 return;
9407 }
9408 desc = mSuspendedEffects.valueAt(index);
9409 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009410 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009411 desc->mRefCount = 1;
9412 }
9413 if (--desc->mRefCount == 0) {
9414 Vector<const effect_uuid_t *> types;
9415 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9416 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9417 continue;
9418 }
9419 types.add(&mSuspendedEffects.valueAt(i)->mType);
9420 }
9421 for (size_t i = 0; i < types.size(); i++) {
9422 setEffectSuspended_l(types[i], false);
9423 }
Steve Block3856b092011-10-20 11:56:00 +01009424 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009425 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9426 }
9427 }
9428}
9429
Eric Laurent6bffdb82011-09-23 08:40:41 -07009430
9431// The volume effect is used for automated tests only
9432#ifndef OPENSL_ES_H_
9433static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9434 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9435const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9436#endif //OPENSL_ES_H_
9437
Eric Laurentdb7c0792011-08-10 10:37:50 -07009438bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9439{
9440 // auxiliary effects and visualizer are never suspended on output mix
9441 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9442 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009443 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9444 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009445 return false;
9446 }
9447 return true;
9448}
9449
Glenn Kastend0539712012-01-30 12:56:03 -08009450void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009451{
Glenn Kastend0539712012-01-30 12:56:03 -08009452 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009453 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009454 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9455 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009456 }
Eric Laurent59255e42011-07-27 19:49:51 -07009457 }
Eric Laurent59255e42011-07-27 19:49:51 -07009458}
9459
9460sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9461 const effect_uuid_t *type)
9462{
Glenn Kasten090f0192012-01-30 13:00:02 -08009463 sp<EffectModule> effect = getEffectFromType_l(type);
9464 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009465}
9466
9467void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9468 bool enabled)
9469{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009470 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009471 if (enabled) {
9472 if (index < 0) {
9473 // if the effect is not suspend check if all effects are suspended
9474 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9475 if (index < 0) {
9476 return;
9477 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009478 if (!isEffectEligibleForSuspend(effect->desc())) {
9479 return;
9480 }
Eric Laurent59255e42011-07-27 19:49:51 -07009481 setEffectSuspended_l(&effect->desc().type, enabled);
9482 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009483 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009484 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009485 return;
9486 }
Eric Laurent59255e42011-07-27 19:49:51 -07009487 }
Steve Block3856b092011-10-20 11:56:00 +01009488 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009489 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009490 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9491 // if effect is requested to suspended but was not yet enabled, supend it now.
9492 if (desc->mEffect == 0) {
9493 desc->mEffect = effect;
9494 effect->setEnabled(false);
9495 effect->setSuspended(true);
9496 }
9497 } else {
9498 if (index < 0) {
9499 return;
9500 }
Steve Block3856b092011-10-20 11:56:00 +01009501 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009502 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009503 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9504 desc->mEffect.clear();
9505 effect->setSuspended(false);
9506 }
9507}
9508
Mathias Agopian65ab4712010-07-14 17:59:35 -07009509#undef LOG_TAG
9510#define LOG_TAG "AudioFlinger"
9511
9512// ----------------------------------------------------------------------------
9513
9514status_t AudioFlinger::onTransact(
9515 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9516{
9517 return BnAudioFlinger::onTransact(code, data, reply, flags);
9518}
9519
Mathias Agopian65ab4712010-07-14 17:59:35 -07009520}; // namespace android