blob: 8b7a48bb5437a0f0775c123aed3dd2ed2e07fa61 [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>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Glenn Kasten58912562012-04-03 10:45:00 -070075#include "FastMixer.h"
76
77// NBAIO implementations
78#include "AudioStreamOutSink.h"
79#include "MonoPipe.h"
80#include "MonoPipeReader.h"
81#include "SourceAudioBufferProvider.h"
82
Glenn Kasten1dc28b72012-04-24 10:01:03 -070083#ifdef HAVE_REQUEST_PRIORITY
84#include "SchedulingPolicyService.h"
85#endif
86
Glenn Kasten58912562012-04-03 10:45:00 -070087#ifdef SOAKER
88#include "Soaker.h"
89#endif
90
Mathias Agopian65ab4712010-07-14 17:59:35 -070091// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
John Grossman1c345192012-03-27 14:00:17 -070093// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
Eric Laurentde070132010-07-13 04:45:46 -0700105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106namespace android {
107
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800108static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
109static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800112static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
114// retry counts for buffer fill timeout
115// 50 * ~20msecs = 1 second
116static const int8_t kMaxTrackRetries = 50;
117static const int8_t kMaxTrackStartupRetries = 50;
118// allow less retry attempts on direct output thread.
119// direct outputs can be a scarce resource in audio hardware and should
120// be released as quickly as possible.
121static const int8_t kMaxTrackRetriesDirect = 2;
122
123static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800124static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Glenn Kasten7dede872011-12-13 11:04:14 -0800126// don't warn about blocked writes or record buffer overflows more often than this
127static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700129// RecordThread loop sleep time upon application overrun or audio HAL read error
130static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Glenn Kasten7dede872011-12-13 11:04:14 -0800132// maximum time to wait for setParameters to complete
133static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700134
Eric Laurent7cafbb32011-11-22 18:50:29 -0800135// minimum sleep time for the mixer thread loop when tracks are active but in underrun
136static const uint32_t kMinThreadSleepTimeUs = 5000;
137// maximum divider applied to the active sleep time in the mixer thread loop
138static const uint32_t kMaxThreadSleepTimeShift = 2;
139
Glenn Kasten58912562012-04-03 10:45:00 -0700140// minimum normal mix buffer size, expressed in milliseconds rather than frames
141static const uint32_t kMinNormalMixBufferSizeMs = 20;
142
John Grossman4ff14ba2012-02-08 16:37:41 -0800143nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800144
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700145// Whether to use fast mixer
146static const enum {
147 FastMixer_Never, // never initialize or use: for debugging only
148 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
149 // normal mixer multiplier is 1
150 FastMixer_Static, // initialize if needed, then use all the time if initialized,
151 // multipler is calculated based on minimum normal mixer buffer size
152 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
153 // multipler is calculated based on minimum normal mixer buffer size
154 // FIXME for FastMixer_Dynamic:
155 // Supporting this option will require fixing HALs that can't handle large writes.
156 // For example, one HAL implementation returns an error from a large write,
157 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
158 // We could either fix the HAL implementations, or provide a wrapper that breaks
159 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
160} kUseFastMixer = FastMixer_Static;
161
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162// ----------------------------------------------------------------------------
163
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700164#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800165// To collect the amplifier usage
166static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800167 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
168 if (service == NULL) {
169 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800170 return;
171 }
172
173 service->addBatteryData(params);
174}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700175#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800176
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700177static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700178{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700179 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 int rc;
181
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700182 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
183 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
184 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
185 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700187 }
188 rc = audio_hw_device_open(mod, dev);
189 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
190 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700193 }
194 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
195 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
196 rc = BAD_VALUE;
197 goto out;
198 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700199 return 0;
200
201out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 *dev = NULL;
203 return rc;
204}
205
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206// ----------------------------------------------------------------------------
207
208AudioFlinger::AudioFlinger()
209 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800210 mPrimaryHardwareDev(NULL),
211 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
212 mMasterVolume(1.0f),
213 mMasterVolumeSupportLvl(MVS_NONE),
214 mMasterMute(false),
215 mNextUniqueId(1),
216 mMode(AUDIO_MODE_INVALID),
217 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700219}
220
221void AudioFlinger::onFirstRef()
222{
Dima Zavin799a70e2011-04-18 16:57:27 -0700223 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700224
Eric Laurent93575202011-01-18 18:39:02 -0800225 Mutex::Autolock _l(mLock);
226
Dima Zavin799a70e2011-04-18 16:57:27 -0700227 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 char val_str[PROPERTY_VALUE_MAX] = { 0 };
229 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
230 uint32_t int_val;
231 if (1 == sscanf(val_str, "%u", &int_val)) {
232 mStandbyTimeInNsecs = milliseconds(int_val);
233 ALOGI("Using %u mSec as standby time.", int_val);
234 } else {
235 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
236 ALOGI("Using default %u mSec as standby time.",
237 (uint32_t)(mStandbyTimeInNsecs / 1000000));
238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240
Eric Laurenta4c5a552012-03-29 10:12:40 -0700241 mMode = AUDIO_MODE_NORMAL;
242 mMasterVolumeSW = 1.0;
243 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800244 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245}
246
247AudioFlinger::~AudioFlinger()
248{
Dima Zavin799a70e2011-04-18 16:57:27 -0700249
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250 while (!mRecordThreads.isEmpty()) {
251 // closeInput() will remove first entry from mRecordThreads
252 closeInput(mRecordThreads.keyAt(0));
253 }
254 while (!mPlaybackThreads.isEmpty()) {
255 // closeOutput() will remove first entry from mPlaybackThreads
256 closeOutput(mPlaybackThreads.keyAt(0));
257 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700258
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800259 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
260 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700261 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
262 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264}
265
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266static const char * const audio_interfaces[] = {
267 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
268 AUDIO_HARDWARE_MODULE_ID_A2DP,
269 AUDIO_HARDWARE_MODULE_ID_USB,
270};
271#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
272
273audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700274{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700275 // if module is 0, the request comes from an old policy manager and we should load
276 // well known modules
277 if (module == 0) {
278 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
279 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
280 loadHwModule_l(audio_interfaces[i]);
281 }
282 } else {
283 // check a match for the requested module handle
284 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
285 if (audioHwdevice != NULL) {
286 return audioHwdevice->hwDevice();
287 }
288 }
289 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700290 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700291 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700292 if ((dev->get_supported_devices(dev) & devices) == devices)
293 return dev;
294 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295
Dima Zavin799a70e2011-04-18 16:57:27 -0700296 return NULL;
297}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
299status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
300{
301 const size_t SIZE = 256;
302 char buffer[SIZE];
303 String8 result;
304
305 result.append("Clients:\n");
306 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800307 sp<Client> client = mClients.valueAt(i).promote();
308 if (client != 0) {
309 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
310 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311 }
312 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700313
314 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800315 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
317 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 result.append(buffer);
320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700321 write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325
326status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
327{
328 const size_t SIZE = 256;
329 char buffer[SIZE];
330 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800331 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332
John Grossman4ff14ba2012-02-08 16:37:41 -0800333 snprintf(buffer, SIZE, "Hardware status: %d\n"
334 "Standby Time mSec: %u\n",
335 hardwareStatus,
336 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337 result.append(buffer);
338 write(fd, result.string(), result.size());
339 return NO_ERROR;
340}
341
342status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
343{
344 const size_t SIZE = 256;
345 char buffer[SIZE];
346 String8 result;
347 snprintf(buffer, SIZE, "Permission Denial: "
348 "can't dump AudioFlinger from pid=%d, uid=%d\n",
349 IPCThreadState::self()->getCallingPid(),
350 IPCThreadState::self()->getCallingUid());
351 result.append(buffer);
352 write(fd, result.string(), result.size());
353 return NO_ERROR;
354}
355
356static bool tryLock(Mutex& mutex)
357{
358 bool locked = false;
359 for (int i = 0; i < kDumpLockRetries; ++i) {
360 if (mutex.tryLock() == NO_ERROR) {
361 locked = true;
362 break;
363 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800364 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365 }
366 return locked;
367}
368
369status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
370{
Glenn Kasten44deb052012-02-05 18:09:08 -0800371 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 dumpPermissionDenial(fd, args);
373 } else {
374 // get state of hardware lock
375 bool hardwareLocked = tryLock(mHardwareLock);
376 if (!hardwareLocked) {
377 String8 result(kHardwareLockedString);
378 write(fd, result.string(), result.size());
379 } else {
380 mHardwareLock.unlock();
381 }
382
383 bool locked = tryLock(mLock);
384
385 // failed to lock - AudioFlinger is probably deadlocked
386 if (!locked) {
387 String8 result(kDeadlockedString);
388 write(fd, result.string(), result.size());
389 }
390
391 dumpClients(fd, args);
392 dumpInternals(fd, args);
393
394 // dump playback threads
395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
396 mPlaybackThreads.valueAt(i)->dump(fd, args);
397 }
398
399 // dump record threads
400 for (size_t i = 0; i < mRecordThreads.size(); i++) {
401 mRecordThreads.valueAt(i)->dump(fd, args);
402 }
403
Dima Zavin799a70e2011-04-18 16:57:27 -0700404 // dump all hardware devs
405 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700406 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 }
409 if (locked) mLock.unlock();
410 }
411 return NO_ERROR;
412}
413
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800414sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
415{
416 // If pid is already in the mClients wp<> map, then use that entry
417 // (for which promote() is always != 0), otherwise create a new entry and Client.
418 sp<Client> client = mClients.valueFor(pid).promote();
419 if (client == 0) {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
424 return client;
425}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426
427// IAudioFlinger interface
428
429
430sp<IAudioTrack> AudioFlinger::createTrack(
431 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800432 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800434 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700435 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800437 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800439 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800440 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 int *sessionId,
442 status_t *status)
443{
444 sp<PlaybackThread::Track> track;
445 sp<TrackHandle> trackHandle;
446 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 status_t lStatus;
448 int lSessionId;
449
Glenn Kasten263709e2012-01-06 08:40:01 -0800450 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
451 // but if someone uses binder directly they could bypass that and cause us to crash
452 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000453 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 lStatus = BAD_VALUE;
455 goto Exit;
456 }
457
458 {
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700461 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800468 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469
Steve Block3856b092011-10-20 11:56:00 +0100470 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700471 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700472 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700473 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
474 if (mPlaybackThreads.keyAt(i) != output) {
475 // prevent same audio session on different output threads
476 uint32_t sessions = t->hasAudioSession(*sessionId);
477 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000478 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700479 lStatus = BAD_VALUE;
480 goto Exit;
481 }
482 // check if an effect with same session ID is waiting for a track to be created
483 if (sessions & PlaybackThread::EFFECT_SESSION) {
484 effectThread = t.get();
485 }
Eric Laurentde070132010-07-13 04:45:46 -0700486 }
487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488 lSessionId = *sessionId;
489 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700490 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700491 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492 if (sessionId != NULL) {
493 *sessionId = lSessionId;
494 }
495 }
Steve Block3856b092011-10-20 11:56:00 +0100496 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497
498 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800499 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700500
501 // move effect chain to this output thread if an effect on same session was waiting
502 // for a track to be created
503 if (lStatus == NO_ERROR && effectThread != NULL) {
504 Mutex::Autolock _dl(thread->mLock);
505 Mutex::Autolock _sl(effectThread->mLock);
506 moveEffectChain_l(lSessionId, effectThread, thread, true);
507 }
Eric Laurenta011e352012-03-29 15:51:43 -0700508
509 // Look for sync events awaiting for a session to be used.
510 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
511 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
512 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
513 track->setSyncEvent(mPendingSyncEvents[i]);
514 mPendingSyncEvents.removeAt(i);
515 i--;
516 }
517 }
518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 }
520 if (lStatus == NO_ERROR) {
521 trackHandle = new TrackHandle(track);
522 } else {
523 // remove local strong reference to Client before deleting the Track so that the Client
524 // destructor is called by the TrackBase destructor with mLock held
525 client.clear();
526 track.clear();
527 }
528
529Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700530 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 *status = lStatus;
532 }
533 return trackHandle;
534}
535
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800536uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537{
538 Mutex::Autolock _l(mLock);
539 PlaybackThread *thread = checkPlaybackThread_l(output);
540 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000541 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 return 0;
543 }
544 return thread->sampleRate();
545}
546
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548{
549 Mutex::Autolock _l(mLock);
550 PlaybackThread *thread = checkPlaybackThread_l(output);
551 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000552 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 return 0;
554 }
555 return thread->channelCount();
556}
557
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800558audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559{
560 Mutex::Autolock _l(mLock);
561 PlaybackThread *thread = checkPlaybackThread_l(output);
562 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000563 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800564 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 }
566 return thread->format();
567}
568
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570{
571 Mutex::Autolock _l(mLock);
572 PlaybackThread *thread = checkPlaybackThread_l(output);
573 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 return 0;
576 }
Glenn Kasten58912562012-04-03 10:45:00 -0700577 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
578 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return thread->frameCount();
580}
581
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800582uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583{
584 Mutex::Autolock _l(mLock);
585 PlaybackThread *thread = checkPlaybackThread_l(output);
586 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000587 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return 0;
589 }
590 return thread->latency();
591}
592
593status_t AudioFlinger::setMasterVolume(float value)
594{
Eric Laurenta1884f92011-08-23 08:25:03 -0700595 status_t ret = initCheck();
596 if (ret != NO_ERROR) {
597 return ret;
598 }
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 // check calling permissions
601 if (!settingsAllowed()) {
602 return PERMISSION_DENIED;
603 }
604
John Grossman4ff14ba2012-02-08 16:37:41 -0800605 float swmv = value;
606
Eric Laurenta4c5a552012-03-29 10:12:40 -0700607 Mutex::Autolock _l(mLock);
608
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800610 if (MVS_NONE != mMasterVolumeSupportLvl) {
611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
612 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700613 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800614
615 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
616 if (NULL != dev->set_master_volume) {
617 dev->set_master_volume(dev, value);
618 }
619 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800620 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800621
622 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624
John Grossman4ff14ba2012-02-08 16:37:41 -0800625 mMasterVolume = value;
626 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800627 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700628 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
630 return NO_ERROR;
631}
632
Glenn Kastenf78aee72012-01-04 11:00:47 -0800633status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634{
Eric Laurenta1884f92011-08-23 08:25:03 -0700635 status_t ret = initCheck();
636 if (ret != NO_ERROR) {
637 return ret;
638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
640 // check calling permissions
641 if (!settingsAllowed()) {
642 return PERMISSION_DENIED;
643 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800644 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000645 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 return BAD_VALUE;
647 }
648
649 { // scope for the lock
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700652 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mHardwareStatus = AUDIO_HW_IDLE;
654 }
655
656 if (NO_ERROR == ret) {
657 Mutex::Autolock _l(mLock);
658 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800659 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700660 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 }
662
663 return ret;
664}
665
666status_t AudioFlinger::setMicMute(bool state)
667{
Eric Laurenta1884f92011-08-23 08:25:03 -0700668 status_t ret = initCheck();
669 if (ret != NO_ERROR) {
670 return ret;
671 }
672
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 // check calling permissions
674 if (!settingsAllowed()) {
675 return PERMISSION_DENIED;
676 }
677
678 AutoMutex lock(mHardwareLock);
679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700680 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700695 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_IDLE;
697 return state;
698}
699
700status_t AudioFlinger::setMasterMute(bool muted)
701{
702 // check calling permissions
703 if (!settingsAllowed()) {
704 return PERMISSION_DENIED;
705 }
706
Eric Laurent93575202011-01-18 18:39:02 -0800707 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800708 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800710 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700711 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712
713 return NO_ERROR;
714}
715
716float AudioFlinger::masterVolume() const
717{
Glenn Kasten98067102011-12-13 11:47:54 -0800718 Mutex::Autolock _l(mLock);
719 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720}
721
John Grossman4ff14ba2012-02-08 16:37:41 -0800722float AudioFlinger::masterVolumeSW() const
723{
724 Mutex::Autolock _l(mLock);
725 return masterVolumeSW_l();
726}
727
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728bool AudioFlinger::masterMute() const
729{
Glenn Kasten98067102011-12-13 11:47:54 -0800730 Mutex::Autolock _l(mLock);
731 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732}
733
John Grossman4ff14ba2012-02-08 16:37:41 -0800734float AudioFlinger::masterVolume_l() const
735{
736 if (MVS_FULL == mMasterVolumeSupportLvl) {
737 float ret_val;
738 AutoMutex lock(mHardwareLock);
739
740 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800741 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
742 (NULL != mPrimaryHardwareDev->get_master_volume),
743 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800744
745 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
746 mHardwareStatus = AUDIO_HW_IDLE;
747 return ret_val;
748 }
749
750 return mMasterVolume;
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
754 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755{
756 // check calling permissions
757 if (!settingsAllowed()) {
758 return PERMISSION_DENIED;
759 }
760
Glenn Kasten263709e2012-01-06 08:40:01 -0800761 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000762 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 return BAD_VALUE;
764 }
765
766 AutoMutex lock(mLock);
767 PlaybackThread *thread = NULL;
768 if (output) {
769 thread = checkPlaybackThread_l(output);
770 if (thread == NULL) {
771 return BAD_VALUE;
772 }
773 }
774
775 mStreamTypes[stream].volume = value;
776
777 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700779 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 }
781 } else {
782 thread->setStreamVolume(stream, value);
783 }
784
785 return NO_ERROR;
786}
787
Glenn Kastenfff6d712012-01-12 16:38:12 -0800788status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 // check calling permissions
791 if (!settingsAllowed()) {
792 return PERMISSION_DENIED;
793 }
794
Glenn Kasten263709e2012-01-06 08:40:01 -0800795 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700796 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000797 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 return BAD_VALUE;
799 }
800
Eric Laurent93575202011-01-18 18:39:02 -0800801 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 mStreamTypes[stream].mute = muted;
803 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700804 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805
806 return NO_ERROR;
807}
808
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800809float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 return 0.0f;
813 }
814
815 AutoMutex lock(mLock);
816 float volume;
817 if (output) {
818 PlaybackThread *thread = checkPlaybackThread_l(output);
819 if (thread == NULL) {
820 return 0.0f;
821 }
822 volume = thread->streamVolume(stream);
823 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800824 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 }
826
827 return volume;
828}
829
Glenn Kastenfff6d712012-01-12 16:38:12 -0800830bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
Glenn Kasten263709e2012-01-06 08:40:01 -0800832 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return true;
834 }
835
Glenn Kasten6637baa2012-01-09 09:40:36 -0800836 AutoMutex lock(mLock);
837 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838}
839
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800840status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800842 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
844 // check calling permissions
845 if (!settingsAllowed()) {
846 return PERMISSION_DENIED;
847 }
848
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 // ioHandle == 0 means the parameters are global to the audio hardware interface
850 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700851 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700852 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800853 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 AutoMutex lock(mHardwareLock);
855 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
856 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
857 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
858 status_t result = dev->set_parameters(dev, keyValuePairs.string());
859 final_result = result ?: final_result;
860 }
861 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800862 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
864 AudioParameter param = AudioParameter(keyValuePairs);
865 String8 value;
866 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700867 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
868 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700869 for (size_t i = 0; i < mRecordThreads.size(); i++) {
870 sp<RecordThread> thread = mRecordThreads.valueAt(i);
871 RecordThread::RecordTrack *track = thread->track();
872 if (track != NULL) {
873 audio_devices_t device = (audio_devices_t)(
874 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700875 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 thread->setEffectSuspended(FX_IID_AEC,
877 suspend,
878 track->sessionId());
879 thread->setEffectSuspended(FX_IID_NS,
880 suspend,
881 track->sessionId());
882 }
883 }
Eric Laurentbee53372011-08-29 12:42:48 -0700884 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 }
886 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700887 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 }
889
890 // hold a strong ref on thread in case closeOutput() or closeInput() is called
891 // and the thread is exited once the lock is released
892 sp<ThreadBase> thread;
893 {
894 Mutex::Autolock _l(mLock);
895 thread = checkPlaybackThread_l(ioHandle);
896 if (thread == NULL) {
897 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800898 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700899 // indicate output device change to all input threads for pre processing
900 AudioParameter param = AudioParameter(keyValuePairs);
901 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700902 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
903 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700904 for (size_t i = 0; i < mRecordThreads.size(); i++) {
905 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
906 }
907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 }
909 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800910 if (thread != 0) {
911 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 }
913 return BAD_VALUE;
914}
915
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800916String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800918// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
920
Eric Laurenta4c5a552012-03-29 10:12:40 -0700921 Mutex::Autolock _l(mLock);
922
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700924 String8 out_s8;
925
Dima Zavin799a70e2011-04-18 16:57:27 -0700926 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800927 char *s;
928 {
929 AutoMutex lock(mHardwareLock);
930 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700931 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800932 s = dev->get_parameters(dev, keys.string());
933 mHardwareStatus = AUDIO_HW_IDLE;
934 }
John Grossmanef7740b2012-02-09 11:28:36 -0800935 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700936 free(s);
937 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700938 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 }
940
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
942 if (playbackThread != NULL) {
943 return playbackThread->getParameters(keys);
944 }
945 RecordThread *recordThread = checkRecordThread_l(ioHandle);
946 if (recordThread != NULL) {
947 return recordThread->getParameters(keys);
948 }
949 return String8("");
950}
951
Glenn Kastenf587ba52012-01-26 16:25:10 -0800952size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953{
Eric Laurenta1884f92011-08-23 08:25:03 -0700954 status_t ret = initCheck();
955 if (ret != NO_ERROR) {
956 return 0;
957 }
958
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800959 AutoMutex lock(mHardwareLock);
960 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700961 struct audio_config config = {
962 sample_rate: sampleRate,
963 channel_mask: audio_channel_in_mask_from_count(channelCount),
964 format: format,
965 };
966 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800967 mHardwareStatus = AUDIO_HW_IDLE;
968 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969}
970
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800971unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
973 if (ioHandle == 0) {
974 return 0;
975 }
976
977 Mutex::Autolock _l(mLock);
978
979 RecordThread *recordThread = checkRecordThread_l(ioHandle);
980 if (recordThread != NULL) {
981 return recordThread->getInputFramesLost();
982 }
983 return 0;
984}
985
986status_t AudioFlinger::setVoiceVolume(float value)
987{
Eric Laurenta1884f92011-08-23 08:25:03 -0700988 status_t ret = initCheck();
989 if (ret != NO_ERROR) {
990 return ret;
991 }
992
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 // check calling permissions
994 if (!settingsAllowed()) {
995 return PERMISSION_DENIED;
996 }
997
998 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800999 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001000 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 mHardwareStatus = AUDIO_HW_IDLE;
1002
1003 return ret;
1004}
1005
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001006status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1007 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008{
1009 status_t status;
1010
1011 Mutex::Autolock _l(mLock);
1012
1013 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1014 if (playbackThread != NULL) {
1015 return playbackThread->getRenderPosition(halFrames, dspFrames);
1016 }
1017
1018 return BAD_VALUE;
1019}
1020
1021void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1022{
1023
1024 Mutex::Autolock _l(mLock);
1025
Glenn Kastenbb001922012-02-03 11:10:26 -08001026 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 if (mNotificationClients.indexOfKey(pid) < 0) {
1028 sp<NotificationClient> notificationClient = new NotificationClient(this,
1029 client,
1030 pid);
Steve Block3856b092011-10-20 11:56:00 +01001031 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032
1033 mNotificationClients.add(pid, notificationClient);
1034
1035 sp<IBinder> binder = client->asBinder();
1036 binder->linkToDeath(notificationClient);
1037
1038 // the config change is always sent from playback or record threads to avoid deadlock
1039 // with AudioSystem::gLock
1040 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1041 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1042 }
1043
1044 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1045 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1046 }
1047 }
1048}
1049
1050void AudioFlinger::removeNotificationClient(pid_t pid)
1051{
1052 Mutex::Autolock _l(mLock);
1053
Glenn Kastena3b09252012-01-20 09:19:01 -08001054 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001055
Steve Block3856b092011-10-20 11:56:00 +01001056 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001057 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001059 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001060 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001061 ALOGV(" pid %d @ %d", ref->mPid, i);
1062 if (ref->mPid == pid) {
1063 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001064 mAudioSessionRefs.removeAt(i);
1065 delete ref;
1066 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001068 } else {
1069 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 }
1071 }
1072 if (removed) {
1073 purgeStaleEffects_l();
1074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075}
1076
1077// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001078void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079{
1080 size_t size = mNotificationClients.size();
1081 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001082 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1083 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 }
1085}
1086
1087// removeClient_l() must be called with AudioFlinger::mLock held
1088void AudioFlinger::removeClient_l(pid_t pid)
1089{
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 mClients.removeItem(pid);
1092}
1093
1094
1095// ----------------------------------------------------------------------------
1096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001097AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1098 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001100 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001101 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001102 // mChannelMask
1103 mChannelCount(0),
1104 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1105 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001106 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001107 mDevice(device),
1108 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109{
1110}
1111
1112AudioFlinger::ThreadBase::~ThreadBase()
1113{
1114 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001115 // do not lock the mutex in destructor
1116 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001117 if (mPowerManager != 0) {
1118 sp<IBinder> binder = mPowerManager->asBinder();
1119 binder->unlinkToDeath(mDeathRecipient);
1120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121}
1122
1123void AudioFlinger::ThreadBase::exit()
1124{
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001127 // This lock prevents the following race in thread (uniprocessor for illustration):
1128 // if (!exitPending()) {
1129 // // context switch from here to exit()
1130 // // exit() calls requestExit(), what exitPending() observes
1131 // // exit() calls signal(), which is dropped since no waiters
1132 // // context switch back from exit() to here
1133 // mWaitWorkCV.wait(...);
1134 // // now thread is hung
1135 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001136 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 requestExit();
1138 mWaitWorkCV.signal();
1139 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001140 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1141 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 requestExitAndWait();
1143}
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1146{
1147 status_t status;
1148
Steve Block3856b092011-10-20 11:56:00 +01001149 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 Mutex::Autolock _l(mLock);
1151
1152 mNewParameters.add(keyValuePairs);
1153 mWaitWorkCV.signal();
1154 // wait condition with timeout in case the thread loop has exited
1155 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001156 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 status = mParamStatus;
1158 mWaitWorkCV.signal();
1159 } else {
1160 status = TIMED_OUT;
1161 }
1162 return status;
1163}
1164
1165void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1166{
1167 Mutex::Autolock _l(mLock);
1168 sendConfigEvent_l(event, param);
1169}
1170
1171// sendConfigEvent_l() must be called with ThreadBase::mLock held
1172void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1173{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001174 ConfigEvent configEvent;
1175 configEvent.mEvent = event;
1176 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 mWaitWorkCV.signal();
1180}
1181
1182void AudioFlinger::ThreadBase::processConfigEvents()
1183{
1184 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001185 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001186 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001187 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 mConfigEvents.removeAt(0);
1189 // release mLock before locking AudioFlinger mLock: lock order is always
1190 // AudioFlinger then ThreadBase to avoid cross deadlock
1191 mLock.unlock();
1192 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001193 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 mLock.lock();
1196 }
1197 mLock.unlock();
1198}
1199
1200status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1201{
1202 const size_t SIZE = 256;
1203 char buffer[SIZE];
1204 String8 result;
1205
1206 bool locked = tryLock(mLock);
1207 if (!locked) {
1208 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1209 write(fd, buffer, strlen(buffer));
1210 }
1211
Eric Laurent612bbb52012-03-14 15:03:26 -07001212 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1213 result.append(buffer);
1214 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1215 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1217 result.append(buffer);
1218 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1219 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001220 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1221 result.append(buffer);
1222 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 result.append(buffer);
1224 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1225 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001226 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1227 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1229 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001230 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 result.append(buffer);
1232
1233 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1234 result.append(buffer);
1235 result.append(" Index Command");
1236 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1237 snprintf(buffer, SIZE, "\n %02d ", i);
1238 result.append(buffer);
1239 result.append(mNewParameters[i]);
1240 }
1241
1242 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1243 result.append(buffer);
1244 snprintf(buffer, SIZE, " Index event param\n");
1245 result.append(buffer);
1246 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001247 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 result.append(buffer);
1249 }
1250 result.append("\n");
1251
1252 write(fd, result.string(), result.size());
1253
1254 if (locked) {
1255 mLock.unlock();
1256 }
1257 return NO_ERROR;
1258}
1259
Eric Laurent1d2bff02011-07-24 17:49:51 -07001260status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1261{
1262 const size_t SIZE = 256;
1263 char buffer[SIZE];
1264 String8 result;
1265
1266 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1267 write(fd, buffer, strlen(buffer));
1268
1269 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1270 sp<EffectChain> chain = mEffectChains[i];
1271 if (chain != 0) {
1272 chain->dump(fd, args);
1273 }
1274 }
1275 return NO_ERROR;
1276}
1277
Eric Laurentfeb0db62011-07-22 09:04:31 -07001278void AudioFlinger::ThreadBase::acquireWakeLock()
1279{
1280 Mutex::Autolock _l(mLock);
1281 acquireWakeLock_l();
1282}
1283
1284void AudioFlinger::ThreadBase::acquireWakeLock_l()
1285{
1286 if (mPowerManager == 0) {
1287 // use checkService() to avoid blocking if power service is not up yet
1288 sp<IBinder> binder =
1289 defaultServiceManager()->checkService(String16("power"));
1290 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001291 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292 } else {
1293 mPowerManager = interface_cast<IPowerManager>(binder);
1294 binder->linkToDeath(mDeathRecipient);
1295 }
1296 }
1297 if (mPowerManager != 0) {
1298 sp<IBinder> binder = new BBinder();
1299 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1300 binder,
1301 String16(mName));
1302 if (status == NO_ERROR) {
1303 mWakeLockToken = binder;
1304 }
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001306 }
1307}
1308
1309void AudioFlinger::ThreadBase::releaseWakeLock()
1310{
1311 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001312 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001313}
1314
1315void AudioFlinger::ThreadBase::releaseWakeLock_l()
1316{
1317 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001319 if (mPowerManager != 0) {
1320 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1321 }
1322 mWakeLockToken.clear();
1323 }
1324}
1325
1326void AudioFlinger::ThreadBase::clearPowerManager()
1327{
1328 Mutex::Autolock _l(mLock);
1329 releaseWakeLock_l();
1330 mPowerManager.clear();
1331}
1332
1333void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1334{
1335 sp<ThreadBase> thread = mThread.promote();
1336 if (thread != 0) {
1337 thread->clearPowerManager();
1338 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001339 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001340}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001341
Eric Laurent59255e42011-07-27 19:49:51 -07001342void AudioFlinger::ThreadBase::setEffectSuspended(
1343 const effect_uuid_t *type, bool suspend, int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
1346 setEffectSuspended_l(type, suspend, sessionId);
1347}
1348
1349void AudioFlinger::ThreadBase::setEffectSuspended_l(
1350 const effect_uuid_t *type, bool suspend, int sessionId)
1351{
Glenn Kasten090f0192012-01-30 13:00:02 -08001352 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001353 if (chain != 0) {
1354 if (type != NULL) {
1355 chain->setEffectSuspended_l(type, suspend);
1356 } else {
1357 chain->setEffectSuspendedAll_l(suspend);
1358 }
1359 }
1360
1361 updateSuspendedSessions_l(type, suspend, sessionId);
1362}
1363
1364void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1365{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001366 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001367 if (index < 0) {
1368 return;
1369 }
1370
1371 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1372 mSuspendedSessions.editValueAt(index);
1373
1374 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001375 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001376 for (int j = 0; j < desc->mRefCount; j++) {
1377 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1378 chain->setEffectSuspendedAll_l(true);
1379 } else {
Steve Block3856b092011-10-20 11:56:00 +01001380 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001381 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001382 chain->setEffectSuspended_l(&desc->mType, true);
1383 }
1384 }
1385 }
1386}
1387
Eric Laurent59255e42011-07-27 19:49:51 -07001388void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1389 bool suspend,
1390 int sessionId)
1391{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001392 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001393
1394 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1395
1396 if (suspend) {
1397 if (index >= 0) {
1398 sessionEffects = mSuspendedSessions.editValueAt(index);
1399 } else {
1400 mSuspendedSessions.add(sessionId, sessionEffects);
1401 }
1402 } else {
1403 if (index < 0) {
1404 return;
1405 }
1406 sessionEffects = mSuspendedSessions.editValueAt(index);
1407 }
1408
1409
1410 int key = EffectChain::kKeyForSuspendAll;
1411 if (type != NULL) {
1412 key = type->timeLow;
1413 }
1414 index = sessionEffects.indexOfKey(key);
1415
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001416 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001417 if (suspend) {
1418 if (index >= 0) {
1419 desc = sessionEffects.valueAt(index);
1420 } else {
1421 desc = new SuspendedSessionDesc();
1422 if (type != NULL) {
1423 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1424 }
1425 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001426 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001427 }
1428 desc->mRefCount++;
1429 } else {
1430 if (index < 0) {
1431 return;
1432 }
1433 desc = sessionEffects.valueAt(index);
1434 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001435 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001436 sessionEffects.removeItemsAt(index);
1437 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001438 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001439 sessionId);
1440 mSuspendedSessions.removeItem(sessionId);
1441 }
1442 }
1443 }
1444 if (!sessionEffects.isEmpty()) {
1445 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1446 }
1447}
1448
1449void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1450 bool enabled,
1451 int sessionId)
1452{
1453 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001454 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1455}
Eric Laurent59255e42011-07-27 19:49:51 -07001456
Eric Laurenta85a74a2011-10-19 11:44:54 -07001457void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1458 bool enabled,
1459 int sessionId)
1460{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001461 if (mType != RECORD) {
1462 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1463 // another session. This gives the priority to well behaved effect control panels
1464 // and applications not using global effects.
1465 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1466 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1467 }
1468 }
Eric Laurent59255e42011-07-27 19:49:51 -07001469
1470 sp<EffectChain> chain = getEffectChain_l(sessionId);
1471 if (chain != 0) {
1472 chain->checkSuspendOnEffectEnabled(effect, enabled);
1473 }
1474}
1475
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476// ----------------------------------------------------------------------------
1477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001478AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1479 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001480 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001481 uint32_t device,
1482 type_t type)
1483 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001484 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1485 // Assumes constructor is called by AudioFlinger with it's mLock held,
1486 // but it would be safer to explicitly pass initial masterMute as parameter
1487 mMasterMute(audioFlinger->masterMute_l()),
1488 // mStreamTypes[] initialized in constructor body
1489 mOutput(output),
1490 // Assumes constructor is called by AudioFlinger with it's mLock held,
1491 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001492 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001493 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001494 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001495 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001496 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001497 // index 0 is reserved for normal mixer's submix
1498 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499{
Glenn Kasten480b4682012-02-28 12:30:08 -08001500 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 readOutputParameters();
1503
Glenn Kasten263709e2012-01-06 08:40:01 -08001504 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001505 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1506 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1507 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001508 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1509 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001511 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1512 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513}
1514
1515AudioFlinger::PlaybackThread::~PlaybackThread()
1516{
1517 delete [] mMixBuffer;
1518}
1519
1520status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1521{
1522 dumpInternals(fd, args);
1523 dumpTracks(fd, args);
1524 dumpEffectChains(fd, args);
1525 return NO_ERROR;
1526}
1527
1528status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1529{
1530 const size_t SIZE = 256;
1531 char buffer[SIZE];
1532 String8 result;
1533
Glenn Kasten58912562012-04-03 10:45:00 -07001534 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1535 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1536 const stream_type_t *st = &mStreamTypes[i];
1537 if (i > 0) {
1538 result.appendFormat(", ");
1539 }
1540 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1541 if (st->mute) {
1542 result.append("M");
1543 }
1544 }
1545 result.append("\n");
1546 write(fd, result.string(), result.length());
1547 result.clear();
1548
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1550 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001551 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 for (size_t i = 0; i < mTracks.size(); ++i) {
1553 sp<Track> track = mTracks[i];
1554 if (track != 0) {
1555 track->dump(buffer, SIZE);
1556 result.append(buffer);
1557 }
1558 }
1559
1560 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1561 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001562 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001564 sp<Track> track = mActiveTracks[i].promote();
1565 if (track != 0) {
1566 track->dump(buffer, SIZE);
1567 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569 }
1570 write(fd, result.string(), result.size());
1571 return NO_ERROR;
1572}
1573
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1575{
1576 const size_t SIZE = 256;
1577 char buffer[SIZE];
1578 String8 result;
1579
1580 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1581 result.append(buffer);
1582 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1583 result.append(buffer);
1584 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1585 result.append(buffer);
1586 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1587 result.append(buffer);
1588 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1589 result.append(buffer);
1590 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1591 result.append(buffer);
1592 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1593 result.append(buffer);
1594 write(fd, result.string(), result.size());
1595
1596 dumpBase(fd, args);
1597
1598 return NO_ERROR;
1599}
1600
1601// Thread virtuals
1602status_t AudioFlinger::PlaybackThread::readyToRun()
1603{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001604 status_t status = initCheck();
1605 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001606 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001607 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001608 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001610 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611}
1612
1613void AudioFlinger::PlaybackThread::onFirstRef()
1614{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001615 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616}
1617
1618// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001619sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001621 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001623 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001624 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 int frameCount,
1626 const sp<IMemory>& sharedBuffer,
1627 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001628 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001629 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 status_t *status)
1631{
1632 sp<Track> track;
1633 status_t lStatus;
1634
Glenn Kasten73d22752012-03-19 13:38:30 -07001635 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1636
1637 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001638 if (flags & IAudioFlinger::TRACK_FAST) {
1639 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001640 // not timed
1641 (!isTimed) &&
1642 // either of these use cases:
1643 (
1644 // use case 1: shared buffer with any frame count
1645 (
1646 (sharedBuffer != 0)
1647 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001648 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001649 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001650 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001651 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001652 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001653 )
1654 ) &&
1655 // PCM data
1656 audio_is_linear_pcm(format) &&
1657 // mono or stereo
1658 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1659 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001660#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001661 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001662 (sampleRate == mSampleRate) &&
1663#endif
1664 // normal mixer has an associated fast mixer
1665 hasFastMixer() &&
1666 // there are sufficient fast track slots available
1667 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001668 // FIXME test that MixerThread for this fast track has a capable output HAL
1669 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001670 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001671 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1672 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001673 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001674 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001675 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001676 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 } else {
1678 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001679 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1680 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1681 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1682 audio_is_linear_pcm(format),
1683 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001684 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001685 // For compatibility with AudioTrack calculation, buffer depth is forced
1686 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1687 // This is probably too conservative, but legacy application code may depend on it.
1688 // If you change this calculation, also review the start threshold which is related.
1689 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1690 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1691 if (minBufCount < 2) {
1692 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001693 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001694 int minFrameCount = mNormalFrameCount * minBufCount;
1695 if (frameCount < minFrameCount) {
1696 frameCount = minFrameCount;
1697 }
1698 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001699 }
1700
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001702 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1703 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001704 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001705 "for output %p with format %d",
1706 sampleRate, format, channelMask, mOutput, mFormat);
1707 lStatus = BAD_VALUE;
1708 goto Exit;
1709 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 }
1711 } else {
1712 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1713 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001714 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 lStatus = BAD_VALUE;
1716 goto Exit;
1717 }
1718 }
1719
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001720 lStatus = initCheck();
1721 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001722 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 goto Exit;
1724 }
1725
1726 { // scope for mLock
1727 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001728
1729 // all tracks in same audio session must share the same routing strategy otherwise
1730 // conflicts will happen when tracks are moved from one output to another by audio policy
1731 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001732 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001733 for (size_t i = 0; i < mTracks.size(); ++i) {
1734 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001735 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001736 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001737 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001738 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001739 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001740 lStatus = BAD_VALUE;
1741 goto Exit;
1742 }
1743 }
1744 }
1745
John Grossman4ff14ba2012-02-08 16:37:41 -08001746 if (!isTimed) {
1747 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001748 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001749 } else {
1750 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1751 channelMask, frameCount, sharedBuffer, sessionId);
1752 }
1753 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 lStatus = NO_MEMORY;
1755 goto Exit;
1756 }
1757 mTracks.add(track);
1758
1759 sp<EffectChain> chain = getEffectChain_l(sessionId);
1760 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001761 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001763 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001764 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 }
1766 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001767
1768#ifdef HAVE_REQUEST_PRIORITY
1769 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1770 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1771 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1772 // so ask activity manager to do this on our behalf
1773 int err = requestPriority(callingPid, tid, 1);
1774 if (err != 0) {
1775 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1776 1, callingPid, tid, err);
1777 }
1778 }
1779#endif
1780
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 lStatus = NO_ERROR;
1782
1783Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001784 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 *status = lStatus;
1786 }
1787 return track;
1788}
1789
1790uint32_t AudioFlinger::PlaybackThread::latency() const
1791{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001792 Mutex::Autolock _l(mLock);
1793 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001794 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001795 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 return 0;
1797 }
1798}
1799
Glenn Kasten6637baa2012-01-09 09:40:36 -08001800void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001802 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804}
1805
Glenn Kasten6637baa2012-01-09 09:40:36 -08001806void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001808 Mutex::Autolock _l(mLock);
1809 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810}
1811
Glenn Kasten6637baa2012-01-09 09:40:36 -08001812void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001814 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816}
1817
Glenn Kasten6637baa2012-01-09 09:40:36 -08001818void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001820 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822}
1823
Glenn Kastenfff6d712012-01-12 16:38:12 -08001824float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001826 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827 return mStreamTypes[stream].volume;
1828}
1829
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830// addTrack_l() must be called with ThreadBase::mLock held
1831status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1832{
1833 status_t status = ALREADY_EXISTS;
1834
1835 // set retry count for buffer fill
1836 track->mRetryCount = kMaxTrackStartupRetries;
1837 if (mActiveTracks.indexOf(track) < 0) {
1838 // the track is newly added, make sure it fills up all its
1839 // buffers before playing. This is to ensure the client will
1840 // effectively get the latency it requested.
1841 track->mFillingUpStatus = Track::FS_FILLING;
1842 track->mResetDone = false;
1843 mActiveTracks.add(track);
1844 if (track->mainBuffer() != mMixBuffer) {
1845 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1846 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001847 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001848 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 }
1850 }
1851
1852 status = NO_ERROR;
1853 }
1854
Steve Block3856b092011-10-20 11:56:00 +01001855 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 mWaitWorkCV.broadcast();
1857
1858 return status;
1859}
1860
1861// destroyTrack_l() must be called with ThreadBase::mLock held
1862void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1863{
1864 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001865 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001867 removeTrack_l(track);
1868 }
1869}
1870
1871void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1872{
1873 mTracks.remove(track);
1874 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001875 // redundant as track is about to be destroyed, for dumpsys only
1876 track->mName = -1;
1877 if (track->isFastTrack()) {
1878 int index = track->mFastIndex;
1879 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1880 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1881 mFastTrackAvailMask |= 1 << index;
1882 // redundant as track is about to be destroyed, for dumpsys only
1883 track->mFastIndex = -1;
1884 }
Eric Laurentb469b942011-05-09 12:09:06 -07001885 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1886 if (chain != 0) {
1887 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888 }
1889}
1890
1891String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1892{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001893 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001894 char *s;
1895
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001896 Mutex::Autolock _l(mLock);
1897 if (initCheck() != NO_ERROR) {
1898 return out_s8;
1899 }
1900
Dima Zavin799a70e2011-04-18 16:57:27 -07001901 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001902 out_s8 = String8(s);
1903 free(s);
1904 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905}
1906
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001907// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1909 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001910 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911
Steve Block3856b092011-10-20 11:56:00 +01001912 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913
1914 switch (event) {
1915 case AudioSystem::OUTPUT_OPENED:
1916 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001917 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 desc.samplingRate = mSampleRate;
1919 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001920 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 desc.latency = latency();
1922 param2 = &desc;
1923 break;
1924
1925 case AudioSystem::STREAM_CONFIG_CHANGED:
1926 param2 = &param;
1927 case AudioSystem::OUTPUT_CLOSED:
1928 default:
1929 break;
1930 }
1931 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1932}
1933
1934void AudioFlinger::PlaybackThread::readOutputParameters()
1935{
Dima Zavin799a70e2011-04-18 16:57:27 -07001936 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001937 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1938 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001939 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001940 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001941 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001942 if (mFrameCount & 15) {
1943 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1944 mFrameCount);
1945 }
1946
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001947 // Calculate size of normal mix buffer relative to the HAL output buffer size
1948 uint32_t multiple = 1;
1949 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001950 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001951 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1952 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1953 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1954 // FIXME this rounding up should not be done if no HAL SRC
1955 if ((multiple > 2) && (multiple & 1)) {
1956 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001957 }
Glenn Kasten58912562012-04-03 10:45:00 -07001958 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001959 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001960 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961
1962 // FIXME - Current mixer implementation only supports stereo output: Always
1963 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001964 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001965 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1966 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967
Eric Laurentde070132010-07-13 04:45:46 -07001968 // force reconfiguration of effect chains and engines to take new buffer size and audio
1969 // parameters into account
1970 // Note that mLock is not held when readOutputParameters() is called from the constructor
1971 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1972 // matter.
1973 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1974 Vector< sp<EffectChain> > effectChains = mEffectChains;
1975 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001976 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978}
1979
1980status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1981{
Glenn Kastena0d68332012-01-27 16:47:15 -08001982 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 return BAD_VALUE;
1984 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001985 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001986 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 return INVALID_OPERATION;
1988 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001989 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990
Dima Zavin799a70e2011-04-18 16:57:27 -07001991 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992}
1993
Eric Laurent39e94f82010-07-28 01:32:47 -07001994uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995{
1996 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001997 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001999 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 }
2001
2002 for (size_t i = 0; i < mTracks.size(); ++i) {
2003 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002004 if (sessionId == track->sessionId() &&
2005 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002006 result |= TRACK_SESSION;
2007 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 }
2009 }
2010
Eric Laurent39e94f82010-07-28 01:32:47 -07002011 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012}
2013
Eric Laurentde070132010-07-13 04:45:46 -07002014uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2015{
Dima Zavinfce7a472011-04-19 22:30:36 -07002016 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002017 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002018 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2019 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002020 }
2021 for (size_t i = 0; i < mTracks.size(); i++) {
2022 sp<Track> track = mTracks[i];
2023 if (sessionId == track->sessionId() &&
2024 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002025 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002026 }
2027 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002028 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002029}
2030
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031
Glenn Kastenaed850d2012-01-26 09:46:34 -08002032AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002033{
2034 Mutex::Autolock _l(mLock);
2035 return mOutput;
2036}
2037
2038AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2039{
2040 Mutex::Autolock _l(mLock);
2041 AudioStreamOut *output = mOutput;
2042 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002043 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2044 // must push a NULL and wait for ack
2045 mOutputSink.clear();
2046 mPipeSink.clear();
2047 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002048 return output;
2049}
2050
2051// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002052audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002053{
2054 if (mOutput == NULL) {
2055 return NULL;
2056 }
2057 return &mOutput->stream->common;
2058}
2059
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002060uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002061{
2062 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2063 // decoding and transfer time. So sleeping for half of the latency would likely cause
2064 // underruns
2065 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002066 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002067 } else {
2068 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2069 }
2070}
2071
Eric Laurenta011e352012-03-29 15:51:43 -07002072status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2073{
2074 if (!isValidSyncEvent(event)) {
2075 return BAD_VALUE;
2076 }
2077
2078 Mutex::Autolock _l(mLock);
2079
2080 for (size_t i = 0; i < mTracks.size(); ++i) {
2081 sp<Track> track = mTracks[i];
2082 if (event->triggerSession() == track->sessionId()) {
2083 track->setSyncEvent(event);
2084 return NO_ERROR;
2085 }
2086 }
2087
2088 return NAME_NOT_FOUND;
2089}
2090
2091bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2092{
2093 switch (event->type()) {
2094 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2095 return true;
2096 default:
2097 break;
2098 }
2099 return false;
2100}
2101
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102// ----------------------------------------------------------------------------
2103
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002104AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002105 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002106 : PlaybackThread(audioFlinger, output, id, device, type),
2107 // mAudioMixer below
2108#ifdef SOAKER
2109 mSoaker(NULL),
2110#endif
2111 // mFastMixer below
2112 mFastMixerFutex(0)
2113 // mOutputSink below
2114 // mPipeSink below
2115 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116{
Glenn Kasten58912562012-04-03 10:45:00 -07002117 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2118 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2119 "mFrameCount=%d, mNormalFrameCount=%d",
2120 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2121 mNormalFrameCount);
2122 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2123
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 // FIXME - Current mixer implementation only supports stereo output
2125 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002126 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 }
Glenn Kasten58912562012-04-03 10:45:00 -07002128
2129 // create an NBAIO sink for the HAL output stream, and negotiate
2130 mOutputSink = new AudioStreamOutSink(output->stream);
2131 size_t numCounterOffers = 0;
2132 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2133 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2134 ALOG_ASSERT(index == 0);
2135
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002136 // initialize fast mixer depending on configuration
2137 bool initFastMixer;
2138 switch (kUseFastMixer) {
2139 case FastMixer_Never:
2140 initFastMixer = false;
2141 break;
2142 case FastMixer_Always:
2143 initFastMixer = true;
2144 break;
2145 case FastMixer_Static:
2146 case FastMixer_Dynamic:
2147 initFastMixer = mFrameCount < mNormalFrameCount;
2148 break;
2149 }
2150 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002151
2152 // create a MonoPipe to connect our submix to FastMixer
2153 NBAIO_Format format = mOutputSink->format();
2154 // frame count will be rounded up to a power of 2, so this formula should work well
2155 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2156 true /*writeCanBlock*/);
2157 const NBAIO_Format offers[1] = {format};
2158 size_t numCounterOffers = 0;
2159 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2160 ALOG_ASSERT(index == 0);
2161 mPipeSink = monoPipe;
2162
2163#ifdef SOAKER
2164 // create a soaker as workaround for governor issues
2165 mSoaker = new Soaker();
2166 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2167 mSoaker->run("Soaker", PRIORITY_LOWEST);
2168#endif
2169
2170 // create fast mixer and configure it initially with just one fast track for our submix
2171 mFastMixer = new FastMixer();
2172 FastMixerStateQueue *sq = mFastMixer->sq();
2173 FastMixerState *state = sq->begin();
2174 FastTrack *fastTrack = &state->mFastTracks[0];
2175 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2176 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2177 fastTrack->mVolumeProvider = NULL;
2178 fastTrack->mGeneration++;
2179 state->mFastTracksGen++;
2180 state->mTrackMask = 1;
2181 // fast mixer will use the HAL output sink
2182 state->mOutputSink = mOutputSink.get();
2183 state->mOutputSinkGen++;
2184 state->mFrameCount = mFrameCount;
2185 state->mCommand = FastMixerState::COLD_IDLE;
2186 // already done in constructor initialization list
2187 //mFastMixerFutex = 0;
2188 state->mColdFutexAddr = &mFastMixerFutex;
2189 state->mColdGen++;
2190 state->mDumpState = &mFastMixerDumpState;
2191 sq->end();
2192 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2193
2194 // start the fast mixer
2195 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2196#ifdef HAVE_REQUEST_PRIORITY
2197 pid_t tid = mFastMixer->getTid();
2198 int err = requestPriority(getpid_cached, tid, 2);
2199 if (err != 0) {
2200 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2201 2, getpid_cached, tid, err);
2202 }
2203#endif
2204
2205 } else {
2206 mFastMixer = NULL;
2207 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002208
2209 switch (kUseFastMixer) {
2210 case FastMixer_Never:
2211 case FastMixer_Dynamic:
2212 mNormalSink = mOutputSink;
2213 break;
2214 case FastMixer_Always:
2215 mNormalSink = mPipeSink;
2216 break;
2217 case FastMixer_Static:
2218 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2219 break;
2220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221}
2222
2223AudioFlinger::MixerThread::~MixerThread()
2224{
Glenn Kasten58912562012-04-03 10:45:00 -07002225 if (mFastMixer != NULL) {
2226 FastMixerStateQueue *sq = mFastMixer->sq();
2227 FastMixerState *state = sq->begin();
2228 if (state->mCommand == FastMixerState::COLD_IDLE) {
2229 int32_t old = android_atomic_inc(&mFastMixerFutex);
2230 if (old == -1) {
2231 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2232 }
2233 }
2234 state->mCommand = FastMixerState::EXIT;
2235 sq->end();
2236 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2237 mFastMixer->join();
2238 // Though the fast mixer thread has exited, it's state queue is still valid.
2239 // We'll use that extract the final state which contains one remaining fast track
2240 // corresponding to our sub-mix.
2241 state = sq->begin();
2242 ALOG_ASSERT(state->mTrackMask == 1);
2243 FastTrack *fastTrack = &state->mFastTracks[0];
2244 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2245 delete fastTrack->mBufferProvider;
2246 sq->end(false /*didModify*/);
2247 delete mFastMixer;
2248#ifdef SOAKER
2249 if (mSoaker != NULL) {
2250 mSoaker->requestExitAndWait();
2251 }
2252 delete mSoaker;
2253#endif
2254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 delete mAudioMixer;
2256}
2257
Glenn Kasten83efdd02012-02-24 07:21:32 -08002258class CpuStats {
2259public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002260 CpuStats();
2261 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002262#ifdef DEBUG_CPU_USAGE
2263private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002264 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2265 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2266
2267 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2268
2269 int mCpuNum; // thread's current CPU number
2270 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002271#endif
2272};
2273
Glenn Kasten190a46f2012-03-06 11:27:10 -08002274CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002275#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002276 : mCpuNum(-1), mCpukHz(-1)
2277#endif
2278{
2279}
2280
2281void CpuStats::sample(const String8 &title) {
2282#ifdef DEBUG_CPU_USAGE
2283 // get current thread's delta CPU time in wall clock ns
2284 double wcNs;
2285 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2286
2287 // record sample for wall clock statistics
2288 if (valid) {
2289 mWcStats.sample(wcNs);
2290 }
2291
2292 // get the current CPU number
2293 int cpuNum = sched_getcpu();
2294
2295 // get the current CPU frequency in kHz
2296 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2297
2298 // check if either CPU number or frequency changed
2299 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2300 mCpuNum = cpuNum;
2301 mCpukHz = cpukHz;
2302 // ignore sample for purposes of cycles
2303 valid = false;
2304 }
2305
2306 // if no change in CPU number or frequency, then record sample for cycle statistics
2307 if (valid && mCpukHz > 0) {
2308 double cycles = wcNs * cpukHz * 0.000001;
2309 mHzStats.sample(cycles);
2310 }
2311
2312 unsigned n = mWcStats.n();
2313 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002314 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002315 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002316 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2317 double perLoop = elapsed / (double) n;
2318 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002319 double perLoop1k = perLoop * 0.001;
2320 double mean = mWcStats.mean();
2321 double stddev = mWcStats.stddev();
2322 double minimum = mWcStats.minimum();
2323 double maximum = mWcStats.maximum();
2324 double meanCycles = mHzStats.mean();
2325 double stddevCycles = mHzStats.stddev();
2326 double minCycles = mHzStats.minimum();
2327 double maxCycles = mHzStats.maximum();
2328 mCpuUsage.resetElapsed();
2329 mWcStats.reset();
2330 mHzStats.reset();
2331 ALOGD("CPU usage for %s over past %.1f secs\n"
2332 " (%u mixer loops at %.1f mean ms per loop):\n"
2333 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2334 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2335 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2336 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002337 elapsed * .000000001, n, perLoop * .000001,
2338 mean * .001,
2339 stddev * .001,
2340 minimum * .001,
2341 maximum * .001,
2342 mean / perLoop100,
2343 stddev / perLoop100,
2344 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002345 maximum / perLoop100,
2346 meanCycles / perLoop1k,
2347 stddevCycles / perLoop1k,
2348 minCycles / perLoop1k,
2349 maxCycles / perLoop1k);
2350
Glenn Kasten83efdd02012-02-24 07:21:32 -08002351 }
2352 }
2353#endif
2354};
2355
Glenn Kasten37d825e2012-02-24 07:21:48 -08002356void AudioFlinger::PlaybackThread::checkSilentMode_l()
2357{
2358 if (!mMasterMute) {
2359 char value[PROPERTY_VALUE_MAX];
2360 if (property_get("ro.audio.silent", value, "0") > 0) {
2361 char *endptr;
2362 unsigned long ul = strtoul(value, &endptr, 0);
2363 if (*endptr == '\0' && ul != 0) {
2364 ALOGD("Silence is golden");
2365 // The setprop command will not allow a property to be changed after
2366 // the first time it is set, so we don't have to worry about un-muting.
2367 setMasterMute_l(true);
2368 }
2369 }
2370 }
2371}
2372
Glenn Kasten000f0e32012-03-01 17:10:56 -08002373bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374{
2375 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002376
Glenn Kasten000f0e32012-03-01 17:10:56 -08002377 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002378
2379 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002381if (mType == MIXER) {
2382 longStandbyExit = false;
2383}
Glenn Kasten688a6402012-02-29 07:57:06 -08002384
Glenn Kasten000f0e32012-03-01 17:10:56 -08002385 // DUPLICATING
2386 // FIXME could this be made local to while loop?
2387 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002388
Glenn Kasten66fcab92012-02-24 14:59:21 -08002389 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002390 sleepTime = idleSleepTime;
2391
2392if (mType == MIXER) {
2393 sleepTimeShift = 0;
2394}
2395
Glenn Kasten83efdd02012-02-24 07:21:32 -08002396 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002397 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398
Eric Laurentfeb0db62011-07-22 09:04:31 -07002399 acquireWakeLock();
2400
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 while (!exitPending())
2402 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002403 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002404
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002405 Vector< sp<EffectChain> > effectChains;
2406
Mathias Agopian65ab4712010-07-14 17:59:35 -07002407 processConfigEvents();
2408
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 { // scope for mLock
2410
2411 Mutex::Autolock _l(mLock);
2412
2413 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002414 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416
Glenn Kastenfa26a852012-03-06 11:28:04 -08002417 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002418
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002420 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002421 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002423
2424 threadLoop_standby();
2425
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 mStandby = true;
2427 mBytesWritten = 0;
2428 }
2429
Glenn Kasten3e074702012-02-28 18:40:35 -08002430 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 // we're about to wait, flush the binder command buffer
2432 IPCThreadState::self()->flushCommands();
2433
Glenn Kastenfa26a852012-03-06 11:28:04 -08002434 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002435
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 if (exitPending()) break;
2437
Eric Laurentfeb0db62011-07-22 09:04:31 -07002438 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002440 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002442 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002443 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444
Eric Laurentda747442012-04-25 18:53:13 -07002445 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002446 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002447
Glenn Kasten37d825e2012-02-24 07:21:48 -08002448 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449
Glenn Kasten000f0e32012-03-01 17:10:56 -08002450 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002452 if (mType == MIXER) {
2453 sleepTimeShift = 0;
2454 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002455
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 continue;
2457 }
2458 }
2459
Glenn Kasten81028042012-04-30 18:15:12 -07002460 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002461 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462
2463 // prevent any changes in effect chain list and in each effect chain
2464 // during mixing and effect process as the audio buffers could be deleted
2465 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002466 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468
Glenn Kastenfec279f2012-03-08 07:47:15 -08002469 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002470 threadLoop_mix();
2471 } else {
2472 threadLoop_sleepTime();
2473 }
2474
2475 if (mSuspended > 0) {
2476 sleepTime = suspendSleepTimeUs();
2477 }
2478
2479 // only process effects if we're going to write
2480 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002481 for (size_t i = 0; i < effectChains.size(); i ++) {
2482 effectChains[i]->process_l();
2483 }
2484 }
2485
2486 // enable changes in effect chain
2487 unlockEffectChains(effectChains);
2488
2489 // sleepTime == 0 means we must write to audio hardware
2490 if (sleepTime == 0) {
2491
2492 threadLoop_write();
2493
2494if (mType == MIXER) {
2495 // write blocked detection
2496 nsecs_t now = systemTime();
2497 nsecs_t delta = now - mLastWriteTime;
2498 if (!mStandby && delta > maxPeriod) {
2499 mNumDelayedWrites++;
2500 if ((now - lastWarning) > kWarningThrottleNs) {
2501 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2502 ns2ms(delta), mNumDelayedWrites, this);
2503 lastWarning = now;
2504 }
2505 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2506 // a different threshold. Or completely removed for what it is worth anyway...
2507 if (mStandby) {
2508 longStandbyExit = true;
2509 }
2510 }
2511}
2512
2513 mStandby = false;
2514 } else {
2515 usleep(sleepTime);
2516 }
2517
Glenn Kasten58912562012-04-03 10:45:00 -07002518 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002519 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002520 // same lock. This will also mutate and push a new fast mixer state.
2521 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002522 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002523
Glenn Kastenfa26a852012-03-06 11:28:04 -08002524 // FIXME I don't understand the need for this here;
2525 // it was in the original code but maybe the
2526 // assignment in saveOutputTracks() makes this unnecessary?
2527 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002528
2529 // Effect chains will be actually deleted here if they were removed from
2530 // mEffectChains list during mixing or effects processing
2531 effectChains.clear();
2532
2533 // FIXME Note that the above .clear() is no longer necessary since effectChains
2534 // is now local to this block, but will keep it for now (at least until merge done).
2535 }
2536
2537if (mType == MIXER || mType == DIRECT) {
2538 // put output stream into standby mode
2539 if (!mStandby) {
2540 mOutput->stream->common.standby(&mOutput->stream->common);
2541 }
2542}
2543if (mType == DUPLICATING) {
2544 // for DuplicatingThread, standby mode is handled by the outputTracks
2545}
2546
2547 releaseWakeLock();
2548
2549 ALOGV("Thread %p type %d exiting", this, mType);
2550 return false;
2551}
2552
Glenn Kasten288ed212012-04-25 17:52:27 -07002553// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002554void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2555{
Glenn Kasten58912562012-04-03 10:45:00 -07002556 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2557}
2558
2559void AudioFlinger::MixerThread::threadLoop_write()
2560{
2561 // FIXME we should only do one push per cycle; confirm this is true
2562 // Start the fast mixer if it's not already running
2563 if (mFastMixer != NULL) {
2564 FastMixerStateQueue *sq = mFastMixer->sq();
2565 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002566 if (state->mCommand != FastMixerState::MIX_WRITE &&
2567 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002568 if (state->mCommand == FastMixerState::COLD_IDLE) {
2569 int32_t old = android_atomic_inc(&mFastMixerFutex);
2570 if (old == -1) {
2571 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2572 }
2573 }
2574 state->mCommand = FastMixerState::MIX_WRITE;
2575 sq->end();
2576 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002577 if (kUseFastMixer == FastMixer_Dynamic) {
2578 mNormalSink = mPipeSink;
2579 }
Glenn Kasten58912562012-04-03 10:45:00 -07002580 } else {
2581 sq->end(false /*didModify*/);
2582 }
2583 }
2584 PlaybackThread::threadLoop_write();
2585}
2586
Glenn Kasten000f0e32012-03-01 17:10:56 -08002587// shared by MIXER and DIRECT, overridden by DUPLICATING
2588void AudioFlinger::PlaybackThread::threadLoop_write()
2589{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002590 // FIXME rewrite to reduce number of system calls
2591 mLastWriteTime = systemTime();
2592 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002593
Glenn Kasten58912562012-04-03 10:45:00 -07002594#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002595 size_t count = mixBufferSize >> mBitShift;
2596 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2597 if (framesWritten > 0) {
2598 size_t bytesWritten = framesWritten << mBitShift;
2599 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002600 }
2601
Glenn Kasten952eeb22012-03-06 11:30:57 -08002602 mNumWrites++;
2603 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002604}
2605
Glenn Kasten58912562012-04-03 10:45:00 -07002606void AudioFlinger::MixerThread::threadLoop_standby()
2607{
2608 // Idle the fast mixer if it's currently running
2609 if (mFastMixer != NULL) {
2610 FastMixerStateQueue *sq = mFastMixer->sq();
2611 FastMixerState *state = sq->begin();
2612 if (!(state->mCommand & FastMixerState::IDLE)) {
2613 state->mCommand = FastMixerState::COLD_IDLE;
2614 state->mColdFutexAddr = &mFastMixerFutex;
2615 state->mColdGen++;
2616 mFastMixerFutex = 0;
2617 sq->end();
2618 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2619 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002620 if (kUseFastMixer == FastMixer_Dynamic) {
2621 mNormalSink = mOutputSink;
2622 }
Glenn Kasten58912562012-04-03 10:45:00 -07002623 } else {
2624 sq->end(false /*didModify*/);
2625 }
2626 }
2627 PlaybackThread::threadLoop_standby();
2628}
2629
Glenn Kasten000f0e32012-03-01 17:10:56 -08002630// shared by MIXER and DIRECT, overridden by DUPLICATING
2631void AudioFlinger::PlaybackThread::threadLoop_standby()
2632{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002633 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2634 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635}
2636
2637void AudioFlinger::MixerThread::threadLoop_mix()
2638{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002639 // obtain the presentation timestamp of the next output buffer
2640 int64_t pts;
2641 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002642
Glenn Kasten952eeb22012-03-06 11:30:57 -08002643 if (NULL != mOutput->stream->get_next_write_timestamp) {
2644 status = mOutput->stream->get_next_write_timestamp(
2645 mOutput->stream, &pts);
2646 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002647
Glenn Kasten952eeb22012-03-06 11:30:57 -08002648 if (status != NO_ERROR) {
2649 pts = AudioBufferProvider::kInvalidPTS;
2650 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002651
Glenn Kasten952eeb22012-03-06 11:30:57 -08002652 // mix buffers...
2653 mAudioMixer->process(pts);
2654 // increase sleep time progressively when application underrun condition clears.
2655 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2656 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2657 // such that we would underrun the audio HAL.
2658 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2659 sleepTimeShift--;
2660 }
2661 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002662 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002663 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002664}
2665
2666void AudioFlinger::MixerThread::threadLoop_sleepTime()
2667{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002668 // If no tracks are ready, sleep once for the duration of an output
2669 // buffer size, then write 0s to the output
2670 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002671 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002672 sleepTime = activeSleepTime >> sleepTimeShift;
2673 if (sleepTime < kMinThreadSleepTimeUs) {
2674 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002676 // reduce sleep time in case of consecutive application underruns to avoid
2677 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2678 // duration we would end up writing less data than needed by the audio HAL if
2679 // the condition persists.
2680 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2681 sleepTimeShift++;
2682 }
2683 } else {
2684 sleepTime = idleSleepTime;
2685 }
2686 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002687 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002688 memset (mMixBuffer, 0, mixBufferSize);
2689 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002690 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002691 }
2692 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693}
2694
2695// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002696AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002697 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698{
2699
Glenn Kasten29c23c32012-01-26 13:37:52 -08002700 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002702 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 size_t mixedTracks = 0;
2704 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002705 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002706 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002707 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708
2709 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002710 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711
Eric Laurent571d49c2010-08-11 05:20:11 -07002712 if (masterMute) {
2713 masterVolume = 0;
2714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002716 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002718 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002719 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 masterVolume = (float)((v + (1 << 23)) >> 24);
2721 chain.clear();
2722 }
2723
Glenn Kasten288ed212012-04-25 17:52:27 -07002724 // prepare a new state to push
2725 FastMixerStateQueue *sq = NULL;
2726 FastMixerState *state = NULL;
2727 bool didModify = false;
2728 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2729 if (mFastMixer != NULL) {
2730 sq = mFastMixer->sq();
2731 state = sq->begin();
2732 }
2733
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002735 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736 if (t == 0) continue;
2737
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002738 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002740
Glenn Kasten288ed212012-04-25 17:52:27 -07002741 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002742 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002743
2744 // It's theoretically possible (though unlikely) for a fast track to be created
2745 // and then removed within the same normal mix cycle. This is not a problem, as
2746 // the track never becomes active so it's fast mixer slot is never touched.
2747 // The converse, of removing an (active) track and then creating a new track
2748 // at the identical fast mixer slot within the same normal mix cycle,
2749 // is impossible because the slot isn't marked available until the end of each cycle.
2750 int j = track->mFastIndex;
2751 FastTrack *fastTrack = &state->mFastTracks[j];
2752
2753 // Determine whether the track is currently in underrun condition,
2754 // and whether it had a recent underrun.
2755 uint32_t underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2756 uint32_t recentUnderruns = (underruns - (track->mObservedUnderruns & ~1)) >> 1;
2757 // don't count underruns that occur while stopping or pausing
2758 if (!(track->isStopped() || track->isPausing())) {
2759 track->mUnderrunCount += recentUnderruns;
2760 }
2761 track->mObservedUnderruns = underruns;
2762
2763 // This is similar to the formula for normal tracks,
2764 // with a few modifications for fast tracks.
2765 bool isActive;
2766 if (track->isStopped()) {
2767 // track stays active after stop() until first underrun
2768 isActive = recentUnderruns == 0;
2769 } else if (track->isPaused() || track->isTerminated()) {
2770 isActive = false;
2771 } else if (track->isPausing()) {
2772 // ramp down is not yet implemented
2773 isActive = true;
2774 track->setPaused();
2775 } else if (track->isResuming()) {
2776 // ramp up is not yet implemented
2777 isActive = true;
2778 track->mState = TrackBase::ACTIVE;
2779 } else {
2780 // no minimum frame count for fast tracks; continual underrun is allowed,
2781 // but later could implement automatic pause after several consecutive underruns,
2782 // or auto-mute yet still consider the track active and continue to service it
2783 isActive = true;
2784 }
2785
2786 if (isActive) {
2787 // was it previously inactive?
2788 if (!(state->mTrackMask & (1 << j))) {
2789 ExtendedAudioBufferProvider *eabp = track;
2790 VolumeProvider *vp = track;
2791 fastTrack->mBufferProvider = eabp;
2792 fastTrack->mVolumeProvider = vp;
2793 fastTrack->mSampleRate = track->mSampleRate;
2794 fastTrack->mChannelMask = track->mChannelMask;
2795 fastTrack->mGeneration++;
2796 state->mTrackMask |= 1 << j;
2797 didModify = true;
2798 // no acknowledgement required for newly active tracks
2799 }
2800 // cache the combined master volume and stream type volume for fast mixer; this
2801 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2802 track->mCachedVolume = track->isMuted() ?
2803 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2804 ++fastTracks;
2805 } else {
2806 // was it previously active?
2807 if (state->mTrackMask & (1 << j)) {
2808 fastTrack->mBufferProvider = NULL;
2809 fastTrack->mGeneration++;
2810 state->mTrackMask &= ~(1 << j);
2811 didModify = true;
2812 // If any fast tracks were removed, we must wait for acknowledgement
2813 // because we're about to decrement the last sp<> on those tracks.
2814 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2815 }
2816 // Remainder of this block is copied from similar code for normal tracks
2817 if (track->isStopped()) {
2818 // Can't reset directly, as fast mixer is still polling this track
2819 // track->reset();
2820 // So instead mark this track as needing to be reset after push with ack
2821 resetMask |= 1 << i;
2822 }
2823 // This would be incomplete if we auto-paused on underrun
2824 size_t audioHALFrames =
2825 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2826 size_t framesWritten =
2827 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2828 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2829 tracksToRemove->add(track);
2830 }
2831 // Avoids a misleading display in dumpsys
2832 track->mObservedUnderruns &= ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07002833 }
2834 continue;
2835 }
2836
2837 { // local variable scope to avoid goto warning
2838
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 audio_track_cblk_t* cblk = track->cblk();
2840
2841 // The first time a track is added we wait
2842 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002843 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002844 // make sure that we have enough frames to mix one full buffer.
2845 // enforce this condition only once to enable draining the buffer in case the client
2846 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002847 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002848 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002849 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002850 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002851 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002852 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002853 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002854 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002855 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002856 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002857 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002858 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002859 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2860 // the minimum track buffer size is normally twice the number of frames necessary
2861 // to fill one buffer and the resampler should not leave more than one buffer worth
2862 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002863 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002864 }
2865 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002866 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 !track->isPaused() && !track->isTerminated())
2868 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002869 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870
2871 mixedTracks++;
2872
2873 // track->mainBuffer() != mMixBuffer means there is an effect chain
2874 // connected to the track
2875 chain.clear();
2876 if (track->mainBuffer() != mMixBuffer) {
2877 chain = getEffectChain_l(track->sessionId());
2878 // Delegate volume control to effect in track effect chain if needed
2879 if (chain != 0) {
2880 tracksWithEffect++;
2881 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002882 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002883 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 }
2885 }
2886
2887
2888 int param = AudioMixer::VOLUME;
2889 if (track->mFillingUpStatus == Track::FS_FILLED) {
2890 // no ramp for the first volume setting
2891 track->mFillingUpStatus = Track::FS_ACTIVE;
2892 if (track->mState == TrackBase::RESUMING) {
2893 track->mState = TrackBase::ACTIVE;
2894 param = AudioMixer::RAMP_VOLUME;
2895 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002896 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 } else if (cblk->server != 0) {
2898 // If the track is stopped before the first frame was mixed,
2899 // do not apply ramp
2900 param = AudioMixer::RAMP_VOLUME;
2901 }
2902
2903 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002904 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002905 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002906 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002907 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 if (track->isPausing()) {
2909 track->setPaused();
2910 }
2911 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002912
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002914 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002916 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002917 vl = vlr & 0xFFFF;
2918 vr = vlr >> 16;
2919 // track volumes come from shared memory, so can't be trusted and must be clamped
2920 if (vl > MAX_GAIN_INT) {
2921 ALOGV("Track left volume out of range: %04X", vl);
2922 vl = MAX_GAIN_INT;
2923 }
2924 if (vr > MAX_GAIN_INT) {
2925 ALOGV("Track right volume out of range: %04X", vr);
2926 vr = MAX_GAIN_INT;
2927 }
2928 // now apply the master volume and stream type volume
2929 vl = (uint32_t)(v * vl) << 12;
2930 vr = (uint32_t)(v * vr) << 12;
2931 // assuming master volume and stream type volume each go up to 1.0,
2932 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933
Glenn Kasten05632a52012-01-03 14:22:33 -08002934 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2935 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002936 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002937 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002938 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002939 }
2940 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002942 // Delegate volume control to effect in track effect chain if needed
2943 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2944 // Do not ramp volume if volume is controlled by effect
2945 param = AudioMixer::VOLUME;
2946 track->mHasVolumeController = true;
2947 } else {
2948 // force no volume ramp when volume controller was just disabled or removed
2949 // from effect chain to avoid volume spike
2950 if (track->mHasVolumeController) {
2951 param = AudioMixer::VOLUME;
2952 }
2953 track->mHasVolumeController = false;
2954 }
2955
2956 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002957 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002958 vl = (vl + (1 << 11)) >> 12;
2959 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2960 vr = (vr + (1 << 11)) >> 12;
2961 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002962
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002963 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 -07002964
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002966 mAudioMixer->setBufferProvider(name, track);
2967 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002969 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2970 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2971 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002973 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 AudioMixer::TRACK,
2975 AudioMixer::FORMAT, (void *)track->format());
2976 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002977 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002979 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002981 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 AudioMixer::RESAMPLE,
2983 AudioMixer::SAMPLE_RATE,
2984 (void *)(cblk->sampleRate));
2985 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002986 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 AudioMixer::TRACK,
2988 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2989 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002990 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 AudioMixer::TRACK,
2992 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2993
2994 // reset retry count
2995 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002996
Eric Laurent27741442012-01-17 19:20:12 -08002997 // If one track is ready, set the mixer ready if:
2998 // - the mixer was not ready during previous round OR
2999 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003000 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003001 mixerStatus != MIXER_TRACKS_ENABLED) {
3002 mixerStatus = MIXER_TRACKS_READY;
3003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003005 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 if (track->isStopped()) {
3007 track->reset();
3008 }
Eric Laurent83faee02012-04-27 18:24:29 -07003009 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3010 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 // We have consumed all the buffers of this track.
3012 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003013 // TODO: use actual buffer filling status instead of latency when available from
3014 // audio HAL
3015 size_t audioHALFrames =
3016 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3017 size_t framesWritten =
3018 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3019 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3020 tracksToRemove->add(track);
3021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 } else {
3023 // No buffers for this track. Give it a few chances to
3024 // fill a buffer, then remove it from active list.
3025 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003026 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003028 // indicate to client process that the track was disabled because of underrun;
3029 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003030 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003031 // If one track is not ready, mark the mixer also not ready if:
3032 // - the mixer was ready during previous round OR
3033 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003034 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003035 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 mixerStatus = MIXER_TRACKS_ENABLED;
3037 }
3038 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003039 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 }
Glenn Kasten58912562012-04-03 10:45:00 -07003041
3042 } // local variable scope to avoid goto warning
3043track_is_ready: ;
3044
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 }
3046
Glenn Kasten288ed212012-04-25 17:52:27 -07003047 // Push the new FastMixer state if necessary
3048 if (didModify) {
3049 state->mFastTracksGen++;
3050 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3051 if (kUseFastMixer == FastMixer_Dynamic &&
3052 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3053 state->mCommand = FastMixerState::COLD_IDLE;
3054 state->mColdFutexAddr = &mFastMixerFutex;
3055 state->mColdGen++;
3056 mFastMixerFutex = 0;
3057 if (kUseFastMixer == FastMixer_Dynamic) {
3058 mNormalSink = mOutputSink;
3059 }
3060 // If we go into cold idle, need to wait for acknowledgement
3061 // so that fast mixer stops doing I/O.
3062 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3063 }
3064 sq->end();
3065 }
3066 if (sq != NULL) {
3067 sq->end(didModify);
3068 sq->push(block);
3069 }
3070
3071 // Now perform the deferred reset on fast tracks that have stopped
3072 while (resetMask != 0) {
3073 size_t i = __builtin_ctz(resetMask);
3074 ALOG_ASSERT(i < count);
3075 resetMask &= ~(1 << i);
3076 sp<Track> t = mActiveTracks[i].promote();
3077 if (t == 0) continue;
3078 Track* track = t.get();
3079 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3080 track->reset();
3081 }
Glenn Kasten58912562012-04-03 10:45:00 -07003082
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 // remove all the tracks that need to be...
3084 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003085 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 for (size_t i=0 ; i<count ; i++) {
3087 const sp<Track>& track = tracksToRemove->itemAt(i);
3088 mActiveTracks.remove(track);
3089 if (track->mainBuffer() != mMixBuffer) {
3090 chain = getEffectChain_l(track->sessionId());
3091 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003092 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003093 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
3095 }
3096 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003097 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 }
3099 }
3100 }
3101
3102 // mix buffer must be cleared if all tracks are connected to an
3103 // effect chain as in this case the mixer will not write to
3104 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003105 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3106 // FIXME as a performance optimization, should remember previous zero status
3107 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 }
3109
Glenn Kasten58912562012-04-03 10:45:00 -07003110 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003111 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003112 if (fastTracks > 0) {
3113 mixerStatus = MIXER_TRACKS_READY;
3114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 return mixerStatus;
3116}
3117
Glenn Kasten66fcab92012-02-24 14:59:21 -08003118/*
3119The derived values that are cached:
3120 - mixBufferSize from frame count * frame size
3121 - activeSleepTime from activeSleepTimeUs()
3122 - idleSleepTime from idleSleepTimeUs()
3123 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3124 - maxPeriod from frame count and sample rate (MIXER only)
3125
3126The parameters that affect these derived values are:
3127 - frame count
3128 - frame size
3129 - sample rate
3130 - device type: A2DP or not
3131 - device latency
3132 - format: PCM or not
3133 - active sleep time
3134 - idle sleep time
3135*/
3136
3137void AudioFlinger::PlaybackThread::cacheParameters_l()
3138{
Glenn Kasten58912562012-04-03 10:45:00 -07003139 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003140 activeSleepTime = activeSleepTimeUs();
3141 idleSleepTime = idleSleepTimeUs();
3142}
3143
Glenn Kastenfff6d712012-01-12 16:38:12 -08003144void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145{
Steve Block3856b092011-10-20 11:56:00 +01003146 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003147 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003149
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 size_t size = mTracks.size();
3151 for (size_t i = 0; i < size; i++) {
3152 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003153 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003154 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 }
3157 }
3158}
3159
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003161int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003163 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164}
3165
3166// deleteTrackName_l() must be called with ThreadBase::mLock held
3167void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3168{
Steve Block3856b092011-10-20 11:56:00 +01003169 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 mAudioMixer->deleteTrackName(name);
3171}
3172
3173// checkForNewParameters_l() must be called with ThreadBase::mLock held
3174bool AudioFlinger::MixerThread::checkForNewParameters_l()
3175{
Glenn Kasten58912562012-04-03 10:45:00 -07003176 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3177 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178 bool reconfig = false;
3179
3180 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003181
3182 if (mFastMixer != NULL) {
3183 FastMixerStateQueue *sq = mFastMixer->sq();
3184 FastMixerState *state = sq->begin();
3185 if (!(state->mCommand & FastMixerState::IDLE)) {
3186 previousCommand = state->mCommand;
3187 state->mCommand = FastMixerState::HOT_IDLE;
3188 sq->end();
3189 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3190 } else {
3191 sq->end(false /*didModify*/);
3192 }
3193 }
3194
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 status_t status = NO_ERROR;
3196 String8 keyValuePair = mNewParameters[0];
3197 AudioParameter param = AudioParameter(keyValuePair);
3198 int value;
3199
3200 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3201 reconfig = true;
3202 }
3203 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003204 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 status = BAD_VALUE;
3206 } else {
3207 reconfig = true;
3208 }
3209 }
3210 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003211 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 status = BAD_VALUE;
3213 } else {
3214 reconfig = true;
3215 }
3216 }
3217 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3218 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003219 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 // if frame count is changed after track creation
3221 if (!mTracks.isEmpty()) {
3222 status = INVALID_OPERATION;
3223 } else {
3224 reconfig = true;
3225 }
3226 }
3227 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003228#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003229 // when changing the audio output device, call addBatteryData to notify
3230 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003231 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003232 uint32_t params = 0;
3233 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003234 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003235 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3236 }
3237
3238 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003239 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003240 // check if any other device (except speaker) is on
3241 if (value & deviceWithoutSpeaker ) {
3242 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3243 }
3244
3245 if (params != 0) {
3246 addBatteryData(params);
3247 }
3248 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003249#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003250
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 // forward device change to effects that have requested to be
3252 // aware of attached audio device.
3253 mDevice = (uint32_t)value;
3254 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003255 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 }
3257 }
3258
3259 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003260 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003261 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003263 mOutput->stream->common.standby(&mOutput->stream->common);
3264 mStandby = true;
3265 mBytesWritten = 0;
3266 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003267 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 }
3269 if (status == NO_ERROR && reconfig) {
3270 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003271 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3272 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003274 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003276 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 if (name < 0) break;
3278 mTracks[i]->mName = name;
3279 // limit track sample rate to 2 x new output sample rate
3280 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3281 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3282 }
3283 }
3284 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3285 }
3286 }
3287
3288 mNewParameters.removeAt(0);
3289
3290 mParamStatus = status;
3291 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003292 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3293 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003294 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 }
Glenn Kasten58912562012-04-03 10:45:00 -07003296
3297 if (!(previousCommand & FastMixerState::IDLE)) {
3298 ALOG_ASSERT(mFastMixer != NULL);
3299 FastMixerStateQueue *sq = mFastMixer->sq();
3300 FastMixerState *state = sq->begin();
3301 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3302 state->mCommand = previousCommand;
3303 sq->end();
3304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3305 }
3306
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 return reconfig;
3308}
3309
3310status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3311{
3312 const size_t SIZE = 256;
3313 char buffer[SIZE];
3314 String8 result;
3315
3316 PlaybackThread::dumpInternals(fd, args);
3317
3318 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3319 result.append(buffer);
3320 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003321
3322 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3323 FastMixerDumpState copy = mFastMixerDumpState;
3324 copy.dump(fd);
3325
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 return NO_ERROR;
3327}
3328
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003329uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330{
Glenn Kasten58912562012-04-03 10:45:00 -07003331 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332}
3333
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003334uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003335{
Glenn Kasten58912562012-04-03 10:45:00 -07003336 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003337}
3338
Glenn Kasten66fcab92012-02-24 14:59:21 -08003339void AudioFlinger::MixerThread::cacheParameters_l()
3340{
3341 PlaybackThread::cacheParameters_l();
3342
3343 // FIXME: Relaxed timing because of a certain device that can't meet latency
3344 // Should be reduced to 2x after the vendor fixes the driver issue
3345 // increase threshold again due to low power audio mode. The way this warning
3346 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003347 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003348}
3349
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003351AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3352 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003353 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003354 // mLeftVolFloat, mRightVolFloat
3355 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357}
3358
3359AudioFlinger::DirectOutputThread::~DirectOutputThread()
3360{
3361}
3362
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003363AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3364 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003365)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003367 sp<Track> trackToRemove;
3368
Glenn Kastenfec279f2012-03-08 07:47:15 -08003369 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370
Glenn Kasten952eeb22012-03-06 11:30:57 -08003371 // find out which tracks need to be processed
3372 if (mActiveTracks.size() != 0) {
3373 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003374 // The track died recently
3375 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376
Glenn Kasten952eeb22012-03-06 11:30:57 -08003377 Track* const track = t.get();
3378 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379
Glenn Kasten952eeb22012-03-06 11:30:57 -08003380 // The first time a track is added we wait
3381 // for all its buffers to be filled before processing it
3382 if (cblk->framesReady() && track->isReady() &&
3383 !track->isPaused() && !track->isTerminated())
3384 {
3385 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386
Glenn Kasten952eeb22012-03-06 11:30:57 -08003387 if (track->mFillingUpStatus == Track::FS_FILLED) {
3388 track->mFillingUpStatus = Track::FS_ACTIVE;
3389 mLeftVolFloat = mRightVolFloat = 0;
3390 mLeftVolShort = mRightVolShort = 0;
3391 if (track->mState == TrackBase::RESUMING) {
3392 track->mState = TrackBase::ACTIVE;
3393 rampVolume = true;
3394 }
3395 } else if (cblk->server != 0) {
3396 // If the track is stopped before the first frame was mixed,
3397 // do not apply ramp
3398 rampVolume = true;
3399 }
3400 // compute volume for this track
3401 float left, right;
3402 if (track->isMuted() || mMasterMute || track->isPausing() ||
3403 mStreamTypes[track->streamType()].mute) {
3404 left = right = 0;
3405 if (track->isPausing()) {
3406 track->setPaused();
3407 }
3408 } else {
3409 float typeVolume = mStreamTypes[track->streamType()].volume;
3410 float v = mMasterVolume * typeVolume;
3411 uint32_t vlr = cblk->getVolumeLR();
3412 float v_clamped = v * (vlr & 0xFFFF);
3413 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3414 left = v_clamped/MAX_GAIN;
3415 v_clamped = v * (vlr >> 16);
3416 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3417 right = v_clamped/MAX_GAIN;
3418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419
Glenn Kasten952eeb22012-03-06 11:30:57 -08003420 if (left != mLeftVolFloat || right != mRightVolFloat) {
3421 mLeftVolFloat = left;
3422 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423
Glenn Kasten952eeb22012-03-06 11:30:57 -08003424 // If audio HAL implements volume control,
3425 // force software volume to nominal value
3426 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3427 left = 1.0f;
3428 right = 1.0f;
3429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430
Glenn Kasten952eeb22012-03-06 11:30:57 -08003431 // Convert volumes from float to 8.24
3432 uint32_t vl = (uint32_t)(left * (1 << 24));
3433 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434
Glenn Kasten952eeb22012-03-06 11:30:57 -08003435 // Delegate volume control to effect in track effect chain if needed
3436 // only one effect chain can be present on DirectOutputThread, so if
3437 // there is one, the track is connected to it
3438 if (!mEffectChains.isEmpty()) {
3439 // Do not ramp volume if volume is controlled by effect
3440 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 rampVolume = false;
3442 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444
Glenn Kasten952eeb22012-03-06 11:30:57 -08003445 // Convert volumes from 8.24 to 4.12 format
3446 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3447 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3448 leftVol = (uint16_t)v_clamped;
3449 v_clamped = (vr + (1 << 11)) >> 12;
3450 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3451 rightVol = (uint16_t)v_clamped;
3452 } else {
3453 leftVol = mLeftVolShort;
3454 rightVol = mRightVolShort;
3455 rampVolume = false;
3456 }
3457
3458 // reset retry count
3459 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003460 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003461 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003462 } else {
3463 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3464 if (track->isStopped()) {
3465 track->reset();
3466 }
3467 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3468 // We have consumed all the buffers of this track.
3469 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003470 // TODO: implement behavior for compressed audio
3471 size_t audioHALFrames =
3472 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3473 size_t framesWritten =
3474 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3475 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3476 trackToRemove = track;
3477 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003478 } else {
3479 // No buffers for this track. Give it a few chances to
3480 // fill a buffer, then remove it from active list.
3481 if (--(track->mRetryCount) <= 0) {
3482 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3483 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003485 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
3487 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003488 }
3489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003491 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003492 // remove all the tracks that need to be...
3493 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003494 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003495 mActiveTracks.remove(trackToRemove);
3496 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003497 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003498 trackToRemove->sessionId());
3499 mEffectChains[0]->decActiveTrackCnt();
3500 }
3501 if (trackToRemove->isTerminated()) {
3502 removeTrack_l(trackToRemove);
3503 }
3504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505
Glenn Kastenfec279f2012-03-08 07:47:15 -08003506 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003507}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508
Glenn Kasten000f0e32012-03-01 17:10:56 -08003509void AudioFlinger::DirectOutputThread::threadLoop_mix()
3510{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003511 AudioBufferProvider::Buffer buffer;
3512 size_t frameCount = mFrameCount;
3513 int8_t *curBuf = (int8_t *)mMixBuffer;
3514 // output audio to hardware
3515 while (frameCount) {
3516 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003517 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003518 if (CC_UNLIKELY(buffer.raw == NULL)) {
3519 memset(curBuf, 0, frameCount * mFrameSize);
3520 break;
3521 }
3522 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3523 frameCount -= buffer.frameCount;
3524 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003525 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003526 }
3527 sleepTime = 0;
3528 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003529 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003530
3531 // apply volume
3532
3533 // Do not apply volume on compressed audio
3534 if (!audio_is_linear_pcm(mFormat)) {
3535 return;
3536 }
3537
3538 // convert to signed 16 bit before volume calculation
3539 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3540 size_t count = mFrameCount * mChannelCount;
3541 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3542 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003543 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003544 *dst-- = (int16_t)(*src--^0x80) << 8;
3545 }
3546 }
3547
3548 frameCount = mFrameCount;
3549 int16_t *out = mMixBuffer;
3550 if (rampVolume) {
3551 if (mChannelCount == 1) {
3552 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3553 int32_t vlInc = d / (int32_t)frameCount;
3554 int32_t vl = ((int32_t)mLeftVolShort << 16);
3555 do {
3556 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3557 out++;
3558 vl += vlInc;
3559 } while (--frameCount);
3560
3561 } else {
3562 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3563 int32_t vlInc = d / (int32_t)frameCount;
3564 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3565 int32_t vrInc = d / (int32_t)frameCount;
3566 int32_t vl = ((int32_t)mLeftVolShort << 16);
3567 int32_t vr = ((int32_t)mRightVolShort << 16);
3568 do {
3569 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3570 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3571 out += 2;
3572 vl += vlInc;
3573 vr += vrInc;
3574 } while (--frameCount);
3575 }
3576 } else {
3577 if (mChannelCount == 1) {
3578 do {
3579 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3580 out++;
3581 } while (--frameCount);
3582 } else {
3583 do {
3584 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3585 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3586 out += 2;
3587 } while (--frameCount);
3588 }
3589 }
3590
3591 // convert back to unsigned 8 bit after volume calculation
3592 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3593 size_t count = mFrameCount * mChannelCount;
3594 int16_t *src = mMixBuffer;
3595 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003596 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003597 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3598 }
3599 }
3600
3601 mLeftVolShort = leftVol;
3602 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003603}
3604
3605void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3606{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003607 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003608 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003609 sleepTime = activeSleepTime;
3610 } else {
3611 sleepTime = idleSleepTime;
3612 }
3613 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003614 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003615 sleepTime = 0;
3616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617}
3618
3619// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003620int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621{
3622 return 0;
3623}
3624
3625// deleteTrackName_l() must be called with ThreadBase::mLock held
3626void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3627{
3628}
3629
3630// checkForNewParameters_l() must be called with ThreadBase::mLock held
3631bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3632{
3633 bool reconfig = false;
3634
3635 while (!mNewParameters.isEmpty()) {
3636 status_t status = NO_ERROR;
3637 String8 keyValuePair = mNewParameters[0];
3638 AudioParameter param = AudioParameter(keyValuePair);
3639 int value;
3640
3641 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3642 // do not accept frame count changes if tracks are open as the track buffer
3643 // size depends on frame count and correct behavior would not be garantied
3644 // if frame count is changed after track creation
3645 if (!mTracks.isEmpty()) {
3646 status = INVALID_OPERATION;
3647 } else {
3648 reconfig = true;
3649 }
3650 }
3651 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003652 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003653 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003655 mOutput->stream->common.standby(&mOutput->stream->common);
3656 mStandby = true;
3657 mBytesWritten = 0;
3658 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003659 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 }
3661 if (status == NO_ERROR && reconfig) {
3662 readOutputParameters();
3663 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3664 }
3665 }
3666
3667 mNewParameters.removeAt(0);
3668
3669 mParamStatus = status;
3670 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003671 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3672 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003673 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 }
3675 return reconfig;
3676}
3677
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003678uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679{
3680 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003681 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003682 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 } else {
3684 time = 10000;
3685 }
3686 return time;
3687}
3688
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003689uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690{
3691 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003692 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003693 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 } else {
3695 time = 10000;
3696 }
3697 return time;
3698}
3699
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003700uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003701{
3702 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003703 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003704 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3705 } else {
3706 time = 10000;
3707 }
3708 return time;
3709}
3710
Glenn Kasten66fcab92012-02-24 14:59:21 -08003711void AudioFlinger::DirectOutputThread::cacheParameters_l()
3712{
3713 PlaybackThread::cacheParameters_l();
3714
3715 // use shorter standby delay as on normal output to release
3716 // hardware resources as soon as possible
3717 standbyDelay = microseconds(activeSleepTime*2);
3718}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003719
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720// ----------------------------------------------------------------------------
3721
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003722AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003723 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003724 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3725 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727 addOutputTrack(mainThread);
3728}
3729
3730AudioFlinger::DuplicatingThread::~DuplicatingThread()
3731{
3732 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3733 mOutputTracks[i]->destroy();
3734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735}
3736
Glenn Kasten000f0e32012-03-01 17:10:56 -08003737void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003739 // mix buffers...
3740 if (outputsReady(outputTracks)) {
3741 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3742 } else {
3743 memset(mMixBuffer, 0, mixBufferSize);
3744 }
3745 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003746 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003747}
3748
3749void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3750{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003751 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003752 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003753 sleepTime = activeSleepTime;
3754 } else {
3755 sleepTime = idleSleepTime;
3756 }
3757 } else if (mBytesWritten != 0) {
3758 // flush remaining overflow buffers in output tracks
3759 for (size_t i = 0; i < outputTracks.size(); i++) {
3760 if (outputTracks[i]->isActive()) {
3761 sleepTime = 0;
3762 writeFrames = 0;
3763 memset(mMixBuffer, 0, mixBufferSize);
3764 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 }
3767 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003768}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769
Glenn Kasten000f0e32012-03-01 17:10:56 -08003770void AudioFlinger::DuplicatingThread::threadLoop_write()
3771{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003772 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 for (size_t i = 0; i < outputTracks.size(); i++) {
3774 outputTracks[i]->write(mMixBuffer, writeFrames);
3775 }
3776 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003777}
Glenn Kasten688a6402012-02-29 07:57:06 -08003778
Glenn Kasten000f0e32012-03-01 17:10:56 -08003779void AudioFlinger::DuplicatingThread::threadLoop_standby()
3780{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 // DuplicatingThread implements standby by stopping all tracks
3782 for (size_t i = 0; i < outputTracks.size(); i++) {
3783 outputTracks[i]->stop();
3784 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785}
3786
Glenn Kastenfa26a852012-03-06 11:28:04 -08003787void AudioFlinger::DuplicatingThread::saveOutputTracks()
3788{
3789 outputTracks = mOutputTracks;
3790}
3791
3792void AudioFlinger::DuplicatingThread::clearOutputTracks()
3793{
3794 outputTracks.clear();
3795}
3796
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3798{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003799 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003800 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003801 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003802 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803 this,
3804 mSampleRate,
3805 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003806 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 frameCount);
3808 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003809 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003811 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003812 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003813 }
3814}
3815
3816void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3817{
3818 Mutex::Autolock _l(mLock);
3819 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003820 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821 mOutputTracks[i]->destroy();
3822 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003823 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 return;
3825 }
3826 }
Steve Block3856b092011-10-20 11:56:00 +01003827 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828}
3829
Glenn Kasten438b0362012-03-06 11:24:48 -08003830// caller must hold mLock
3831void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832{
3833 mWaitTimeMs = UINT_MAX;
3834 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3835 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003836 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3838 if (waitTimeMs < mWaitTimeMs) {
3839 mWaitTimeMs = waitTimeMs;
3840 }
3841 }
3842 }
3843}
3844
3845
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003846bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847{
3848 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003849 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003851 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 return false;
3853 }
3854 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3855 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003856 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 return false;
3858 }
3859 }
3860 return true;
3861}
3862
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003863uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864{
3865 return (mWaitTimeMs * 1000) / 2;
3866}
3867
Glenn Kasten66fcab92012-02-24 14:59:21 -08003868void AudioFlinger::DuplicatingThread::cacheParameters_l()
3869{
3870 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3871 updateWaitTime_l();
3872
3873 MixerThread::cacheParameters_l();
3874}
3875
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876// ----------------------------------------------------------------------------
3877
3878// TrackBase constructor must be called with AudioFlinger::mLock held
3879AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003880 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881 const sp<Client>& client,
3882 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003883 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003884 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 const sp<IMemory>& sharedBuffer,
3887 int sessionId)
3888 : RefBase(),
3889 mThread(thread),
3890 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003891 mCblk(NULL),
3892 // mBuffer
3893 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 mFrameCount(0),
3895 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003896 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003898 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003900 // mChannelCount
3901 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902{
Steve Block3856b092011-10-20 11:56:00 +01003903 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904
Steve Blockb8a80522011-12-20 16:23:08 +00003905 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003906 size_t size = sizeof(audio_track_cblk_t);
3907 uint8_t channelCount = popcount(channelMask);
3908 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3909 if (sharedBuffer == 0) {
3910 size += bufferSize;
3911 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003913 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 mCblkMemory = client->heap()->allocate(size);
3915 if (mCblkMemory != 0) {
3916 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003917 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918 new(mCblk) audio_track_cblk_t();
3919 // clear all buffers
3920 mCblk->frameCount = frameCount;
3921 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003922// uncomment the following lines to quickly test 32-bit wraparound
3923// mCblk->user = 0xffff0000;
3924// mCblk->server = 0xffff0000;
3925// mCblk->userBase = 0xffff0000;
3926// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003927 mChannelCount = channelCount;
3928 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 if (sharedBuffer == 0) {
3930 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3931 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3932 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003933 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 mCblk->flags = CBLK_UNDERRUN_ON;
3935 } else {
3936 mBuffer = sharedBuffer->pointer();
3937 }
3938 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3939 }
3940 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003941 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 client->heap()->dump("AudioTrack");
3943 return;
3944 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003945 } else {
3946 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003947 // construct the shared structure in-place.
3948 new(mCblk) audio_track_cblk_t();
3949 // clear all buffers
3950 mCblk->frameCount = frameCount;
3951 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003952// uncomment the following lines to quickly test 32-bit wraparound
3953// mCblk->user = 0xffff0000;
3954// mCblk->server = 0xffff0000;
3955// mCblk->userBase = 0xffff0000;
3956// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003957 mChannelCount = channelCount;
3958 mChannelMask = channelMask;
3959 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3960 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3961 // Force underrun condition to avoid false underrun callback until first data is
3962 // written to buffer (other flags are cleared)
3963 mCblk->flags = CBLK_UNDERRUN_ON;
3964 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966}
3967
3968AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3969{
Glenn Kastena0d68332012-01-27 16:47:15 -08003970 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003971 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003973 } else {
3974 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975 }
3976 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003977 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003978 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003979 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003981 // If the client's reference count drops to zero, the associated destructor
3982 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3983 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 mClient.clear();
3985 }
3986}
3987
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003988// AudioBufferProvider interface
3989// getNextBuffer() = 0;
3990// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3992{
Glenn Kastene0feee32011-12-13 11:53:26 -08003993 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07003995 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003996 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 buffer->frameCount = 0;
3998}
3999
4000bool AudioFlinger::ThreadBase::TrackBase::step() {
4001 bool result;
4002 audio_track_cblk_t* cblk = this->cblk();
4003
4004 result = cblk->stepServer(mFrameCount);
4005 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004006 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004007 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 }
4009 return result;
4010}
4011
4012void AudioFlinger::ThreadBase::TrackBase::reset() {
4013 audio_track_cblk_t* cblk = this->cblk();
4014
4015 cblk->user = 0;
4016 cblk->server = 0;
4017 cblk->userBase = 0;
4018 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004019 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004020 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021}
4022
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4024 return (int)mCblk->sampleRate;
4025}
4026
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4028 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004029 size_t frameSize = cblk->frameSize;
4030 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4031 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032
4033 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004034 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4035 "TrackBase::getBuffer buffer out of range:\n"
4036 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4037 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004039 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040
4041 return bufferStart;
4042}
4043
Eric Laurenta011e352012-03-29 15:51:43 -07004044status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4045{
4046 mSyncEvents.add(event);
4047 return NO_ERROR;
4048}
4049
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050// ----------------------------------------------------------------------------
4051
4052// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4053AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004054 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004056 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004058 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004059 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 int frameCount,
4061 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004062 int sessionId,
4063 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004064 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004065 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004066 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004067 // mRetryCount initialized later when needed
4068 mSharedBuffer(sharedBuffer),
4069 mStreamType(streamType),
4070 mName(-1), // see note below
4071 mMainBuffer(thread->mixBuffer()),
4072 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004073 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004074 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004075 mFlags(flags),
4076 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004077 mObservedUnderruns(0),
4078 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004079 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080{
4081 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4083 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004084 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004085 if (flags & IAudioFlinger::TRACK_FAST) {
4086 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4087 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4088 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4089 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004090 // FIXME This is too eager. We allocate a fast track index before the
4091 // fast track becomes active. Since fast tracks are a scarce resource,
4092 // this means we are potentially denying other more important fast tracks from
4093 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004094 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004095 // Read the initial underruns because this field is never cleared by the fast mixer
4096 mObservedUnderruns = thread->getFastTrackUnderruns(i) & ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07004097 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004098 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004099 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004100 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004101 if (mName < 0) {
4102 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004103 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4104 // then we leak a fast track index. Should swap these two sections, or better yet
4105 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004108 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109}
4110
4111AudioFlinger::PlaybackThread::Track::~Track()
4112{
Steve Block3856b092011-10-20 11:56:00 +01004113 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 sp<ThreadBase> thread = mThread.promote();
4115 if (thread != 0) {
4116 Mutex::Autolock _l(thread->mLock);
4117 mState = TERMINATED;
4118 }
4119}
4120
4121void AudioFlinger::PlaybackThread::Track::destroy()
4122{
4123 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4124 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004125 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 // we must acquire a strong reference on this Track before locking mLock
4127 // here so that the destructor is called only when exiting this function.
4128 // On the other hand, as long as Track::destroy() is only called by
4129 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4130 // this Track with its member mTrack.
4131 sp<Track> keep(this);
4132 { // scope for mLock
4133 sp<ThreadBase> thread = mThread.promote();
4134 if (thread != 0) {
4135 if (!isOutputTrack()) {
4136 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004137 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004138
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004139#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004140 // to track the speaker usage
4141 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004142#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 }
4144 AudioSystem::releaseOutput(thread->id());
4145 }
4146 Mutex::Autolock _l(thread->mLock);
4147 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4148 playbackThread->destroyTrack_l(this);
4149 }
4150 }
4151}
4152
Glenn Kasten288ed212012-04-25 17:52:27 -07004153/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4154{
Glenn Kastene213c862012-04-25 13:46:15 -07004155 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4156 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004157}
4158
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4160{
Glenn Kasten83d86532012-01-17 14:39:34 -08004161 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004162 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004163 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004164 } else {
4165 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4166 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004167 track_state state = mState;
4168 char stateChar;
4169 switch (state) {
4170 case IDLE:
4171 stateChar = 'I';
4172 break;
4173 case TERMINATED:
4174 stateChar = 'T';
4175 break;
4176 case STOPPED:
4177 stateChar = 'S';
4178 break;
4179 case RESUMING:
4180 stateChar = 'R';
4181 break;
4182 case ACTIVE:
4183 stateChar = 'A';
4184 break;
4185 case PAUSING:
4186 stateChar = 'p';
4187 break;
4188 case PAUSED:
4189 stateChar = 'P';
4190 break;
4191 default:
4192 stateChar = '?';
4193 break;
4194 }
4195 bool nowInUnderrun = mObservedUnderruns & 1;
Glenn Kastene213c862012-04-25 13:46:15 -07004196 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4197 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004198 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199 mStreamType,
4200 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004201 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mSessionId,
4203 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004204 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004205 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 mMute,
4207 mFillingUpStatus,
4208 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004209 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4210 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 mCblk->server,
4212 mCblk->user,
4213 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004214 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004215 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004216 mUnderrunCount,
4217 nowInUnderrun ? '*' : ' ');
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218}
4219
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004220// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004221status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004222 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004224 audio_track_cblk_t* cblk = this->cblk();
4225 uint32_t framesReady;
4226 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004228 // Check if last stepServer failed, try to step now
4229 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004230 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4231 // Since the fast mixer is higher priority than client callback thread,
4232 // it does not result in priority inversion for client.
4233 // But a non-blocking solution would be preferable to avoid
4234 // fast mixer being unable to tryLock(), and
4235 // to avoid the extra context switches if the client wakes up,
4236 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004237 if (!step()) goto getNextBuffer_exit;
4238 ALOGV("stepServer recovered");
4239 mStepServerFailed = false;
4240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
Glenn Kasten288ed212012-04-25 17:52:27 -07004242 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004243 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004245 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 uint32_t s = cblk->server;
4247 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4248
4249 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4250 if (framesReq > framesReady) {
4251 framesReq = framesReady;
4252 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004253 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 framesReq = bufferEnd - s;
4255 }
4256
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004257 buffer->raw = getBuffer(s, framesReq);
4258 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004260 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263
4264getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004265 buffer->raw = NULL;
4266 buffer->frameCount = 0;
4267 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4268 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269}
4270
Glenn Kasten288ed212012-04-25 17:52:27 -07004271// Note that framesReady() takes a mutex on the control block using tryLock().
4272// This could result in priority inversion if framesReady() is called by the normal mixer,
4273// as the normal mixer thread runs at lower
4274// priority than the client's callback thread: there is a short window within framesReady()
4275// during which the normal mixer could be preempted, and the client callback would block.
4276// Another problem can occur if framesReady() is called by the fast mixer:
4277// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4278// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4279size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004280 return mCblk->framesReady();
4281}
4282
Glenn Kasten288ed212012-04-25 17:52:27 -07004283// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004285 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286
John Grossman4ff14ba2012-02-08 16:37:41 -08004287 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4289 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004290 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 return true;
4292 }
4293 return false;
4294}
4295
Glenn Kasten3acbd052012-02-28 10:39:56 -08004296status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004297 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298{
4299 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004300 ALOGV("start(%d), calling pid %d session %d",
4301 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004302
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 sp<ThreadBase> thread = mThread.promote();
4304 if (thread != 0) {
4305 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004306 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 // here the track could be either new, or restarted
4308 // in both cases "unstop" the track
4309 if (mState == PAUSED) {
4310 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004311 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 } else {
4313 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004314 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 }
4316
4317 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4318 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004319 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004321
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004322#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004323 // to track the speaker usage
4324 if (status == NO_ERROR) {
4325 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4326 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004327#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 }
4329 if (status == NO_ERROR) {
4330 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4331 playbackThread->addTrack_l(this);
4332 } else {
4333 mState = state;
4334 }
4335 } else {
4336 status = BAD_VALUE;
4337 }
4338 return status;
4339}
4340
4341void AudioFlinger::PlaybackThread::Track::stop()
4342{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004343 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 sp<ThreadBase> thread = mThread.promote();
4345 if (thread != 0) {
4346 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004347 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 if (mState > STOPPED) {
4349 mState = STOPPED;
4350 // If the track is not active (PAUSED and buffers full), flush buffers
4351 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4352 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4353 reset();
4354 }
Steve Block3856b092011-10-20 11:56:00 +01004355 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 }
4357 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4358 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004359 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004361
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004362#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004363 // to track the speaker usage
4364 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004365#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 }
4367 }
4368}
4369
4370void AudioFlinger::PlaybackThread::Track::pause()
4371{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004372 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373 sp<ThreadBase> thread = mThread.promote();
4374 if (thread != 0) {
4375 Mutex::Autolock _l(thread->mLock);
4376 if (mState == ACTIVE || mState == RESUMING) {
4377 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004378 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 if (!isOutputTrack()) {
4380 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004381 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004383
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004384#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004385 // to track the speaker usage
4386 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004387#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 }
4389 }
4390 }
4391}
4392
4393void AudioFlinger::PlaybackThread::Track::flush()
4394{
Steve Block3856b092011-10-20 11:56:00 +01004395 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 sp<ThreadBase> thread = mThread.promote();
4397 if (thread != 0) {
4398 Mutex::Autolock _l(thread->mLock);
4399 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4400 return;
4401 }
4402 // No point remaining in PAUSED state after a flush => go to
4403 // STOPPED state
4404 mState = STOPPED;
4405
Eric Laurent38ccae22011-03-28 18:37:07 -07004406 // do not reset the track if it is still in the process of being stopped or paused.
4407 // this will be done by prepareTracks_l() when the track is stopped.
4408 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4409 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4410 reset();
4411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 }
4413}
4414
4415void AudioFlinger::PlaybackThread::Track::reset()
4416{
4417 // Do not reset twice to avoid discarding data written just after a flush and before
4418 // the audioflinger thread detects the track is stopped.
4419 if (!mResetDone) {
4420 TrackBase::reset();
4421 // Force underrun condition to avoid false underrun callback until first data is
4422 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004423 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4424 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 mFillingUpStatus = FS_FILLING;
4426 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004427 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 }
4429}
4430
4431void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4432{
4433 mMute = muted;
4434}
4435
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4437{
4438 status_t status = DEAD_OBJECT;
4439 sp<ThreadBase> thread = mThread.promote();
4440 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004441 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4442 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 }
4444 return status;
4445}
4446
4447void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4448{
4449 mAuxEffectId = EffectId;
4450 mAuxBuffer = buffer;
4451}
4452
Eric Laurenta011e352012-03-29 15:51:43 -07004453bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4454 size_t audioHalFrames)
4455{
4456 // a track is considered presented when the total number of frames written to audio HAL
4457 // corresponds to the number of frames written when presentationComplete() is called for the
4458 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4459 if (mPresentationCompleteFrames == 0) {
4460 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4461 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4462 mPresentationCompleteFrames, audioHalFrames);
4463 }
4464 if (framesWritten >= mPresentationCompleteFrames) {
4465 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4466 mSessionId, framesWritten);
4467 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4468 mPresentationCompleteFrames = 0;
4469 return true;
4470 }
4471 return false;
4472}
4473
4474void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4475{
4476 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4477 if (mSyncEvents[i]->type() == type) {
4478 mSyncEvents[i]->trigger();
4479 mSyncEvents.removeAt(i);
4480 i--;
4481 }
4482 }
4483}
4484
Glenn Kasten58912562012-04-03 10:45:00 -07004485// implement VolumeBufferProvider interface
4486
4487uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4488{
4489 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4490 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4491 uint32_t vlr = mCblk->getVolumeLR();
4492 uint32_t vl = vlr & 0xFFFF;
4493 uint32_t vr = vlr >> 16;
4494 // track volumes come from shared memory, so can't be trusted and must be clamped
4495 if (vl > MAX_GAIN_INT) {
4496 vl = MAX_GAIN_INT;
4497 }
4498 if (vr > MAX_GAIN_INT) {
4499 vr = MAX_GAIN_INT;
4500 }
4501 // now apply the cached master volume and stream type volume;
4502 // this is trusted but lacks any synchronization or barrier so may be stale
4503 float v = mCachedVolume;
4504 vl *= v;
4505 vr *= v;
4506 // re-combine into U4.16
4507 vlr = (vr << 16) | (vl & 0xFFFF);
4508 // FIXME look at mute, pause, and stop flags
4509 return vlr;
4510}
Eric Laurenta011e352012-03-29 15:51:43 -07004511
John Grossman4ff14ba2012-02-08 16:37:41 -08004512// timed audio tracks
4513
4514sp<AudioFlinger::PlaybackThread::TimedTrack>
4515AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004516 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004517 const sp<Client>& client,
4518 audio_stream_type_t streamType,
4519 uint32_t sampleRate,
4520 audio_format_t format,
4521 uint32_t channelMask,
4522 int frameCount,
4523 const sp<IMemory>& sharedBuffer,
4524 int sessionId) {
4525 if (!client->reserveTimedTrack())
4526 return NULL;
4527
Glenn Kastena0356762012-03-19 10:38:51 -07004528 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004529 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4530 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004531}
4532
4533AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004534 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004535 const sp<Client>& client,
4536 audio_stream_type_t streamType,
4537 uint32_t sampleRate,
4538 audio_format_t format,
4539 uint32_t channelMask,
4540 int frameCount,
4541 const sp<IMemory>& sharedBuffer,
4542 int sessionId)
4543 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004544 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004545 mQueueHeadInFlight(false),
4546 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004547 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004548 mTimedSilenceBuffer(NULL),
4549 mTimedSilenceBufferSize(0),
4550 mTimedAudioOutputOnTime(false),
4551 mMediaTimeTransformValid(false)
4552{
4553 LocalClock lc;
4554 mLocalTimeFreq = lc.getLocalFreq();
4555
4556 mLocalTimeToSampleTransform.a_zero = 0;
4557 mLocalTimeToSampleTransform.b_zero = 0;
4558 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4559 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4560 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4561 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004562
4563 mMediaTimeToSampleTransform.a_zero = 0;
4564 mMediaTimeToSampleTransform.b_zero = 0;
4565 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4566 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4567 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4568 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004569}
4570
4571AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4572 mClient->releaseTimedTrack();
4573 delete [] mTimedSilenceBuffer;
4574}
4575
4576status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4577 size_t size, sp<IMemory>* buffer) {
4578
4579 Mutex::Autolock _l(mTimedBufferQueueLock);
4580
4581 trimTimedBufferQueue_l();
4582
4583 // lazily initialize the shared memory heap for timed buffers
4584 if (mTimedMemoryDealer == NULL) {
4585 const int kTimedBufferHeapSize = 512 << 10;
4586
4587 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4588 "AudioFlingerTimed");
4589 if (mTimedMemoryDealer == NULL)
4590 return NO_MEMORY;
4591 }
4592
4593 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4594 if (newBuffer == NULL) {
4595 newBuffer = mTimedMemoryDealer->allocate(size);
4596 if (newBuffer == NULL)
4597 return NO_MEMORY;
4598 }
4599
4600 *buffer = newBuffer;
4601 return NO_ERROR;
4602}
4603
4604// caller must hold mTimedBufferQueueLock
4605void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4606 int64_t mediaTimeNow;
4607 {
4608 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4609 if (!mMediaTimeTransformValid)
4610 return;
4611
4612 int64_t targetTimeNow;
4613 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4614 ? mCCHelper.getCommonTime(&targetTimeNow)
4615 : mCCHelper.getLocalTime(&targetTimeNow);
4616
4617 if (OK != res)
4618 return;
4619
4620 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4621 &mediaTimeNow)) {
4622 return;
4623 }
4624 }
4625
John Grossman1c345192012-03-27 14:00:17 -07004626 size_t trimEnd;
4627 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004628 int64_t bufEnd;
4629
John Grossmanc95cfbb2012-04-12 11:53:11 -07004630 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4631 // We have a next buffer. Just use its PTS as the PTS of the frame
4632 // following the last frame in this buffer. If the stream is sparse
4633 // (ie, there are deliberate gaps left in the stream which should be
4634 // filled with silence by the TimedAudioTrack), then this can result
4635 // in one extra buffer being left un-trimmed when it could have
4636 // been. In general, this is not typical, and we would rather
4637 // optimized away the TS calculation below for the more common case
4638 // where PTSes are contiguous.
4639 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4640 } else {
4641 // We have no next buffer. Compute the PTS of the frame following
4642 // the last frame in this buffer by computing the duration of of
4643 // this frame in media time units and adding it to the PTS of the
4644 // buffer.
4645 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4646 / mCblk->frameSize;
4647
4648 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4649 &bufEnd)) {
4650 ALOGE("Failed to convert frame count of %lld to media time"
4651 " duration" " (scale factor %d/%u) in %s",
4652 frameCount,
4653 mMediaTimeToSampleTransform.a_to_b_numer,
4654 mMediaTimeToSampleTransform.a_to_b_denom,
4655 __PRETTY_FUNCTION__);
4656 break;
4657 }
4658 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004659 }
John Grossman9fbdee12012-03-26 17:51:46 -07004660
4661 if (bufEnd > mediaTimeNow)
4662 break;
4663
4664 // Is the buffer we want to use in the middle of a mix operation right
4665 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4666 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004667 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004668 mTrimQueueHeadOnRelease = true;
4669 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004670 }
4671
John Grossman9fbdee12012-03-26 17:51:46 -07004672 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004673 if (trimStart < trimEnd) {
4674 // Update the bookkeeping for framesReady()
4675 for (size_t i = trimStart; i < trimEnd; ++i) {
4676 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4677 }
4678
4679 // Now actually remove the buffers from the queue.
4680 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004681 }
4682}
4683
John Grossman1c345192012-03-27 14:00:17 -07004684void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4685 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004686 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4687 "%s called (reason \"%s\"), but timed buffer queue has no"
4688 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004689
4690 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4691 mTimedBufferQueue.removeAt(0);
4692}
4693
4694void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4695 const TimedBuffer& buf,
4696 const char* logTag) {
4697 uint32_t bufBytes = buf.buffer()->size();
4698 uint32_t consumedAlready = buf.position();
4699
Eric Laurentb388e532012-04-14 13:32:48 -07004700 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004701 "Bad bookkeeping while updating frames pending. Timed buffer is"
4702 " only %u bytes long, but claims to have consumed %u"
4703 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004704 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004705
4706 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004707 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4708 "Bad bookkeeping while updating frames pending. Should have at"
4709 " least %u queued frames, but we think we have only %u. (update"
4710 " reason: \"%s\")",
4711 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004712
4713 mFramesPendingInQueue -= bufFrames;
4714}
4715
John Grossman4ff14ba2012-02-08 16:37:41 -08004716status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4717 const sp<IMemory>& buffer, int64_t pts) {
4718
4719 {
4720 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4721 if (!mMediaTimeTransformValid)
4722 return INVALID_OPERATION;
4723 }
4724
4725 Mutex::Autolock _l(mTimedBufferQueueLock);
4726
John Grossman1c345192012-03-27 14:00:17 -07004727 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4728 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004729 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4730
4731 return NO_ERROR;
4732}
4733
4734status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4735 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4736
John Grossman1c345192012-03-27 14:00:17 -07004737 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4738 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4739 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004740
4741 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4742 target == TimedAudioTrack::COMMON_TIME)) {
4743 return BAD_VALUE;
4744 }
4745
4746 Mutex::Autolock lock(mMediaTimeTransformLock);
4747 mMediaTimeTransform = xform;
4748 mMediaTimeTransformTarget = target;
4749 mMediaTimeTransformValid = true;
4750
4751 return NO_ERROR;
4752}
4753
4754#define min(a, b) ((a) < (b) ? (a) : (b))
4755
4756// implementation of getNextBuffer for tracks whose buffers have timestamps
4757status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4758 AudioBufferProvider::Buffer* buffer, int64_t pts)
4759{
4760 if (pts == AudioBufferProvider::kInvalidPTS) {
4761 buffer->raw = 0;
4762 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004763 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004764 return INVALID_OPERATION;
4765 }
4766
John Grossman4ff14ba2012-02-08 16:37:41 -08004767 Mutex::Autolock _l(mTimedBufferQueueLock);
4768
John Grossman9fbdee12012-03-26 17:51:46 -07004769 ALOG_ASSERT(!mQueueHeadInFlight,
4770 "getNextBuffer called without releaseBuffer!");
4771
John Grossman4ff14ba2012-02-08 16:37:41 -08004772 while (true) {
4773
4774 // if we have no timed buffers, then fail
4775 if (mTimedBufferQueue.isEmpty()) {
4776 buffer->raw = 0;
4777 buffer->frameCount = 0;
4778 return NOT_ENOUGH_DATA;
4779 }
4780
4781 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4782
4783 // calculate the PTS of the head of the timed buffer queue expressed in
4784 // local time
4785 int64_t headLocalPTS;
4786 {
4787 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4788
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004789 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004790
4791 if (mMediaTimeTransform.a_to_b_denom == 0) {
4792 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004793 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004794 return NO_ERROR;
4795 }
4796
4797 int64_t transformedPTS;
4798 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4799 &transformedPTS)) {
4800 // the transform failed. this shouldn't happen, but if it does
4801 // then just drop this buffer
4802 ALOGW("timedGetNextBuffer transform failed");
4803 buffer->raw = 0;
4804 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004805 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004806 return NO_ERROR;
4807 }
4808
4809 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4810 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4811 &headLocalPTS)) {
4812 buffer->raw = 0;
4813 buffer->frameCount = 0;
4814 return INVALID_OPERATION;
4815 }
4816 } else {
4817 headLocalPTS = transformedPTS;
4818 }
4819 }
4820
4821 // adjust the head buffer's PTS to reflect the portion of the head buffer
4822 // that has already been consumed
4823 int64_t effectivePTS = headLocalPTS +
4824 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4825
4826 // Calculate the delta in samples between the head of the input buffer
4827 // queue and the start of the next output buffer that will be written.
4828 // If the transformation fails because of over or underflow, it means
4829 // that the sample's position in the output stream is so far out of
4830 // whack that it should just be dropped.
4831 int64_t sampleDelta;
4832 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4833 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004834 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4835 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004836 continue;
4837 }
4838 if (!mLocalTimeToSampleTransform.doForwardTransform(
4839 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004840 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004841 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004842 continue;
4843 }
4844
John Grossman1c345192012-03-27 14:00:17 -07004845 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4846 " sampleDelta=[%d.%08x]",
4847 head.pts(), head.position(), pts,
4848 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4849 + (sampleDelta >> 32)),
4850 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004851
4852 // if the delta between the ideal placement for the next input sample and
4853 // the current output position is within this threshold, then we will
4854 // concatenate the next input samples to the previous output
4855 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004856 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004857
4858 // if this is the first buffer of audio that we're emitting from this track
4859 // then it should be almost exactly on time.
4860 const int64_t kSampleStartupThreshold = 1LL << 32;
4861
4862 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004863 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004864 // the next input is close enough to being on time, so concatenate it
4865 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004866 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004867
John Grossman1c345192012-03-27 14:00:17 -07004868 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4869 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004870 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004871 }
4872
4873 // Looks like our output is not on time. Reset our on timed status.
4874 // Next time we mix samples from our input queue, then should be within
4875 // the StartupThreshold.
4876 mTimedAudioOutputOnTime = false;
4877 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004878 // the gap between the current output position and the proper start of
4879 // the next input sample is too big, so fill it with silence
4880 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4881
John Grossman9fbdee12012-03-26 17:51:46 -07004882 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004883 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4884 return NO_ERROR;
4885 } else {
4886 // the next input sample is late
4887 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4888 size_t onTimeSamplePosition =
4889 head.position() + lateFrames * mCblk->frameSize;
4890
4891 if (onTimeSamplePosition > head.buffer()->size()) {
4892 // all the remaining samples in the head are too late, so
4893 // drop it and move on
4894 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004895 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004896 continue;
4897 } else {
4898 // skip over the late samples
4899 head.setPosition(onTimeSamplePosition);
4900
4901 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004902 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004903
4904 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4905 return NO_ERROR;
4906 }
4907 }
4908 }
4909}
4910
4911// Yield samples from the timed buffer queue head up to the given output
4912// buffer's capacity.
4913//
4914// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004915void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004916 AudioBufferProvider::Buffer* buffer) {
4917
4918 const TimedBuffer& head = mTimedBufferQueue[0];
4919
4920 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4921 head.position());
4922
4923 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4924 mCblk->frameSize);
4925 size_t framesRequested = buffer->frameCount;
4926 buffer->frameCount = min(framesLeftInHead, framesRequested);
4927
John Grossman9fbdee12012-03-26 17:51:46 -07004928 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004929 mTimedAudioOutputOnTime = true;
4930}
4931
4932// Yield samples of silence up to the given output buffer's capacity
4933//
4934// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004935void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004936 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4937
4938 // lazily allocate a buffer filled with silence
4939 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4940 delete [] mTimedSilenceBuffer;
4941 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4942 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4943 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4944 }
4945
4946 buffer->raw = mTimedSilenceBuffer;
4947 size_t framesRequested = buffer->frameCount;
4948 buffer->frameCount = min(numFrames, framesRequested);
4949
4950 mTimedAudioOutputOnTime = false;
4951}
4952
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004953// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004954void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4955 AudioBufferProvider::Buffer* buffer) {
4956
4957 Mutex::Autolock _l(mTimedBufferQueueLock);
4958
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004959 // If the buffer which was just released is part of the buffer at the head
4960 // of the queue, be sure to update the amt of the buffer which has been
4961 // consumed. If the buffer being returned is not part of the head of the
4962 // queue, its either because the buffer is part of the silence buffer, or
4963 // because the head of the timed queue was trimmed after the mixer called
4964 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004965 if (buffer->raw == mTimedSilenceBuffer) {
4966 ALOG_ASSERT(!mQueueHeadInFlight,
4967 "Queue head in flight during release of silence buffer!");
4968 goto done;
4969 }
4970
4971 ALOG_ASSERT(mQueueHeadInFlight,
4972 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4973 " head in flight.");
4974
4975 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004976 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004977
4978 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004979 void* end = reinterpret_cast<void*>(
4980 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4981 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004982
John Grossman9fbdee12012-03-26 17:51:46 -07004983 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4984 "released buffer not within the head of the timed buffer"
4985 " queue; qHead = [%p, %p], released buffer = %p",
4986 start, end, buffer->raw);
4987
4988 head.setPosition(head.position() +
4989 (buffer->frameCount * mCblk->frameSize));
4990 mQueueHeadInFlight = false;
4991
John Grossman1c345192012-03-27 14:00:17 -07004992 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4993 "Bad bookkeeping during releaseBuffer! Should have at"
4994 " least %u queued frames, but we think we have only %u",
4995 buffer->frameCount, mFramesPendingInQueue);
4996
4997 mFramesPendingInQueue -= buffer->frameCount;
4998
John Grossman9fbdee12012-03-26 17:51:46 -07004999 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5000 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005001 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005002 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005003 }
John Grossman9fbdee12012-03-26 17:51:46 -07005004 } else {
5005 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5006 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005007 }
5008
John Grossman9fbdee12012-03-26 17:51:46 -07005009done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005010 buffer->raw = 0;
5011 buffer->frameCount = 0;
5012}
5013
Glenn Kasten288ed212012-04-25 17:52:27 -07005014size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005015 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005016 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005017}
5018
5019AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5020 : mPTS(0), mPosition(0) {}
5021
5022AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5023 const sp<IMemory>& buffer, int64_t pts)
5024 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5025
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026// ----------------------------------------------------------------------------
5027
5028// RecordTrack constructor must be called with AudioFlinger::mLock held
5029AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005030 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 const sp<Client>& client,
5032 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005033 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005034 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 int sessionId)
5037 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005038 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 mOverflow(false)
5040{
5041 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005042 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5043 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5044 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5045 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5046 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5047 } else {
5048 mCblk->frameSize = sizeof(int8_t);
5049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 }
5051}
5052
5053AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5054{
5055 sp<ThreadBase> thread = mThread.promote();
5056 if (thread != 0) {
5057 AudioSystem::releaseInput(thread->id());
5058 }
5059}
5060
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005061// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005062status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005063{
5064 audio_track_cblk_t* cblk = this->cblk();
5065 uint32_t framesAvail;
5066 uint32_t framesReq = buffer->frameCount;
5067
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005068 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005069 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005071 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005072 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 }
5074
5075 framesAvail = cblk->framesAvailable_l();
5076
Glenn Kastenf6b16782011-12-15 09:51:17 -08005077 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 uint32_t s = cblk->server;
5079 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5080
5081 if (framesReq > framesAvail) {
5082 framesReq = framesAvail;
5083 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005084 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005085 framesReq = bufferEnd - s;
5086 }
5087
5088 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005089 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090
5091 buffer->frameCount = framesReq;
5092 return NO_ERROR;
5093 }
5094
5095getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005096 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097 buffer->frameCount = 0;
5098 return NOT_ENOUGH_DATA;
5099}
5100
Glenn Kasten3acbd052012-02-28 10:39:56 -08005101status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005102 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103{
5104 sp<ThreadBase> thread = mThread.promote();
5105 if (thread != 0) {
5106 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005107 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 } else {
5109 return BAD_VALUE;
5110 }
5111}
5112
5113void AudioFlinger::RecordThread::RecordTrack::stop()
5114{
5115 sp<ThreadBase> thread = mThread.promote();
5116 if (thread != 0) {
5117 RecordThread *recordThread = (RecordThread *)thread.get();
5118 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005119 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005120 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005121 // read from buffer
5122 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 }
5124}
5125
5126void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5127{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005128 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005129 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005130 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005131 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005132 mSessionId,
5133 mFrameCount,
5134 mState,
5135 mCblk->sampleRate,
5136 mCblk->server,
5137 mCblk->user);
5138}
5139
5140
5141// ----------------------------------------------------------------------------
5142
5143AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005144 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145 DuplicatingThread *sourceThread,
5146 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005147 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005148 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005149 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005150 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5151 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152 mActive(false), mSourceThread(sourceThread)
5153{
5154
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 if (mCblk != NULL) {
5156 mCblk->flags |= CBLK_DIRECTION_OUT;
5157 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 mOutBuffer.frameCount = 0;
5159 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005160 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005161 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5162 mCblk, mBuffer, mCblk->buffers,
5163 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005165 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 }
5167}
5168
5169AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5170{
5171 clearBufferQueue();
5172}
5173
Glenn Kasten3acbd052012-02-28 10:39:56 -08005174status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005175 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005177 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 if (status != NO_ERROR) {
5179 return status;
5180 }
5181
5182 mActive = true;
5183 mRetryCount = 127;
5184 return status;
5185}
5186
5187void AudioFlinger::PlaybackThread::OutputTrack::stop()
5188{
5189 Track::stop();
5190 clearBufferQueue();
5191 mOutBuffer.frameCount = 0;
5192 mActive = false;
5193}
5194
5195bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5196{
5197 Buffer *pInBuffer;
5198 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005199 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 bool outputBufferFull = false;
5201 inBuffer.frameCount = frames;
5202 inBuffer.i16 = data;
5203
5204 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5205
5206 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005207 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 sp<ThreadBase> thread = mThread.promote();
5209 if (thread != 0) {
5210 MixerThread *mixerThread = (MixerThread *)thread.get();
5211 if (mCblk->frameCount > frames){
5212 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5213 uint32_t startFrames = (mCblk->frameCount - frames);
5214 pInBuffer = new Buffer;
5215 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5216 pInBuffer->frameCount = startFrames;
5217 pInBuffer->i16 = pInBuffer->mBuffer;
5218 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5219 mBufferQueue.add(pInBuffer);
5220 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005221 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005222 }
5223 }
5224 }
5225 }
5226
5227 while (waitTimeLeftMs) {
5228 // First write pending buffers, then new data
5229 if (mBufferQueue.size()) {
5230 pInBuffer = mBufferQueue.itemAt(0);
5231 } else {
5232 pInBuffer = &inBuffer;
5233 }
5234
5235 if (pInBuffer->frameCount == 0) {
5236 break;
5237 }
5238
5239 if (mOutBuffer.frameCount == 0) {
5240 mOutBuffer.frameCount = pInBuffer->frameCount;
5241 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005242 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005243 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244 outputBufferFull = true;
5245 break;
5246 }
5247 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5248 if (waitTimeLeftMs >= waitTimeMs) {
5249 waitTimeLeftMs -= waitTimeMs;
5250 } else {
5251 waitTimeLeftMs = 0;
5252 }
5253 }
5254
5255 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5256 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5257 mCblk->stepUser(outFrames);
5258 pInBuffer->frameCount -= outFrames;
5259 pInBuffer->i16 += outFrames * channelCount;
5260 mOutBuffer.frameCount -= outFrames;
5261 mOutBuffer.i16 += outFrames * channelCount;
5262
5263 if (pInBuffer->frameCount == 0) {
5264 if (mBufferQueue.size()) {
5265 mBufferQueue.removeAt(0);
5266 delete [] pInBuffer->mBuffer;
5267 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005268 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269 } else {
5270 break;
5271 }
5272 }
5273 }
5274
5275 // If we could not write all frames, allocate a buffer and queue it for next time.
5276 if (inBuffer.frameCount) {
5277 sp<ThreadBase> thread = mThread.promote();
5278 if (thread != 0 && !thread->standby()) {
5279 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5280 pInBuffer = new Buffer;
5281 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5282 pInBuffer->frameCount = inBuffer.frameCount;
5283 pInBuffer->i16 = pInBuffer->mBuffer;
5284 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5285 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005286 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005288 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005289 }
5290 }
5291 }
5292
5293 // Calling write() with a 0 length buffer, means that no more data will be written:
5294 // If no more buffers are pending, fill output track buffer to make sure it is started
5295 // by output mixer.
5296 if (frames == 0 && mBufferQueue.size() == 0) {
5297 if (mCblk->user < mCblk->frameCount) {
5298 frames = mCblk->frameCount - mCblk->user;
5299 pInBuffer = new Buffer;
5300 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5301 pInBuffer->frameCount = frames;
5302 pInBuffer->i16 = pInBuffer->mBuffer;
5303 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5304 mBufferQueue.add(pInBuffer);
5305 } else if (mActive) {
5306 stop();
5307 }
5308 }
5309
5310 return outputBufferFull;
5311}
5312
5313status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5314{
5315 int active;
5316 status_t result;
5317 audio_track_cblk_t* cblk = mCblk;
5318 uint32_t framesReq = buffer->frameCount;
5319
Steve Block3856b092011-10-20 11:56:00 +01005320// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 buffer->frameCount = 0;
5322
5323 uint32_t framesAvail = cblk->framesAvailable();
5324
5325
5326 if (framesAvail == 0) {
5327 Mutex::Autolock _l(cblk->lock);
5328 goto start_loop_here;
5329 while (framesAvail == 0) {
5330 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005331 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005332 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005333 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 }
5335 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5336 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005337 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338 }
5339 // read the server count again
5340 start_loop_here:
5341 framesAvail = cblk->framesAvailable_l();
5342 }
5343 }
5344
5345// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005346// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347// }
5348
5349 if (framesReq > framesAvail) {
5350 framesReq = framesAvail;
5351 }
5352
5353 uint32_t u = cblk->user;
5354 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5355
Marco Nelissena1472d92012-03-30 14:36:54 -07005356 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 framesReq = bufferEnd - u;
5358 }
5359
5360 buffer->frameCount = framesReq;
5361 buffer->raw = (void *)cblk->buffer(u);
5362 return NO_ERROR;
5363}
5364
5365
5366void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5367{
5368 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369
5370 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005371 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 delete [] pBuffer->mBuffer;
5373 delete pBuffer;
5374 }
5375 mBufferQueue.clear();
5376}
5377
5378// ----------------------------------------------------------------------------
5379
5380AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5381 : RefBase(),
5382 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005383 // 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 -07005384 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005385 mPid(pid),
5386 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387{
5388 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5389}
5390
5391// Client destructor must be called with AudioFlinger::mLock held
5392AudioFlinger::Client::~Client()
5393{
5394 mAudioFlinger->removeClient_l(mPid);
5395}
5396
Glenn Kasten435dbe62012-01-30 10:15:48 -08005397sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398{
5399 return mMemoryDealer;
5400}
5401
John Grossman4ff14ba2012-02-08 16:37:41 -08005402// Reserve one of the limited slots for a timed audio track associated
5403// with this client
5404bool AudioFlinger::Client::reserveTimedTrack()
5405{
5406 const int kMaxTimedTracksPerClient = 4;
5407
5408 Mutex::Autolock _l(mTimedTrackLock);
5409
5410 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5411 ALOGW("can not create timed track - pid %d has exceeded the limit",
5412 mPid);
5413 return false;
5414 }
5415
5416 mTimedTrackCount++;
5417 return true;
5418}
5419
5420// Release a slot for a timed audio track
5421void AudioFlinger::Client::releaseTimedTrack()
5422{
5423 Mutex::Autolock _l(mTimedTrackLock);
5424 mTimedTrackCount--;
5425}
5426
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427// ----------------------------------------------------------------------------
5428
5429AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5430 const sp<IAudioFlingerClient>& client,
5431 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005432 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433{
5434}
5435
5436AudioFlinger::NotificationClient::~NotificationClient()
5437{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438}
5439
5440void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5441{
5442 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005443 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444}
5445
5446// ----------------------------------------------------------------------------
5447
5448AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5449 : BnAudioTrack(),
5450 mTrack(track)
5451{
5452}
5453
5454AudioFlinger::TrackHandle::~TrackHandle() {
5455 // just stop the track on deletion, associated resources
5456 // will be freed from the main thread once all pending buffers have
5457 // been played. Unless it's not in the active track list, in which
5458 // case we free everything now...
5459 mTrack->destroy();
5460}
5461
Glenn Kasten90716c52012-01-26 13:40:12 -08005462sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5463 return mTrack->getCblk();
5464}
5465
Glenn Kasten3acbd052012-02-28 10:39:56 -08005466status_t AudioFlinger::TrackHandle::start() {
5467 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468}
5469
5470void AudioFlinger::TrackHandle::stop() {
5471 mTrack->stop();
5472}
5473
5474void AudioFlinger::TrackHandle::flush() {
5475 mTrack->flush();
5476}
5477
5478void AudioFlinger::TrackHandle::mute(bool e) {
5479 mTrack->mute(e);
5480}
5481
5482void AudioFlinger::TrackHandle::pause() {
5483 mTrack->pause();
5484}
5485
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5487{
5488 return mTrack->attachAuxEffect(EffectId);
5489}
5490
John Grossman4ff14ba2012-02-08 16:37:41 -08005491status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5492 sp<IMemory>* buffer) {
5493 if (!mTrack->isTimedTrack())
5494 return INVALID_OPERATION;
5495
5496 PlaybackThread::TimedTrack* tt =
5497 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5498 return tt->allocateTimedBuffer(size, buffer);
5499}
5500
5501status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5502 int64_t pts) {
5503 if (!mTrack->isTimedTrack())
5504 return INVALID_OPERATION;
5505
5506 PlaybackThread::TimedTrack* tt =
5507 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5508 return tt->queueTimedBuffer(buffer, pts);
5509}
5510
5511status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5512 const LinearTransform& xform, int target) {
5513
5514 if (!mTrack->isTimedTrack())
5515 return INVALID_OPERATION;
5516
5517 PlaybackThread::TimedTrack* tt =
5518 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5519 return tt->setMediaTimeTransform(
5520 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5521}
5522
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523status_t AudioFlinger::TrackHandle::onTransact(
5524 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5525{
5526 return BnAudioTrack::onTransact(code, data, reply, flags);
5527}
5528
5529// ----------------------------------------------------------------------------
5530
5531sp<IAudioRecord> AudioFlinger::openRecord(
5532 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005533 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005535 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005536 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005538 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 int *sessionId,
5540 status_t *status)
5541{
5542 sp<RecordThread::RecordTrack> recordTrack;
5543 sp<RecordHandle> recordHandle;
5544 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 status_t lStatus;
5546 RecordThread *thread;
5547 size_t inFrameCount;
5548 int lSessionId;
5549
5550 // check calling permissions
5551 if (!recordingAllowed()) {
5552 lStatus = PERMISSION_DENIED;
5553 goto Exit;
5554 }
5555
5556 // add client to list
5557 { // scope for mLock
5558 Mutex::Autolock _l(mLock);
5559 thread = checkRecordThread_l(input);
5560 if (thread == NULL) {
5561 lStatus = BAD_VALUE;
5562 goto Exit;
5563 }
5564
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005565 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005566
5567 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005568 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 lSessionId = *sessionId;
5570 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005571 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 if (sessionId != NULL) {
5573 *sessionId = lSessionId;
5574 }
5575 }
5576 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005577 recordTrack = thread->createRecordTrack_l(client,
5578 sampleRate,
5579 format,
5580 channelMask,
5581 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005582 lSessionId,
5583 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005585 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5587 // destructor is called by the TrackBase destructor with mLock held
5588 client.clear();
5589 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 goto Exit;
5591 }
5592
5593 // return to handle to client
5594 recordHandle = new RecordHandle(recordTrack);
5595 lStatus = NO_ERROR;
5596
5597Exit:
5598 if (status) {
5599 *status = lStatus;
5600 }
5601 return recordHandle;
5602}
5603
5604// ----------------------------------------------------------------------------
5605
5606AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5607 : BnAudioRecord(),
5608 mRecordTrack(recordTrack)
5609{
5610}
5611
5612AudioFlinger::RecordHandle::~RecordHandle() {
5613 stop();
5614}
5615
Glenn Kasten90716c52012-01-26 13:40:12 -08005616sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5617 return mRecordTrack->getCblk();
5618}
5619
Glenn Kasten3acbd052012-02-28 10:39:56 -08005620status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005621 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005622 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623}
5624
5625void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005626 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 mRecordTrack->stop();
5628}
5629
Mathias Agopian65ab4712010-07-14 17:59:35 -07005630status_t AudioFlinger::RecordHandle::onTransact(
5631 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5632{
5633 return BnAudioRecord::onTransact(code, data, reply, flags);
5634}
5635
5636// ----------------------------------------------------------------------------
5637
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005638AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5639 AudioStreamIn *input,
5640 uint32_t sampleRate,
5641 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005642 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005643 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005644 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005645 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5646 // mRsmpInIndex and mInputBytes set by readInputParameters()
5647 mReqChannelCount(popcount(channels)),
5648 mReqSampleRate(sampleRate)
5649 // mBytesRead is only meaningful while active, and so is cleared in start()
5650 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651{
Glenn Kasten480b4682012-02-28 12:30:08 -08005652 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005653
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654 readInputParameters();
5655}
5656
5657
5658AudioFlinger::RecordThread::~RecordThread()
5659{
5660 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005661 delete mResampler;
5662 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663}
5664
5665void AudioFlinger::RecordThread::onFirstRef()
5666{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005667 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668}
5669
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005670status_t AudioFlinger::RecordThread::readyToRun()
5671{
5672 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005673 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005674 return status;
5675}
5676
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677bool AudioFlinger::RecordThread::threadLoop()
5678{
5679 AudioBufferProvider::Buffer buffer;
5680 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005681 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682
Eric Laurent44d98482010-09-30 16:12:31 -07005683 nsecs_t lastWarning = 0;
5684
Eric Laurentfeb0db62011-07-22 09:04:31 -07005685 acquireWakeLock();
5686
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 // start recording
5688 while (!exitPending()) {
5689
5690 processConfigEvents();
5691
5692 { // scope for mLock
5693 Mutex::Autolock _l(mLock);
5694 checkForNewParameters_l();
5695 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5696 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005697 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 mStandby = true;
5699 }
5700
5701 if (exitPending()) break;
5702
Eric Laurentfeb0db62011-07-22 09:04:31 -07005703 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005704 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 // go to sleep
5706 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005707 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005708 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 continue;
5710 }
5711 if (mActiveTrack != 0) {
5712 if (mActiveTrack->mState == TrackBase::PAUSING) {
5713 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005714 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 mStandby = true;
5716 }
5717 mActiveTrack.clear();
5718 mStartStopCond.broadcast();
5719 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5720 if (mReqChannelCount != mActiveTrack->channelCount()) {
5721 mActiveTrack.clear();
5722 mStartStopCond.broadcast();
5723 } else if (mBytesRead != 0) {
5724 // record start succeeds only if first read from audio input
5725 // succeeds
5726 if (mBytesRead > 0) {
5727 mActiveTrack->mState = TrackBase::ACTIVE;
5728 } else {
5729 mActiveTrack.clear();
5730 }
5731 mStartStopCond.broadcast();
5732 }
5733 mStandby = false;
5734 }
5735 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005736 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 }
5738
5739 if (mActiveTrack != 0) {
5740 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5741 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005742 unlockEffectChains(effectChains);
5743 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744 continue;
5745 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005746 for (size_t i = 0; i < effectChains.size(); i ++) {
5747 effectChains[i]->process_l();
5748 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005749
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005751 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005753 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 // no resampling
5755 while (framesOut) {
5756 size_t framesIn = mFrameCount - mRsmpInIndex;
5757 if (framesIn) {
5758 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5759 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5760 if (framesIn > framesOut)
5761 framesIn = framesOut;
5762 mRsmpInIndex += framesIn;
5763 framesOut -= framesIn;
5764 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005765 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766 memcpy(dst, src, framesIn * mFrameSize);
5767 } else {
5768 int16_t *src16 = (int16_t *)src;
5769 int16_t *dst16 = (int16_t *)dst;
5770 if (mChannelCount == 1) {
5771 while (framesIn--) {
5772 *dst16++ = *src16;
5773 *dst16++ = *src16++;
5774 }
5775 } else {
5776 while (framesIn--) {
5777 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5778 src16 += 2;
5779 }
5780 }
5781 }
5782 }
5783 if (framesOut && mFrameCount == mRsmpInIndex) {
5784 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005785 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005786 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787 framesOut = 0;
5788 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005789 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 mRsmpInIndex = 0;
5791 }
5792 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005793 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5795 // Force input into standby so that it tries to
5796 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005797 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005798 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 }
5800 mRsmpInIndex = mFrameCount;
5801 framesOut = 0;
5802 buffer.frameCount = 0;
5803 }
5804 }
5805 }
5806 } else {
5807 // resampling
5808
5809 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5810 // alter output frame count as if we were expecting stereo samples
5811 if (mChannelCount == 1 && mReqChannelCount == 1) {
5812 framesOut >>= 1;
5813 }
5814 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5815 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5816 // are 32 bit aligned which should be always true.
5817 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005818 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 // the resampler always outputs stereo samples: do post stereo to mono conversion
5820 int16_t *src = (int16_t *)mRsmpOutBuffer;
5821 int16_t *dst = buffer.i16;
5822 while (framesOut--) {
5823 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5824 src += 2;
5825 }
5826 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005827 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 }
5829
5830 }
Eric Laurenta011e352012-03-29 15:51:43 -07005831 if (mFramestoDrop == 0) {
5832 mActiveTrack->releaseBuffer(&buffer);
5833 } else {
5834 if (mFramestoDrop > 0) {
5835 mFramestoDrop -= buffer.frameCount;
5836 if (mFramestoDrop < 0) {
5837 mFramestoDrop = 0;
5838 }
5839 }
5840 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 mActiveTrack->overflow();
5842 }
5843 // client isn't retrieving buffers fast enough
5844 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005845 if (!mActiveTrack->setOverflow()) {
5846 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005847 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005848 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005849 lastWarning = now;
5850 }
5851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852 // Release the processor for a while before asking for a new buffer.
5853 // This will give the application more chance to read from the buffer and
5854 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005855 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 }
5857 }
Eric Laurentec437d82011-07-26 20:54:46 -07005858 // enable changes in effect chain
5859 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005860 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861 }
5862
5863 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005864 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865 }
5866 mActiveTrack.clear();
5867
5868 mStartStopCond.broadcast();
5869
Eric Laurentfeb0db62011-07-22 09:04:31 -07005870 releaseWakeLock();
5871
Steve Block3856b092011-10-20 11:56:00 +01005872 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 return false;
5874}
5875
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005876
5877sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5878 const sp<AudioFlinger::Client>& client,
5879 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005880 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005881 int channelMask,
5882 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005883 int sessionId,
5884 status_t *status)
5885{
5886 sp<RecordTrack> track;
5887 status_t lStatus;
5888
5889 lStatus = initCheck();
5890 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005891 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005892 goto Exit;
5893 }
5894
5895 { // scope for mLock
5896 Mutex::Autolock _l(mLock);
5897
5898 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005899 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900
Glenn Kasten7378ca52012-01-20 13:44:40 -08005901 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005902 lStatus = NO_MEMORY;
5903 goto Exit;
5904 }
5905
5906 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005907 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5908 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005909 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005910 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5911 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005912 }
5913 lStatus = NO_ERROR;
5914
5915Exit:
5916 if (status) {
5917 *status = lStatus;
5918 }
5919 return track;
5920}
5921
Eric Laurenta011e352012-03-29 15:51:43 -07005922status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005923 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005924 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925{
Glenn Kasten58912562012-04-03 10:45:00 -07005926 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005927 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005929
5930 if (event == AudioSystem::SYNC_EVENT_NONE) {
5931 mSyncStartEvent.clear();
5932 mFramestoDrop = 0;
5933 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5934 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5935 triggerSession,
5936 recordTrack->sessionId(),
5937 syncStartEventCallback,
5938 this);
5939 mFramestoDrop = -1;
5940 }
5941
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005943 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 if (mActiveTrack != 0) {
5945 if (recordTrack != mActiveTrack.get()) {
5946 status = -EBUSY;
5947 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5948 mActiveTrack->mState = TrackBase::ACTIVE;
5949 }
5950 return status;
5951 }
5952
5953 recordTrack->mState = TrackBase::IDLE;
5954 mActiveTrack = recordTrack;
5955 mLock.unlock();
5956 status_t status = AudioSystem::startInput(mId);
5957 mLock.lock();
5958 if (status != NO_ERROR) {
5959 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005960 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 return status;
5962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 mRsmpInIndex = mFrameCount;
5964 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005965 if (mResampler != NULL) {
5966 mResampler->reset();
5967 }
5968 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005970 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 mWaitWorkCV.signal();
5972 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005973 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 mActiveTrack.clear();
5975 status = INVALID_OPERATION;
5976 goto startError;
5977 }
5978 mStartStopCond.wait(mLock);
5979 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005980 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 status = BAD_VALUE;
5982 goto startError;
5983 }
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 return status;
5986 }
5987startError:
5988 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005989 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 return status;
5991}
5992
Eric Laurenta011e352012-03-29 15:51:43 -07005993void AudioFlinger::RecordThread::clearSyncStartEvent()
5994{
5995 if (mSyncStartEvent != 0) {
5996 mSyncStartEvent->cancel();
5997 }
5998 mSyncStartEvent.clear();
5999}
6000
6001void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6002{
6003 sp<SyncEvent> strongEvent = event.promote();
6004
6005 if (strongEvent != 0) {
6006 RecordThread *me = (RecordThread *)strongEvent->cookie();
6007 me->handleSyncStartEvent(strongEvent);
6008 }
6009}
6010
6011void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6012{
6013 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6014 mActiveTrack.get(),
6015 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6016 event->listenerSession());
6017
6018 if (mActiveTrack != 0 &&
6019 event == mSyncStartEvent) {
6020 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6021 // from audio HAL
6022 mFramestoDrop = mFrameCount * 2;
6023 mSyncStartEvent.clear();
6024 }
6025}
6026
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006028 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006029 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006031 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6033 mActiveTrack->mState = TrackBase::PAUSING;
6034 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006035 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 return;
6037 }
6038 mStartStopCond.wait(mLock);
6039 // if we have been restarted, recordTrack == mActiveTrack.get() here
6040 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6041 mLock.unlock();
6042 AudioSystem::stopInput(mId);
6043 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006044 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045 }
6046 }
6047 }
6048}
6049
Eric Laurenta011e352012-03-29 15:51:43 -07006050bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6051{
6052 return false;
6053}
6054
6055status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6056{
6057 if (!isValidSyncEvent(event)) {
6058 return BAD_VALUE;
6059 }
6060
6061 Mutex::Autolock _l(mLock);
6062
6063 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6064 mTrack->setSyncEvent(event);
6065 return NO_ERROR;
6066 }
6067 return NAME_NOT_FOUND;
6068}
6069
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6071{
6072 const size_t SIZE = 256;
6073 char buffer[SIZE];
6074 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075
6076 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6077 result.append(buffer);
6078
6079 if (mActiveTrack != 0) {
6080 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006081 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 mActiveTrack->dump(buffer, SIZE);
6083 result.append(buffer);
6084
6085 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6086 result.append(buffer);
6087 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6088 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006089 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090 result.append(buffer);
6091 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6092 result.append(buffer);
6093 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6094 result.append(buffer);
6095
6096
6097 } else {
6098 result.append("No record client\n");
6099 }
6100 write(fd, result.string(), result.size());
6101
6102 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006103 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104
6105 return NO_ERROR;
6106}
6107
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006108// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006109status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110{
6111 size_t framesReq = buffer->frameCount;
6112 size_t framesReady = mFrameCount - mRsmpInIndex;
6113 int channelCount;
6114
6115 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006116 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006118 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6120 // Force input into standby so that it tries to
6121 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006122 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006123 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006125 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 buffer->frameCount = 0;
6127 return NOT_ENOUGH_DATA;
6128 }
6129 mRsmpInIndex = 0;
6130 framesReady = mFrameCount;
6131 }
6132
6133 if (framesReq > framesReady) {
6134 framesReq = framesReady;
6135 }
6136
6137 if (mChannelCount == 1 && mReqChannelCount == 2) {
6138 channelCount = 1;
6139 } else {
6140 channelCount = 2;
6141 }
6142 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6143 buffer->frameCount = framesReq;
6144 return NO_ERROR;
6145}
6146
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006147// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6149{
6150 mRsmpInIndex += buffer->frameCount;
6151 buffer->frameCount = 0;
6152}
6153
6154bool AudioFlinger::RecordThread::checkForNewParameters_l()
6155{
6156 bool reconfig = false;
6157
6158 while (!mNewParameters.isEmpty()) {
6159 status_t status = NO_ERROR;
6160 String8 keyValuePair = mNewParameters[0];
6161 AudioParameter param = AudioParameter(keyValuePair);
6162 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006163 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 int reqSamplingRate = mReqSampleRate;
6165 int reqChannelCount = mReqChannelCount;
6166
6167 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6168 reqSamplingRate = value;
6169 reconfig = true;
6170 }
6171 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006172 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 reconfig = true;
6174 }
6175 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006176 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 reconfig = true;
6178 }
6179 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6180 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006181 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 // if frame count is changed after track creation
6183 if (mActiveTrack != 0) {
6184 status = INVALID_OPERATION;
6185 } else {
6186 reconfig = true;
6187 }
6188 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006189 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6190 // forward device change to effects that have requested to be
6191 // aware of attached audio device.
6192 for (size_t i = 0; i < mEffectChains.size(); i++) {
6193 mEffectChains[i]->setDevice_l(value);
6194 }
6195 // store input device and output device but do not forward output device to audio HAL.
6196 // Note that status is ignored by the caller for output device
6197 // (see AudioFlinger::setParameters()
6198 if (value & AUDIO_DEVICE_OUT_ALL) {
6199 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6200 status = BAD_VALUE;
6201 } else {
6202 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006203 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6204 if (mTrack != NULL) {
6205 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006206 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006207 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6208 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6209 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006210 }
6211 mDevice |= (uint32_t)value;
6212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006214 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006216 mInput->stream->common.standby(&mInput->stream->common);
6217 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6218 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 }
6220 if (reconfig) {
6221 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006222 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006223 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006224 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006225 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6226 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 status = NO_ERROR;
6228 }
6229 if (status == NO_ERROR) {
6230 readInputParameters();
6231 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6232 }
6233 }
6234 }
6235
6236 mNewParameters.removeAt(0);
6237
6238 mParamStatus = status;
6239 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006240 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6241 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006242 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 }
6244 return reconfig;
6245}
6246
6247String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6248{
Dima Zavinfce7a472011-04-19 22:30:36 -07006249 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006250 String8 out_s8 = String8();
6251
6252 Mutex::Autolock _l(mLock);
6253 if (initCheck() != NO_ERROR) {
6254 return out_s8;
6255 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006256
Dima Zavin799a70e2011-04-18 16:57:27 -07006257 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006258 out_s8 = String8(s);
6259 free(s);
6260 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261}
6262
6263void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6264 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006265 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266
6267 switch (event) {
6268 case AudioSystem::INPUT_OPENED:
6269 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006270 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 desc.samplingRate = mSampleRate;
6272 desc.format = mFormat;
6273 desc.frameCount = mFrameCount;
6274 desc.latency = 0;
6275 param2 = &desc;
6276 break;
6277
6278 case AudioSystem::INPUT_CLOSED:
6279 default:
6280 break;
6281 }
6282 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6283}
6284
6285void AudioFlinger::RecordThread::readInputParameters()
6286{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006287 delete mRsmpInBuffer;
6288 // mRsmpInBuffer is always assigned a new[] below
6289 delete mRsmpOutBuffer;
6290 mRsmpOutBuffer = NULL;
6291 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006292 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293
Dima Zavin799a70e2011-04-18 16:57:27 -07006294 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006295 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6296 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006297 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006298 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006299 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006301 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6303
Glenn Kasten53d76db2012-03-08 12:32:47 -08006304 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 {
6306 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006307 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6308 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309 if (mChannelCount == 1 && mReqChannelCount == 2) {
6310 channelCount = 1;
6311 } else {
6312 channelCount = 2;
6313 }
6314 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6315 mResampler->setSampleRate(mSampleRate);
6316 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6317 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6318
6319 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6320 if (mChannelCount == 1 && mReqChannelCount == 1) {
6321 mFrameCount >>= 1;
6322 }
6323
6324 }
6325 mRsmpInIndex = mFrameCount;
6326}
6327
6328unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6329{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006330 Mutex::Autolock _l(mLock);
6331 if (initCheck() != NO_ERROR) {
6332 return 0;
6333 }
6334
Dima Zavin799a70e2011-04-18 16:57:27 -07006335 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336}
6337
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006338uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6339{
6340 Mutex::Autolock _l(mLock);
6341 uint32_t result = 0;
6342 if (getEffectChain_l(sessionId) != 0) {
6343 result = EFFECT_SESSION;
6344 }
6345
6346 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6347 result |= TRACK_SESSION;
6348 }
6349
6350 return result;
6351}
6352
Eric Laurent59bd0da2011-08-01 09:52:20 -07006353AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6354{
6355 Mutex::Autolock _l(mLock);
6356 return mTrack;
6357}
6358
Glenn Kastenaed850d2012-01-26 09:46:34 -08006359AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006360{
6361 Mutex::Autolock _l(mLock);
6362 return mInput;
6363}
6364
6365AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6366{
6367 Mutex::Autolock _l(mLock);
6368 AudioStreamIn *input = mInput;
6369 mInput = NULL;
6370 return input;
6371}
6372
6373// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006374audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006375{
6376 if (mInput == NULL) {
6377 return NULL;
6378 }
6379 return &mInput->stream->common;
6380}
6381
6382
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383// ----------------------------------------------------------------------------
6384
Eric Laurenta4c5a552012-03-29 10:12:40 -07006385audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6386{
6387 if (!settingsAllowed()) {
6388 return 0;
6389 }
6390 Mutex::Autolock _l(mLock);
6391 return loadHwModule_l(name);
6392}
6393
6394// loadHwModule_l() must be called with AudioFlinger::mLock held
6395audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6396{
6397 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6398 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6399 ALOGW("loadHwModule() module %s already loaded", name);
6400 return mAudioHwDevs.keyAt(i);
6401 }
6402 }
6403
Eric Laurenta4c5a552012-03-29 10:12:40 -07006404 audio_hw_device_t *dev;
6405
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006406 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006407 if (rc) {
6408 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6409 return 0;
6410 }
6411
6412 mHardwareStatus = AUDIO_HW_INIT;
6413 rc = dev->init_check(dev);
6414 mHardwareStatus = AUDIO_HW_IDLE;
6415 if (rc) {
6416 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6417 return 0;
6418 }
6419
6420 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6421 (NULL != dev->set_master_volume)) {
6422 AutoMutex lock(mHardwareLock);
6423 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6424 dev->set_master_volume(dev, mMasterVolume);
6425 mHardwareStatus = AUDIO_HW_IDLE;
6426 }
6427
6428 audio_module_handle_t handle = nextUniqueId();
6429 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6430
6431 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006432 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006433
6434 return handle;
6435
6436}
6437
6438audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6439 audio_devices_t *pDevices,
6440 uint32_t *pSamplingRate,
6441 audio_format_t *pFormat,
6442 audio_channel_mask_t *pChannelMask,
6443 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006444 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445{
6446 status_t status;
6447 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006448 struct audio_config config = {
6449 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6450 channel_mask: pChannelMask ? *pChannelMask : 0,
6451 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6452 };
6453 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006454 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455
Eric Laurenta4c5a552012-03-29 10:12:40 -07006456 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6457 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006458 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006459 config.sample_rate,
6460 config.format,
6461 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006462 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463
6464 if (pDevices == NULL || *pDevices == 0) {
6465 return 0;
6466 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006467
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 Mutex::Autolock _l(mLock);
6469
Eric Laurenta4c5a552012-03-29 10:12:40 -07006470 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006471 if (outHwDev == NULL)
6472 return 0;
6473
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006474 audio_io_handle_t id = nextUniqueId();
6475
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006476 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006477
6478 status = outHwDev->open_output_stream(outHwDev,
6479 id,
6480 *pDevices,
6481 (audio_output_flags_t)flags,
6482 &config,
6483 &outStream);
6484
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006485 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006486 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006487 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006488 config.sample_rate,
6489 config.format,
6490 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 status);
6492
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006493 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006494 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006495
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006496 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006497 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6498 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006500 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 } else {
6502 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006503 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 }
6505 mPlaybackThreads.add(id, thread);
6506
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006507 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6508 if (pFormat != NULL) *pFormat = config.format;
6509 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006510 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511
6512 // notify client processes of the new output creation
6513 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006514
6515 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006516 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006517 ALOGI("Using module %d has the primary audio interface", module);
6518 mPrimaryHardwareDev = outHwDev;
6519
6520 AutoMutex lock(mHardwareLock);
6521 mHardwareStatus = AUDIO_HW_SET_MODE;
6522 outHwDev->set_mode(outHwDev, mMode);
6523
6524 // Determine the level of master volume support the primary audio HAL has,
6525 // and set the initial master volume at the same time.
6526 float initialVolume = 1.0;
6527 mMasterVolumeSupportLvl = MVS_NONE;
6528
6529 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6530 if ((NULL != outHwDev->get_master_volume) &&
6531 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6532 mMasterVolumeSupportLvl = MVS_FULL;
6533 } else {
6534 mMasterVolumeSupportLvl = MVS_SETONLY;
6535 initialVolume = 1.0;
6536 }
6537
6538 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6539 if ((NULL == outHwDev->set_master_volume) ||
6540 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6541 mMasterVolumeSupportLvl = MVS_NONE;
6542 }
6543 // now that we have a primary device, initialize master volume on other devices
6544 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6545 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6546
6547 if ((dev != mPrimaryHardwareDev) &&
6548 (NULL != dev->set_master_volume)) {
6549 dev->set_master_volume(dev, initialVolume);
6550 }
6551 }
6552 mHardwareStatus = AUDIO_HW_IDLE;
6553 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6554 ? initialVolume
6555 : 1.0;
6556 mMasterVolume = initialVolume;
6557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 return id;
6559 }
6560
6561 return 0;
6562}
6563
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006564audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6565 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566{
6567 Mutex::Autolock _l(mLock);
6568 MixerThread *thread1 = checkMixerThread_l(output1);
6569 MixerThread *thread2 = checkMixerThread_l(output2);
6570
6571 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006572 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 return 0;
6574 }
6575
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006576 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6578 thread->addOutputTrack(thread2);
6579 mPlaybackThreads.add(id, thread);
6580 // notify client processes of the new output creation
6581 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6582 return id;
6583}
6584
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006585status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586{
6587 // keep strong reference on the playback thread so that
6588 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006589 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 {
6591 Mutex::Autolock _l(mLock);
6592 thread = checkPlaybackThread_l(output);
6593 if (thread == NULL) {
6594 return BAD_VALUE;
6595 }
6596
Steve Block3856b092011-10-20 11:56:00 +01006597 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006599 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006601 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6603 dupThread->removeOutputTrack((MixerThread *)thread.get());
6604 }
6605 }
6606 }
Glenn Kastena1117922012-01-26 10:53:32 -08006607 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 mPlaybackThreads.removeItem(output);
6609 }
6610 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006611 // The thread entity (active unit of execution) is no longer running here,
6612 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006614 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006615 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006616 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006617 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006618 out->hwDev->close_output_stream(out->hwDev, out->stream);
6619 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 }
6621 return NO_ERROR;
6622}
6623
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006624status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625{
6626 Mutex::Autolock _l(mLock);
6627 PlaybackThread *thread = checkPlaybackThread_l(output);
6628
6629 if (thread == NULL) {
6630 return BAD_VALUE;
6631 }
6632
Steve Block3856b092011-10-20 11:56:00 +01006633 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 thread->suspend();
6635
6636 return NO_ERROR;
6637}
6638
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006639status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640{
6641 Mutex::Autolock _l(mLock);
6642 PlaybackThread *thread = checkPlaybackThread_l(output);
6643
6644 if (thread == NULL) {
6645 return BAD_VALUE;
6646 }
6647
Steve Block3856b092011-10-20 11:56:00 +01006648 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649
6650 thread->restore();
6651
6652 return NO_ERROR;
6653}
6654
Eric Laurenta4c5a552012-03-29 10:12:40 -07006655audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6656 audio_devices_t *pDevices,
6657 uint32_t *pSamplingRate,
6658 audio_format_t *pFormat,
6659 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660{
6661 status_t status;
6662 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006663 struct audio_config config = {
6664 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6665 channel_mask: pChannelMask ? *pChannelMask : 0,
6666 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6667 };
6668 uint32_t reqSamplingRate = config.sample_rate;
6669 audio_format_t reqFormat = config.format;
6670 audio_channel_mask_t reqChannels = config.channel_mask;
6671 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006672 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673
6674 if (pDevices == NULL || *pDevices == 0) {
6675 return 0;
6676 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006677
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678 Mutex::Autolock _l(mLock);
6679
Eric Laurenta4c5a552012-03-29 10:12:40 -07006680 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006681 if (inHwDev == NULL)
6682 return 0;
6683
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006684 audio_io_handle_t id = nextUniqueId();
6685
6686 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006687 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006688 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006689 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006690 config.sample_rate,
6691 config.format,
6692 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693 status);
6694
6695 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6696 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6697 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006698 if (status == BAD_VALUE &&
6699 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6700 (config.sample_rate <= 2 * reqSamplingRate) &&
6701 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006702 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006703 inStream = NULL;
6704 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006705 }
6706
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006707 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006708 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6709
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006710 // Start record thread
6711 // RecorThread require both input and output device indication to forward to audio
6712 // pre processing modules
6713 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6714 thread = new RecordThread(this,
6715 input,
6716 reqSamplingRate,
6717 reqChannels,
6718 id,
6719 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006721 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006722 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006723 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006724 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725
Dima Zavin799a70e2011-04-18 16:57:27 -07006726 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727
6728 // notify client processes of the new input creation
6729 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6730 return id;
6731 }
6732
6733 return 0;
6734}
6735
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006736status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737{
6738 // keep strong reference on the record thread so that
6739 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006740 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 {
6742 Mutex::Autolock _l(mLock);
6743 thread = checkRecordThread_l(input);
6744 if (thread == NULL) {
6745 return BAD_VALUE;
6746 }
6747
Steve Block3856b092011-10-20 11:56:00 +01006748 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006749 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750 mRecordThreads.removeItem(input);
6751 }
6752 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006753 // The thread entity (active unit of execution) is no longer running here,
6754 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006756 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006757 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006758 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006759 in->hwDev->close_input_stream(in->hwDev, in->stream);
6760 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761
6762 return NO_ERROR;
6763}
6764
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006765status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006766{
6767 Mutex::Autolock _l(mLock);
6768 MixerThread *dstThread = checkMixerThread_l(output);
6769 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006770 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 return BAD_VALUE;
6772 }
6773
Steve Block3856b092011-10-20 11:56:00 +01006774 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6776
6777 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6778 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006779 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 MixerThread *srcThread = (MixerThread *)thread;
6781 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782 }
Eric Laurentde070132010-07-13 04:45:46 -07006783 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006784
6785 return NO_ERROR;
6786}
6787
6788
6789int AudioFlinger::newAudioSessionId()
6790{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006791 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792}
6793
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006794void AudioFlinger::acquireAudioSessionId(int audioSession)
6795{
6796 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006797 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006798 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006799 size_t num = mAudioSessionRefs.size();
6800 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006801 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006802 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6803 ref->mCnt++;
6804 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006805 return;
6806 }
6807 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006808 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6809 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006810}
6811
6812void AudioFlinger::releaseAudioSessionId(int audioSession)
6813{
6814 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006815 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006816 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006817 size_t num = mAudioSessionRefs.size();
6818 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006819 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006820 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6821 ref->mCnt--;
6822 ALOGV(" decremented refcount to %d", ref->mCnt);
6823 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006824 mAudioSessionRefs.removeAt(i);
6825 delete ref;
6826 purgeStaleEffects_l();
6827 }
6828 return;
6829 }
6830 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006831 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006832}
6833
6834void AudioFlinger::purgeStaleEffects_l() {
6835
Steve Block3856b092011-10-20 11:56:00 +01006836 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006837
6838 Vector< sp<EffectChain> > chains;
6839
6840 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6841 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6842 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6843 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006844 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6845 chains.push(ec);
6846 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006847 }
6848 }
6849 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6850 sp<RecordThread> t = mRecordThreads.valueAt(i);
6851 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6852 sp<EffectChain> ec = t->mEffectChains[j];
6853 chains.push(ec);
6854 }
6855 }
6856
6857 for (size_t i = 0; i < chains.size(); i++) {
6858 sp<EffectChain> ec = chains[i];
6859 int sessionid = ec->sessionId();
6860 sp<ThreadBase> t = ec->mThread.promote();
6861 if (t == 0) {
6862 continue;
6863 }
6864 size_t numsessionrefs = mAudioSessionRefs.size();
6865 bool found = false;
6866 for (size_t k = 0; k < numsessionrefs; k++) {
6867 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006868 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006869 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006870 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006871 found = true;
6872 break;
6873 }
6874 }
6875 if (!found) {
6876 // remove all effects from the chain
6877 while (ec->mEffects.size()) {
6878 sp<EffectModule> effect = ec->mEffects[0];
6879 effect->unPin();
6880 Mutex::Autolock _l (t->mLock);
6881 t->removeEffect_l(effect);
6882 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6883 sp<EffectHandle> handle = effect->mHandles[j].promote();
6884 if (handle != 0) {
6885 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006886 if (handle->mHasControl && handle->mEnabled) {
6887 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6888 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006889 }
6890 }
6891 AudioSystem::unregisterEffect(effect->id());
6892 }
6893 }
6894 }
6895 return;
6896}
6897
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006899AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900{
Glenn Kastena1117922012-01-26 10:53:32 -08006901 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902}
6903
6904// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006905AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906{
6907 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006908 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909}
6910
6911// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006912AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913{
Glenn Kastena1117922012-01-26 10:53:32 -08006914 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915}
6916
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006917uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006919 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920}
6921
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006922AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006923{
6924 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6925 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006926 AudioStreamOut *output = thread->getOutput();
6927 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006928 return thread;
6929 }
6930 }
6931 return NULL;
6932}
6933
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006934uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006935{
6936 PlaybackThread *thread = primaryPlaybackThread_l();
6937
6938 if (thread == NULL) {
6939 return 0;
6940 }
6941
6942 return thread->device();
6943}
6944
Eric Laurenta011e352012-03-29 15:51:43 -07006945sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6946 int triggerSession,
6947 int listenerSession,
6948 sync_event_callback_t callBack,
6949 void *cookie)
6950{
6951 Mutex::Autolock _l(mLock);
6952
6953 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6954 status_t playStatus = NAME_NOT_FOUND;
6955 status_t recStatus = NAME_NOT_FOUND;
6956 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6957 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6958 if (playStatus == NO_ERROR) {
6959 return event;
6960 }
6961 }
6962 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6963 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6964 if (recStatus == NO_ERROR) {
6965 return event;
6966 }
6967 }
6968 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6969 mPendingSyncEvents.add(event);
6970 } else {
6971 ALOGV("createSyncEvent() invalid event %d", event->type());
6972 event.clear();
6973 }
6974 return event;
6975}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006976
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977// ----------------------------------------------------------------------------
6978// Effect management
6979// ----------------------------------------------------------------------------
6980
6981
Glenn Kastenf587ba52012-01-26 16:25:10 -08006982status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983{
6984 Mutex::Autolock _l(mLock);
6985 return EffectQueryNumberEffects(numEffects);
6986}
6987
Glenn Kastenf587ba52012-01-26 16:25:10 -08006988status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989{
6990 Mutex::Autolock _l(mLock);
6991 return EffectQueryEffect(index, descriptor);
6992}
6993
Glenn Kasten5e92a782012-01-30 07:40:52 -08006994status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006995 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996{
6997 Mutex::Autolock _l(mLock);
6998 return EffectGetDescriptor(pUuid, descriptor);
6999}
7000
7001
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7003 effect_descriptor_t *pDesc,
7004 const sp<IEffectClient>& effectClient,
7005 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007006 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 int sessionId,
7008 status_t *status,
7009 int *id,
7010 int *enabled)
7011{
7012 status_t lStatus = NO_ERROR;
7013 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007016 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007017 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018
7019 if (pDesc == NULL) {
7020 lStatus = BAD_VALUE;
7021 goto Exit;
7022 }
7023
Eric Laurent84e9a102010-09-23 16:10:16 -07007024 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007025 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007026 lStatus = PERMISSION_DENIED;
7027 goto Exit;
7028 }
7029
Dima Zavinfce7a472011-04-19 22:30:36 -07007030 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007031 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007032 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007033 lStatus = PERMISSION_DENIED;
7034 goto Exit;
7035 }
7036
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007037 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007038 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007039 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007040 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007041 lStatus = BAD_VALUE;
7042 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007043 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007044 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007045 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007046 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007047 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007048 }
7049 }
7050
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051 {
7052 Mutex::Autolock _l(mLock);
7053
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054
7055 if (!EffectIsNullUuid(&pDesc->uuid)) {
7056 // if uuid is specified, request effect descriptor
7057 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7058 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007059 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060 goto Exit;
7061 }
7062 } else {
7063 // if uuid is not specified, look for an available implementation
7064 // of the required type in effect factory
7065 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007066 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 lStatus = BAD_VALUE;
7068 goto Exit;
7069 }
7070 uint32_t numEffects = 0;
7071 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007072 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 bool found = false;
7074
7075 lStatus = EffectQueryNumberEffects(&numEffects);
7076 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007077 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 goto Exit;
7079 }
7080 for (uint32_t i = 0; i < numEffects; i++) {
7081 lStatus = EffectQueryEffect(i, &desc);
7082 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007083 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 continue;
7085 }
7086 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7087 // If matching type found save effect descriptor. If the session is
7088 // 0 and the effect is not auxiliary, continue enumeration in case
7089 // an auxiliary version of this effect type is available
7090 found = true;
7091 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007092 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7094 break;
7095 }
7096 }
7097 }
7098 if (!found) {
7099 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007100 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 goto Exit;
7102 }
7103 // For same effect type, chose auxiliary version over insert version if
7104 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007105 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007106 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7107 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7108 }
7109 }
7110
7111 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007112 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7114 lStatus = INVALID_OPERATION;
7115 goto Exit;
7116 }
7117
Eric Laurent59255e42011-07-27 19:49:51 -07007118 // check recording permission for visualizer
7119 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7120 !recordingAllowed()) {
7121 lStatus = PERMISSION_DENIED;
7122 goto Exit;
7123 }
7124
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 // return effect descriptor
7126 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7127
7128 // If output is not specified try to find a matching audio session ID in one of the
7129 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007130 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7131 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007132 // Note: io is never 0 when creating an effect on an input
7133 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007134 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007135 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7136 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007137 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007138 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007141 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007142 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7143 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7144 io = mRecordThreads.keyAt(i);
7145 break;
7146 }
7147 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007148 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007149 // If no output thread contains the requested session ID, default to
7150 // first output. The effect chain will be moved to the correct output
7151 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007152 if (io == 0 && mPlaybackThreads.size()) {
7153 io = mPlaybackThreads.keyAt(0);
7154 }
Steve Block3856b092011-10-20 11:56:00 +01007155 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007156 }
7157 ThreadBase *thread = checkRecordThread_l(io);
7158 if (thread == NULL) {
7159 thread = checkPlaybackThread_l(io);
7160 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007161 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007162 lStatus = BAD_VALUE;
7163 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007166
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007167 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007169 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007170 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7171 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 if (handle != 0 && id != NULL) {
7173 *id = handle->id();
7174 }
7175 }
7176
7177Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007178 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179 *status = lStatus;
7180 }
7181 return handle;
7182}
7183
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007184status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7185 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007186{
Steve Block3856b092011-10-20 11:56:00 +01007187 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007188 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007189 Mutex::Autolock _l(mLock);
7190 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007191 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007192 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 }
Eric Laurentde070132010-07-13 04:45:46 -07007194 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7195 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007196 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007197 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 }
Eric Laurentde070132010-07-13 04:45:46 -07007199 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7200 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007201 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007202 return BAD_VALUE;
7203 }
7204
7205 Mutex::Autolock _dl(dstThread->mLock);
7206 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007207 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007208
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209 return NO_ERROR;
7210}
7211
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007212// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007213status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007214 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007215 AudioFlinger::PlaybackThread *dstThread,
7216 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007217{
Steve Block3856b092011-10-20 11:56:00 +01007218 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007219 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007220
Eric Laurent59255e42011-07-27 19:49:51 -07007221 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007222 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007223 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007224 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007225 return INVALID_OPERATION;
7226 }
7227
Eric Laurent39e94f82010-07-28 01:32:47 -07007228 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007229 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007230 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007231 // removed.
7232 srcThread->removeEffectChain_l(chain);
7233
7234 // transfer all effects one by one so that new effect chain is created on new thread with
7235 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007236 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007237 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007238 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007239 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7240 while (effect != 0) {
7241 srcThread->removeEffect_l(effect);
7242 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007243 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7244 if (effect->state() == EffectModule::ACTIVE ||
7245 effect->state() == EffectModule::STOPPING) {
7246 effect->start();
7247 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007248 // if the move request is not received from audio policy manager, the effect must be
7249 // re-registered with the new strategy and output
7250 if (dstChain == 0) {
7251 dstChain = effect->chain().promote();
7252 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007253 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007254 srcThread->addEffect_l(effect);
7255 return NO_INIT;
7256 }
7257 strategy = dstChain->strategy();
7258 }
7259 if (reRegister) {
7260 AudioSystem::unregisterEffect(effect->id());
7261 AudioSystem::registerEffect(&effect->desc(),
7262 dstOutput,
7263 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007264 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007265 effect->id());
7266 }
Eric Laurentde070132010-07-13 04:45:46 -07007267 effect = chain->getEffectFromId_l(0);
7268 }
7269
7270 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271}
7272
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007273
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007275sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276 const sp<AudioFlinger::Client>& client,
7277 const sp<IEffectClient>& effectClient,
7278 int32_t priority,
7279 int sessionId,
7280 effect_descriptor_t *desc,
7281 int *enabled,
7282 status_t *status
7283 )
7284{
7285 sp<EffectModule> effect;
7286 sp<EffectHandle> handle;
7287 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007289 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290 bool effectCreated = false;
7291 bool effectRegistered = false;
7292
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007293 lStatus = initCheck();
7294 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007295 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 goto Exit;
7297 }
7298
7299 // Do not allow effects with session ID 0 on direct output or duplicating threads
7300 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007301 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007302 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007303 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304 lStatus = BAD_VALUE;
7305 goto Exit;
7306 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007307 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007308 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007309 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 desc->name, desc->flags, mType);
7311 lStatus = BAD_VALUE;
7312 goto Exit;
7313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314
Steve Block3856b092011-10-20 11:56:00 +01007315 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316
7317 { // scope for mLock
7318 Mutex::Autolock _l(mLock);
7319
7320 // check for existing effect chain with the requested audio session
7321 chain = getEffectChain_l(sessionId);
7322 if (chain == 0) {
7323 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007324 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325 chain = new EffectChain(this, sessionId);
7326 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007327 chain->setStrategy(getStrategyForSession_l(sessionId));
7328 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007330 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 }
7332
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007333 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334
7335 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007336 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007338 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 if (lStatus != NO_ERROR) {
7340 goto Exit;
7341 }
7342 effectRegistered = true;
7343 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007344 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 lStatus = effect->status();
7346 if (lStatus != NO_ERROR) {
7347 goto Exit;
7348 }
Eric Laurentcab11242010-07-15 12:50:15 -07007349 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 if (lStatus != NO_ERROR) {
7351 goto Exit;
7352 }
7353 effectCreated = true;
7354
7355 effect->setDevice(mDevice);
7356 effect->setMode(mAudioFlinger->getMode());
7357 }
7358 // create effect handle and connect it to effect module
7359 handle = new EffectHandle(effect, client, effectClient, priority);
7360 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007361 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 *enabled = (int)effect->isEnabled();
7363 }
7364 }
7365
7366Exit:
7367 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007368 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007370 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371 }
7372 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007373 AudioSystem::unregisterEffect(effect->id());
7374 }
7375 if (chainCreated) {
7376 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 }
7378 handle.clear();
7379 }
7380
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007381 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 *status = lStatus;
7383 }
7384 return handle;
7385}
7386
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007387sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7388{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007389 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007390 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007391}
7392
Eric Laurentde070132010-07-13 04:45:46 -07007393// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7394// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007396{
7397 // check for existing effect chain with the requested audio session
7398 int sessionId = effect->sessionId();
7399 sp<EffectChain> chain = getEffectChain_l(sessionId);
7400 bool chainCreated = false;
7401
7402 if (chain == 0) {
7403 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007404 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007405 chain = new EffectChain(this, sessionId);
7406 addEffectChain_l(chain);
7407 chain->setStrategy(getStrategyForSession_l(sessionId));
7408 chainCreated = true;
7409 }
Steve Block3856b092011-10-20 11:56:00 +01007410 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007411
7412 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007413 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007414 this, effect->desc().name, chain.get());
7415 return BAD_VALUE;
7416 }
7417
7418 status_t status = chain->addEffect_l(effect);
7419 if (status != NO_ERROR) {
7420 if (chainCreated) {
7421 removeEffectChain_l(chain);
7422 }
7423 return status;
7424 }
7425
7426 effect->setDevice(mDevice);
7427 effect->setMode(mAudioFlinger->getMode());
7428 return NO_ERROR;
7429}
7430
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007431void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007432
Steve Block3856b092011-10-20 11:56:00 +01007433 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007435 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7436 detachAuxEffect_l(effect->id());
7437 }
7438
7439 sp<EffectChain> chain = effect->chain().promote();
7440 if (chain != 0) {
7441 // remove effect chain if removing last effect
7442 if (chain->removeEffect_l(effect) == 0) {
7443 removeEffectChain_l(chain);
7444 }
7445 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007446 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007447 }
7448}
7449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007450void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007451 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007452{
7453 effectChains = mEffectChains;
7454 for (size_t i = 0; i < mEffectChains.size(); i++) {
7455 mEffectChains[i]->lock();
7456 }
7457}
7458
7459void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007460 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007461{
7462 for (size_t i = 0; i < effectChains.size(); i++) {
7463 effectChains[i]->unlock();
7464 }
7465}
7466
7467sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7468{
7469 Mutex::Autolock _l(mLock);
7470 return getEffectChain_l(sessionId);
7471}
7472
7473sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7474{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007475 size_t size = mEffectChains.size();
7476 for (size_t i = 0; i < size; i++) {
7477 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007478 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007479 }
7480 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007481 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007482}
7483
Glenn Kastenf78aee72012-01-04 11:00:47 -08007484void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007485{
7486 Mutex::Autolock _l(mLock);
7487 size_t size = mEffectChains.size();
7488 for (size_t i = 0; i < size; i++) {
7489 mEffectChains[i]->setMode_l(mode);
7490 }
7491}
7492
7493void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007494 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007495 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007496
Mathias Agopian65ab4712010-07-14 17:59:35 -07007497 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007498 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007499 // delete the effect module if removing last handle on it
7500 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007501 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007502 removeEffect_l(effect);
7503 AudioSystem::unregisterEffect(effect->id());
7504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 }
7506}
7507
7508status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7509{
7510 int session = chain->sessionId();
7511 int16_t *buffer = mMixBuffer;
7512 bool ownsBuffer = false;
7513
Steve Block3856b092011-10-20 11:56:00 +01007514 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515 if (session > 0) {
7516 // Only one effect chain can be present in direct output thread and it uses
7517 // the mix buffer as input
7518 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007519 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520 buffer = new int16_t[numSamples];
7521 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007522 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 ownsBuffer = true;
7524 }
7525
7526 // Attach all tracks with same session ID to this chain.
7527 for (size_t i = 0; i < mTracks.size(); ++i) {
7528 sp<Track> track = mTracks[i];
7529 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007530 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007532 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533 }
7534 }
7535
7536 // indicate all active tracks in the chain
7537 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7538 sp<Track> track = mActiveTracks[i].promote();
7539 if (track == 0) continue;
7540 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007541 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007542 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543 }
7544 }
7545 }
7546
7547 chain->setInBuffer(buffer, ownsBuffer);
7548 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007549 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007550 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007551 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7552 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007554 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7555 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007556 // Effect chain for other sessions are inserted at beginning of effect
7557 // chains list to be processed before output mix effects. Relative order between other
7558 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559 size_t size = mEffectChains.size();
7560 size_t i = 0;
7561 for (i = 0; i < size; i++) {
7562 if (mEffectChains[i]->sessionId() < session) break;
7563 }
7564 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007565 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566
7567 return NO_ERROR;
7568}
7569
7570size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7571{
7572 int session = chain->sessionId();
7573
Steve Block3856b092011-10-20 11:56:00 +01007574 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575
7576 for (size_t i = 0; i < mEffectChains.size(); i++) {
7577 if (chain == mEffectChains[i]) {
7578 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007579 // detach all active tracks from the chain
7580 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7581 sp<Track> track = mActiveTracks[i].promote();
7582 if (track == 0) continue;
7583 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007584 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007585 chain.get(), session);
7586 chain->decActiveTrackCnt();
7587 }
7588 }
7589
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 // detach all tracks with same session ID from this chain
7591 for (size_t i = 0; i < mTracks.size(); ++i) {
7592 sp<Track> track = mTracks[i];
7593 if (session == track->sessionId()) {
7594 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007595 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 }
7597 }
Eric Laurentde070132010-07-13 04:45:46 -07007598 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 }
7600 }
7601 return mEffectChains.size();
7602}
7603
Eric Laurentde070132010-07-13 04:45:46 -07007604status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7605 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606{
7607 Mutex::Autolock _l(mLock);
7608 return attachAuxEffect_l(track, EffectId);
7609}
7610
Eric Laurentde070132010-07-13 04:45:46 -07007611status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7612 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613{
7614 status_t status = NO_ERROR;
7615
7616 if (EffectId == 0) {
7617 track->setAuxBuffer(0, NULL);
7618 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007619 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7620 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621 if (effect != 0) {
7622 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7623 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7624 } else {
7625 status = INVALID_OPERATION;
7626 }
7627 } else {
7628 status = BAD_VALUE;
7629 }
7630 }
7631 return status;
7632}
7633
7634void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7635{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007636 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 sp<Track> track = mTracks[i];
7638 if (track->auxEffectId() == effectId) {
7639 attachAuxEffect_l(track, 0);
7640 }
7641 }
7642}
7643
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007644status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7645{
7646 // only one chain per input thread
7647 if (mEffectChains.size() != 0) {
7648 return INVALID_OPERATION;
7649 }
Steve Block3856b092011-10-20 11:56:00 +01007650 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007651
7652 chain->setInBuffer(NULL);
7653 chain->setOutBuffer(NULL);
7654
Eric Laurent59255e42011-07-27 19:49:51 -07007655 checkSuspendOnAddEffectChain_l(chain);
7656
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007657 mEffectChains.add(chain);
7658
7659 return NO_ERROR;
7660}
7661
7662size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7663{
Steve Block3856b092011-10-20 11:56:00 +01007664 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007665 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007666 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7667 chain.get(), mEffectChains.size(), this);
7668 if (mEffectChains.size() == 1) {
7669 mEffectChains.removeAt(0);
7670 }
7671 return 0;
7672}
7673
Mathias Agopian65ab4712010-07-14 17:59:35 -07007674// ----------------------------------------------------------------------------
7675// EffectModule implementation
7676// ----------------------------------------------------------------------------
7677
7678#undef LOG_TAG
7679#define LOG_TAG "AudioFlinger::EffectModule"
7680
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007681AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682 const wp<AudioFlinger::EffectChain>& chain,
7683 effect_descriptor_t *desc,
7684 int id,
7685 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007686 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007687 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007688{
Steve Block3856b092011-10-20 11:56:00 +01007689 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007691 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692 return;
7693 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694
7695 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7696
7697 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007698 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699
7700 if (mStatus != NO_ERROR) {
7701 return;
7702 }
7703 lStatus = init();
7704 if (lStatus < 0) {
7705 mStatus = lStatus;
7706 goto Error;
7707 }
7708
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007709 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7710 mPinned = true;
7711 }
Steve Block3856b092011-10-20 11:56:00 +01007712 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713 return;
7714Error:
7715 EffectRelease(mEffectInterface);
7716 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007717 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718}
7719
7720AudioFlinger::EffectModule::~EffectModule()
7721{
Steve Block3856b092011-10-20 11:56:00 +01007722 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007724 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7725 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7726 sp<ThreadBase> thread = mThread.promote();
7727 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007728 audio_stream_t *stream = thread->stream();
7729 if (stream != NULL) {
7730 stream->remove_audio_effect(stream, mEffectInterface);
7731 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007732 }
7733 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734 // release effect engine
7735 EffectRelease(mEffectInterface);
7736 }
7737}
7738
Glenn Kasten435dbe62012-01-30 10:15:48 -08007739status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740{
7741 status_t status;
7742
7743 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 int priority = handle->priority();
7745 size_t size = mHandles.size();
7746 sp<EffectHandle> h;
7747 size_t i;
7748 for (i = 0; i < size; i++) {
7749 h = mHandles[i].promote();
7750 if (h == 0) continue;
7751 if (h->priority() <= priority) break;
7752 }
7753 // if inserted in first place, move effect control from previous owner to this handle
7754 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007755 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007757 enabled = h->enabled();
7758 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 }
Eric Laurent59255e42011-07-27 19:49:51 -07007760 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761 status = NO_ERROR;
7762 } else {
7763 status = ALREADY_EXISTS;
7764 }
Steve Block3856b092011-10-20 11:56:00 +01007765 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 mHandles.insertAt(handle, i);
7767 return status;
7768}
7769
7770size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7771{
7772 Mutex::Autolock _l(mLock);
7773 size_t size = mHandles.size();
7774 size_t i;
7775 for (i = 0; i < size; i++) {
7776 if (mHandles[i] == handle) break;
7777 }
7778 if (i == size) {
7779 return size;
7780 }
Steve Block3856b092011-10-20 11:56:00 +01007781 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007782
7783 bool enabled = false;
7784 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007785 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007786 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007787 enabled = hdl->enabled();
7788 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 mHandles.removeAt(i);
7790 size = mHandles.size();
7791 // if removed from first place, move effect control from this handle to next in line
7792 if (i == 0 && size != 0) {
7793 sp<EffectHandle> h = mHandles[0].promote();
7794 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007795 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 }
7797 }
7798
Eric Laurentec437d82011-07-26 20:54:46 -07007799 // Prevent calls to process() and other functions on effect interface from now on.
7800 // The effect engine will be released by the destructor when the last strong reference on
7801 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007802 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007803 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007804 }
7805
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 return size;
7807}
7808
Eric Laurent59255e42011-07-27 19:49:51 -07007809sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7810{
7811 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007812 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007813}
7814
Glenn Kasten58123c32012-02-03 10:32:24 -08007815void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007817 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 // keep a strong reference on this EffectModule to avoid calling the
7819 // destructor before we exit
7820 sp<EffectModule> keep(this);
7821 {
7822 sp<ThreadBase> thread = mThread.promote();
7823 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007824 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 }
7826 }
7827}
7828
7829void AudioFlinger::EffectModule::updateState() {
7830 Mutex::Autolock _l(mLock);
7831
7832 switch (mState) {
7833 case RESTART:
7834 reset_l();
7835 // FALL THROUGH
7836
7837 case STARTING:
7838 // clear auxiliary effect input buffer for next accumulation
7839 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7840 memset(mConfig.inputCfg.buffer.raw,
7841 0,
7842 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7843 }
7844 start_l();
7845 mState = ACTIVE;
7846 break;
7847 case STOPPING:
7848 stop_l();
7849 mDisableWaitCnt = mMaxDisableWaitCnt;
7850 mState = STOPPED;
7851 break;
7852 case STOPPED:
7853 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7854 // turn off sequence.
7855 if (--mDisableWaitCnt == 0) {
7856 reset_l();
7857 mState = IDLE;
7858 }
7859 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007860 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 break;
7862 }
7863}
7864
7865void AudioFlinger::EffectModule::process()
7866{
7867 Mutex::Autolock _l(mLock);
7868
Eric Laurentec437d82011-07-26 20:54:46 -07007869 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870 mConfig.inputCfg.buffer.raw == NULL ||
7871 mConfig.outputCfg.buffer.raw == NULL) {
7872 return;
7873 }
7874
Eric Laurent8f45bd72010-08-31 13:50:07 -07007875 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7877 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007878 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007879 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007880 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 }
7882
7883 // do the actual processing in the effect engine
7884 int ret = (*mEffectInterface)->process(mEffectInterface,
7885 &mConfig.inputCfg.buffer,
7886 &mConfig.outputCfg.buffer);
7887
7888 // force transition to IDLE state when engine is ready
7889 if (mState == STOPPED && ret == -ENODATA) {
7890 mDisableWaitCnt = 1;
7891 }
7892
7893 // clear auxiliary effect input buffer for next accumulation
7894 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007895 memset(mConfig.inputCfg.buffer.raw, 0,
7896 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 }
7898 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007899 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7900 // If an insert effect is idle and input buffer is different from output buffer,
7901 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007903 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007904 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7905 int16_t *in = mConfig.inputCfg.buffer.s16;
7906 int16_t *out = mConfig.outputCfg.buffer.s16;
7907 for (size_t i = 0; i < frameCnt; i++) {
7908 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 }
7911 }
7912}
7913
7914void AudioFlinger::EffectModule::reset_l()
7915{
7916 if (mEffectInterface == NULL) {
7917 return;
7918 }
7919 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7920}
7921
7922status_t AudioFlinger::EffectModule::configure()
7923{
7924 uint32_t channels;
7925 if (mEffectInterface == NULL) {
7926 return NO_INIT;
7927 }
7928
7929 sp<ThreadBase> thread = mThread.promote();
7930 if (thread == 0) {
7931 return DEAD_OBJECT;
7932 }
7933
7934 // TODO: handle configuration of effects replacing track process
7935 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007936 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007938 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939 }
7940
7941 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007942 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943 } else {
7944 mConfig.inputCfg.channels = channels;
7945 }
7946 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007947 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7948 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 mConfig.inputCfg.samplingRate = thread->sampleRate();
7950 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7951 mConfig.inputCfg.bufferProvider.cookie = NULL;
7952 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7953 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7954 mConfig.outputCfg.bufferProvider.cookie = NULL;
7955 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7956 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7957 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7958 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007959 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007960 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007961 // - in other sessions:
7962 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7963 // other effect: overwrites output buffer: input buffer == output buffer
7964 // Auxiliary effect:
7965 // accumulates in output buffer: input buffer != output buffer
7966 // Therefore: accumulate <=> input buffer != output buffer
7967 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7968 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7969 } else {
7970 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7971 }
7972 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7973 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7974 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7975 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7976
Steve Block3856b092011-10-20 11:56:00 +01007977 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007978 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7979
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007981 uint32_t size = sizeof(int);
7982 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007983 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007984 sizeof(effect_config_t),
7985 &mConfig,
7986 &size,
7987 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 if (status == 0) {
7989 status = cmdStatus;
7990 }
7991
7992 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7993 (1000 * mConfig.outputCfg.buffer.frameCount);
7994
7995 return status;
7996}
7997
7998status_t AudioFlinger::EffectModule::init()
7999{
8000 Mutex::Autolock _l(mLock);
8001 if (mEffectInterface == NULL) {
8002 return NO_INIT;
8003 }
8004 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008005 uint32_t size = sizeof(status_t);
8006 status_t status = (*mEffectInterface)->command(mEffectInterface,
8007 EFFECT_CMD_INIT,
8008 0,
8009 NULL,
8010 &size,
8011 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012 if (status == 0) {
8013 status = cmdStatus;
8014 }
8015 return status;
8016}
8017
Eric Laurentec35a142011-10-05 17:42:25 -07008018status_t AudioFlinger::EffectModule::start()
8019{
8020 Mutex::Autolock _l(mLock);
8021 return start_l();
8022}
8023
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024status_t AudioFlinger::EffectModule::start_l()
8025{
8026 if (mEffectInterface == NULL) {
8027 return NO_INIT;
8028 }
8029 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008030 uint32_t size = sizeof(status_t);
8031 status_t status = (*mEffectInterface)->command(mEffectInterface,
8032 EFFECT_CMD_ENABLE,
8033 0,
8034 NULL,
8035 &size,
8036 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 if (status == 0) {
8038 status = cmdStatus;
8039 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008040 if (status == 0 &&
8041 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8042 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8043 sp<ThreadBase> thread = mThread.promote();
8044 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008045 audio_stream_t *stream = thread->stream();
8046 if (stream != NULL) {
8047 stream->add_audio_effect(stream, mEffectInterface);
8048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008049 }
8050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051 return status;
8052}
8053
Eric Laurentec437d82011-07-26 20:54:46 -07008054status_t AudioFlinger::EffectModule::stop()
8055{
8056 Mutex::Autolock _l(mLock);
8057 return stop_l();
8058}
8059
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060status_t AudioFlinger::EffectModule::stop_l()
8061{
8062 if (mEffectInterface == NULL) {
8063 return NO_INIT;
8064 }
8065 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008066 uint32_t size = sizeof(status_t);
8067 status_t status = (*mEffectInterface)->command(mEffectInterface,
8068 EFFECT_CMD_DISABLE,
8069 0,
8070 NULL,
8071 &size,
8072 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073 if (status == 0) {
8074 status = cmdStatus;
8075 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008076 if (status == 0 &&
8077 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8078 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8079 sp<ThreadBase> thread = mThread.promote();
8080 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008081 audio_stream_t *stream = thread->stream();
8082 if (stream != NULL) {
8083 stream->remove_audio_effect(stream, mEffectInterface);
8084 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008085 }
8086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008087 return status;
8088}
8089
Eric Laurent25f43952010-07-28 05:40:18 -07008090status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8091 uint32_t cmdSize,
8092 void *pCmdData,
8093 uint32_t *replySize,
8094 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095{
8096 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008097// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098
Eric Laurentec437d82011-07-26 20:54:46 -07008099 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 return NO_INIT;
8101 }
Eric Laurent25f43952010-07-28 05:40:18 -07008102 status_t status = (*mEffectInterface)->command(mEffectInterface,
8103 cmdCode,
8104 cmdSize,
8105 pCmdData,
8106 replySize,
8107 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008109 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 for (size_t i = 1; i < mHandles.size(); i++) {
8111 sp<EffectHandle> h = mHandles[i].promote();
8112 if (h != 0) {
8113 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8114 }
8115 }
8116 }
8117 return status;
8118}
8119
8120status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8121{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008122
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008124 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125
8126 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008127 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8128 if (enabled && status != NO_ERROR) {
8129 return status;
8130 }
8131
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 switch (mState) {
8133 // going from disabled to enabled
8134 case IDLE:
8135 mState = STARTING;
8136 break;
8137 case STOPPED:
8138 mState = RESTART;
8139 break;
8140 case STOPPING:
8141 mState = ACTIVE;
8142 break;
8143
8144 // going from enabled to disabled
8145 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008146 mState = STOPPED;
8147 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148 case STARTING:
8149 mState = IDLE;
8150 break;
8151 case ACTIVE:
8152 mState = STOPPING;
8153 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008154 case DESTROYED:
8155 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 }
8157 for (size_t i = 1; i < mHandles.size(); i++) {
8158 sp<EffectHandle> h = mHandles[i].promote();
8159 if (h != 0) {
8160 h->setEnabled(enabled);
8161 }
8162 }
8163 }
8164 return NO_ERROR;
8165}
8166
Glenn Kastenc59c0042012-02-02 14:06:11 -08008167bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008168{
8169 switch (mState) {
8170 case RESTART:
8171 case STARTING:
8172 case ACTIVE:
8173 return true;
8174 case IDLE:
8175 case STOPPING:
8176 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008177 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 default:
8179 return false;
8180 }
8181}
8182
Glenn Kastenc59c0042012-02-02 14:06:11 -08008183bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008184{
8185 switch (mState) {
8186 case RESTART:
8187 case ACTIVE:
8188 case STOPPING:
8189 case STOPPED:
8190 return true;
8191 case IDLE:
8192 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008193 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008194 default:
8195 return false;
8196 }
8197}
8198
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8200{
8201 Mutex::Autolock _l(mLock);
8202 status_t status = NO_ERROR;
8203
8204 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8205 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008206 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008207 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8208 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209 status_t cmdStatus;
8210 uint32_t volume[2];
8211 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008212 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 volume[0] = *left;
8214 volume[1] = *right;
8215 if (controller) {
8216 pVolume = volume;
8217 }
Eric Laurent25f43952010-07-28 05:40:18 -07008218 status = (*mEffectInterface)->command(mEffectInterface,
8219 EFFECT_CMD_SET_VOLUME,
8220 size,
8221 volume,
8222 &size,
8223 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008224 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8225 *left = volume[0];
8226 *right = volume[1];
8227 }
8228 }
8229 return status;
8230}
8231
8232status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8233{
8234 Mutex::Autolock _l(mLock);
8235 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008236 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8237 // audio pre processing modules on RecordThread can receive both output and
8238 // input device indication in the same call
8239 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8240 if (dev) {
8241 status_t cmdStatus;
8242 uint32_t size = sizeof(status_t);
8243
8244 status = (*mEffectInterface)->command(mEffectInterface,
8245 EFFECT_CMD_SET_DEVICE,
8246 sizeof(uint32_t),
8247 &dev,
8248 &size,
8249 &cmdStatus);
8250 if (status == NO_ERROR) {
8251 status = cmdStatus;
8252 }
8253 }
8254 dev = device & AUDIO_DEVICE_IN_ALL;
8255 if (dev) {
8256 status_t cmdStatus;
8257 uint32_t size = sizeof(status_t);
8258
8259 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8260 EFFECT_CMD_SET_INPUT_DEVICE,
8261 sizeof(uint32_t),
8262 &dev,
8263 &size,
8264 &cmdStatus);
8265 if (status2 == NO_ERROR) {
8266 status2 = cmdStatus;
8267 }
8268 if (status == NO_ERROR) {
8269 status = status2;
8270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 }
8272 }
8273 return status;
8274}
8275
Glenn Kastenf78aee72012-01-04 11:00:47 -08008276status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277{
8278 Mutex::Autolock _l(mLock);
8279 status_t status = NO_ERROR;
8280 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008281 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008282 uint32_t size = sizeof(status_t);
8283 status = (*mEffectInterface)->command(mEffectInterface,
8284 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008285 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008286 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008287 &size,
8288 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008289 if (status == NO_ERROR) {
8290 status = cmdStatus;
8291 }
8292 }
8293 return status;
8294}
8295
Eric Laurent59255e42011-07-27 19:49:51 -07008296void AudioFlinger::EffectModule::setSuspended(bool suspended)
8297{
8298 Mutex::Autolock _l(mLock);
8299 mSuspended = suspended;
8300}
Glenn Kastena3a85482012-01-04 11:01:11 -08008301
8302bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008303{
8304 Mutex::Autolock _l(mLock);
8305 return mSuspended;
8306}
8307
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8309{
8310 const size_t SIZE = 256;
8311 char buffer[SIZE];
8312 String8 result;
8313
8314 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8315 result.append(buffer);
8316
8317 bool locked = tryLock(mLock);
8318 // failed to lock - AudioFlinger is probably deadlocked
8319 if (!locked) {
8320 result.append("\t\tCould not lock Fx mutex:\n");
8321 }
8322
8323 result.append("\t\tSession Status State Engine:\n");
8324 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8325 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8326 result.append(buffer);
8327
8328 result.append("\t\tDescriptor:\n");
8329 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8330 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8331 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8332 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8333 result.append(buffer);
8334 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8335 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8336 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8337 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8338 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008339 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340 mDescriptor.apiVersion,
8341 mDescriptor.flags);
8342 result.append(buffer);
8343 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8344 mDescriptor.name);
8345 result.append(buffer);
8346 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8347 mDescriptor.implementor);
8348 result.append(buffer);
8349
8350 result.append("\t\t- Input configuration:\n");
8351 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8352 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8353 (uint32_t)mConfig.inputCfg.buffer.raw,
8354 mConfig.inputCfg.buffer.frameCount,
8355 mConfig.inputCfg.samplingRate,
8356 mConfig.inputCfg.channels,
8357 mConfig.inputCfg.format);
8358 result.append(buffer);
8359
8360 result.append("\t\t- Output configuration:\n");
8361 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8362 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8363 (uint32_t)mConfig.outputCfg.buffer.raw,
8364 mConfig.outputCfg.buffer.frameCount,
8365 mConfig.outputCfg.samplingRate,
8366 mConfig.outputCfg.channels,
8367 mConfig.outputCfg.format);
8368 result.append(buffer);
8369
8370 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8371 result.append(buffer);
8372 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8373 for (size_t i = 0; i < mHandles.size(); ++i) {
8374 sp<EffectHandle> handle = mHandles[i].promote();
8375 if (handle != 0) {
8376 handle->dump(buffer, SIZE);
8377 result.append(buffer);
8378 }
8379 }
8380
8381 result.append("\n");
8382
8383 write(fd, result.string(), result.length());
8384
8385 if (locked) {
8386 mLock.unlock();
8387 }
8388
8389 return NO_ERROR;
8390}
8391
8392// ----------------------------------------------------------------------------
8393// EffectHandle implementation
8394// ----------------------------------------------------------------------------
8395
8396#undef LOG_TAG
8397#define LOG_TAG "AudioFlinger::EffectHandle"
8398
8399AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8400 const sp<AudioFlinger::Client>& client,
8401 const sp<IEffectClient>& effectClient,
8402 int32_t priority)
8403 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008404 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008405 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008406{
Steve Block3856b092011-10-20 11:56:00 +01008407 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008408
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008409 if (client == 0) {
8410 return;
8411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008412 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8413 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8414 if (mCblkMemory != 0) {
8415 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8416
Glenn Kastena0d68332012-01-27 16:47:15 -08008417 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 new(mCblk) effect_param_cblk_t();
8419 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008421 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008422 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008423 return;
8424 }
8425}
8426
8427AudioFlinger::EffectHandle::~EffectHandle()
8428{
Steve Block3856b092011-10-20 11:56:00 +01008429 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008430 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008431 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008432}
8433
8434status_t AudioFlinger::EffectHandle::enable()
8435{
Steve Block3856b092011-10-20 11:56:00 +01008436 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008437 if (!mHasControl) return INVALID_OPERATION;
8438 if (mEffect == 0) return DEAD_OBJECT;
8439
Eric Laurentdb7c0792011-08-10 10:37:50 -07008440 if (mEnabled) {
8441 return NO_ERROR;
8442 }
8443
Eric Laurent59255e42011-07-27 19:49:51 -07008444 mEnabled = true;
8445
8446 sp<ThreadBase> thread = mEffect->thread().promote();
8447 if (thread != 0) {
8448 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8449 }
8450
8451 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8452 if (mEffect->suspended()) {
8453 return NO_ERROR;
8454 }
8455
Eric Laurentdb7c0792011-08-10 10:37:50 -07008456 status_t status = mEffect->setEnabled(true);
8457 if (status != NO_ERROR) {
8458 if (thread != 0) {
8459 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8460 }
8461 mEnabled = false;
8462 }
8463 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464}
8465
8466status_t AudioFlinger::EffectHandle::disable()
8467{
Steve Block3856b092011-10-20 11:56:00 +01008468 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008469 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008470 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008471
Eric Laurentdb7c0792011-08-10 10:37:50 -07008472 if (!mEnabled) {
8473 return NO_ERROR;
8474 }
Eric Laurent59255e42011-07-27 19:49:51 -07008475 mEnabled = false;
8476
8477 if (mEffect->suspended()) {
8478 return NO_ERROR;
8479 }
8480
8481 status_t status = mEffect->setEnabled(false);
8482
8483 sp<ThreadBase> thread = mEffect->thread().promote();
8484 if (thread != 0) {
8485 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8486 }
8487
8488 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008489}
8490
8491void AudioFlinger::EffectHandle::disconnect()
8492{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008493 disconnect(true);
8494}
8495
Glenn Kasten58123c32012-02-03 10:32:24 -08008496void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008497{
Glenn Kasten58123c32012-02-03 10:32:24 -08008498 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008499 if (mEffect == 0) {
8500 return;
8501 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008502 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008503
Eric Laurenta85a74a2011-10-19 11:44:54 -07008504 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008505 sp<ThreadBase> thread = mEffect->thread().promote();
8506 if (thread != 0) {
8507 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8508 }
Eric Laurent59255e42011-07-27 19:49:51 -07008509 }
8510
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 // release sp on module => module destructor can be called now
8512 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008514 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008515 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008516 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8517 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008518 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008519 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8521 mClient.clear();
8522 }
8523}
8524
Eric Laurent25f43952010-07-28 05:40:18 -07008525status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8526 uint32_t cmdSize,
8527 void *pCmdData,
8528 uint32_t *replySize,
8529 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530{
Steve Block3856b092011-10-20 11:56:00 +01008531// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008532// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533
8534 // only get parameter command is permitted for applications not controlling the effect
8535 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8536 return INVALID_OPERATION;
8537 }
8538 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008539 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008540
8541 // handle commands that are not forwarded transparently to effect engine
8542 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8543 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8544 // no risk to block the whole media server process or mixer threads is we are stuck here
8545 Mutex::Autolock _l(mCblk->lock);
8546 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8547 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8548 mCblk->serverIndex = 0;
8549 mCblk->clientIndex = 0;
8550 return BAD_VALUE;
8551 }
8552 status_t status = NO_ERROR;
8553 while (mCblk->serverIndex < mCblk->clientIndex) {
8554 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008555 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556 int *p = (int *)(mBuffer + mCblk->serverIndex);
8557 int size = *p++;
8558 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008559 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 break;
8561 }
8562 effect_param_t *param = (effect_param_t *)p;
8563 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008564 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565 mCblk->serverIndex += size;
8566 continue;
8567 }
Eric Laurent25f43952010-07-28 05:40:18 -07008568 uint32_t psize = sizeof(effect_param_t) +
8569 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8570 param->vsize;
8571 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8572 psize,
8573 p,
8574 &rsize,
8575 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008576 // stop at first error encountered
8577 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008579 *(int *)pReplyData = reply;
8580 break;
8581 } else if (reply != NO_ERROR) {
8582 *(int *)pReplyData = reply;
8583 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584 }
8585 mCblk->serverIndex += size;
8586 }
8587 mCblk->serverIndex = 0;
8588 mCblk->clientIndex = 0;
8589 return status;
8590 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008591 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008592 return enable();
8593 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008594 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595 return disable();
8596 }
8597
8598 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8599}
8600
Eric Laurent59255e42011-07-27 19:49:51 -07008601void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008602{
Steve Block3856b092011-10-20 11:56:00 +01008603 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008604
8605 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008606 mEnabled = enabled;
8607
Mathias Agopian65ab4712010-07-14 17:59:35 -07008608 if (signal && mEffectClient != 0) {
8609 mEffectClient->controlStatusChanged(hasControl);
8610 }
8611}
8612
Eric Laurent25f43952010-07-28 05:40:18 -07008613void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8614 uint32_t cmdSize,
8615 void *pCmdData,
8616 uint32_t replySize,
8617 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618{
8619 if (mEffectClient != 0) {
8620 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8621 }
8622}
8623
8624
8625
8626void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8627{
8628 if (mEffectClient != 0) {
8629 mEffectClient->enableStatusChanged(enabled);
8630 }
8631}
8632
8633status_t AudioFlinger::EffectHandle::onTransact(
8634 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8635{
8636 return BnEffect::onTransact(code, data, reply, flags);
8637}
8638
8639
8640void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8641{
Glenn Kastena0d68332012-01-27 16:47:15 -08008642 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008643
8644 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008645 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008646 mPriority,
8647 mHasControl,
8648 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008649 mCblk ? mCblk->clientIndex : 0,
8650 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651 );
8652
8653 if (locked) {
8654 mCblk->lock.unlock();
8655 }
8656}
8657
8658#undef LOG_TAG
8659#define LOG_TAG "AudioFlinger::EffectChain"
8660
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008661AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008662 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008663 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008664 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8665 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008666{
Dima Zavinfce7a472011-04-19 22:30:36 -07008667 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008668 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008669 return;
8670 }
8671 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8672 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008673}
8674
8675AudioFlinger::EffectChain::~EffectChain()
8676{
8677 if (mOwnInBuffer) {
8678 delete mInBuffer;
8679 }
8680
8681}
8682
Eric Laurent59255e42011-07-27 19:49:51 -07008683// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008684sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008685{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008686 size_t size = mEffects.size();
8687
8688 for (size_t i = 0; i < size; i++) {
8689 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008690 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008691 }
8692 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008693 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694}
8695
Eric Laurent59255e42011-07-27 19:49:51 -07008696// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008697sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008698{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 size_t size = mEffects.size();
8700
8701 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008702 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8703 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008704 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008705 }
8706 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008707 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708}
8709
Eric Laurent59255e42011-07-27 19:49:51 -07008710// getEffectFromType_l() must be called with ThreadBase::mLock held
8711sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8712 const effect_uuid_t *type)
8713{
Eric Laurent59255e42011-07-27 19:49:51 -07008714 size_t size = mEffects.size();
8715
8716 for (size_t i = 0; i < size; i++) {
8717 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008718 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008719 }
8720 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008721 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008722}
8723
Mathias Agopian65ab4712010-07-14 17:59:35 -07008724// Must be called with EffectChain::mLock locked
8725void AudioFlinger::EffectChain::process_l()
8726{
Eric Laurentdac69112010-09-28 14:09:57 -07008727 sp<ThreadBase> thread = mThread.promote();
8728 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008729 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008730 return;
8731 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008732 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8733 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008734 // always process effects unless no more tracks are on the session and the effect tail
8735 // has been rendered
8736 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008737 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008738 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008739
Eric Laurent544fe9b2011-11-11 15:42:52 -08008740 if (!tracksOnSession && mTailBufferCount == 0) {
8741 doProcess = false;
8742 }
8743
8744 if (activeTrackCnt() == 0) {
8745 // if no track is active and the effect tail has not been rendered,
8746 // the input buffer must be cleared here as the mixer process will not do it
8747 if (tracksOnSession || mTailBufferCount > 0) {
8748 size_t numSamples = thread->frameCount() * thread->channelCount();
8749 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8750 if (mTailBufferCount > 0) {
8751 mTailBufferCount--;
8752 }
8753 }
8754 }
Eric Laurentdac69112010-09-28 14:09:57 -07008755 }
8756
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008758 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008759 for (size_t i = 0; i < size; i++) {
8760 mEffects[i]->process();
8761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762 }
8763 for (size_t i = 0; i < size; i++) {
8764 mEffects[i]->updateState();
8765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766}
8767
Eric Laurentcab11242010-07-15 12:50:15 -07008768// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008769status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770{
8771 effect_descriptor_t desc = effect->desc();
8772 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8773
8774 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008775 effect->setChain(this);
8776 sp<ThreadBase> thread = mThread.promote();
8777 if (thread == 0) {
8778 return NO_INIT;
8779 }
8780 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008781
8782 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8783 // Auxiliary effects are inserted at the beginning of mEffects vector as
8784 // they are processed first and accumulated in chain input buffer
8785 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008786
Mathias Agopian65ab4712010-07-14 17:59:35 -07008787 // the input buffer for auxiliary effect contains mono samples in
8788 // 32 bit format. This is to avoid saturation in AudoMixer
8789 // accumulation stage. Saturation is done in EffectModule::process() before
8790 // calling the process in effect engine
8791 size_t numSamples = thread->frameCount();
8792 int32_t *buffer = new int32_t[numSamples];
8793 memset(buffer, 0, numSamples * sizeof(int32_t));
8794 effect->setInBuffer((int16_t *)buffer);
8795 // auxiliary effects output samples to chain input buffer for further processing
8796 // by insert effects
8797 effect->setOutBuffer(mInBuffer);
8798 } else {
8799 // Insert effects are inserted at the end of mEffects vector as they are processed
8800 // after track and auxiliary effects.
8801 // Insert effect order as a function of indicated preference:
8802 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8803 // another effect is present
8804 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8805 // last effect claiming first position
8806 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8807 // first effect claiming last position
8808 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8809 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8810 // already present
8811
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008812 size_t size = mEffects.size();
8813 size_t idx_insert = size;
8814 ssize_t idx_insert_first = -1;
8815 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008816
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008817 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818 effect_descriptor_t d = mEffects[i]->desc();
8819 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8820 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8821 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8822 // check invalid effect chaining combinations
8823 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8824 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008825 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 return INVALID_OPERATION;
8827 }
8828 // remember position of first insert effect and by default
8829 // select this as insert position for new effect
8830 if (idx_insert == size) {
8831 idx_insert = i;
8832 }
8833 // remember position of last insert effect claiming
8834 // first position
8835 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8836 idx_insert_first = i;
8837 }
8838 // remember position of first insert effect claiming
8839 // last position
8840 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8841 idx_insert_last == -1) {
8842 idx_insert_last = i;
8843 }
8844 }
8845 }
8846
8847 // modify idx_insert from first position if needed
8848 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8849 if (idx_insert_last != -1) {
8850 idx_insert = idx_insert_last;
8851 } else {
8852 idx_insert = size;
8853 }
8854 } else {
8855 if (idx_insert_first != -1) {
8856 idx_insert = idx_insert_first + 1;
8857 }
8858 }
8859
8860 // always read samples from chain input buffer
8861 effect->setInBuffer(mInBuffer);
8862
8863 // if last effect in the chain, output samples to chain
8864 // output buffer, otherwise to chain input buffer
8865 if (idx_insert == size) {
8866 if (idx_insert != 0) {
8867 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8868 mEffects[idx_insert-1]->configure();
8869 }
8870 effect->setOutBuffer(mOutBuffer);
8871 } else {
8872 effect->setOutBuffer(mInBuffer);
8873 }
8874 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008875
Steve Block3856b092011-10-20 11:56:00 +01008876 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877 }
8878 effect->configure();
8879 return NO_ERROR;
8880}
8881
Eric Laurentcab11242010-07-15 12:50:15 -07008882// removeEffect_l() must be called with PlaybackThread::mLock held
8883size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008884{
8885 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008886 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8888
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008889 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008891 // calling stop here will remove pre-processing effect from the audio HAL.
8892 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8893 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008894 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8895 mEffects[i]->state() == EffectModule::STOPPING) {
8896 mEffects[i]->stop();
8897 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008898 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8899 delete[] effect->inBuffer();
8900 } else {
8901 if (i == size - 1 && i != 0) {
8902 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8903 mEffects[i - 1]->configure();
8904 }
8905 }
8906 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008907 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008908 break;
8909 }
8910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911
8912 return mEffects.size();
8913}
8914
Eric Laurentcab11242010-07-15 12:50:15 -07008915// setDevice_l() must be called with PlaybackThread::mLock held
8916void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917{
8918 size_t size = mEffects.size();
8919 for (size_t i = 0; i < size; i++) {
8920 mEffects[i]->setDevice(device);
8921 }
8922}
8923
Eric Laurentcab11242010-07-15 12:50:15 -07008924// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008925void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926{
8927 size_t size = mEffects.size();
8928 for (size_t i = 0; i < size; i++) {
8929 mEffects[i]->setMode(mode);
8930 }
8931}
8932
Eric Laurentcab11242010-07-15 12:50:15 -07008933// setVolume_l() must be called with PlaybackThread::mLock held
8934bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935{
8936 uint32_t newLeft = *left;
8937 uint32_t newRight = *right;
8938 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008939 int ctrlIdx = -1;
8940 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008941
Eric Laurentcab11242010-07-15 12:50:15 -07008942 // first update volume controller
8943 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008944 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008945 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8946 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008947 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008948 break;
8949 }
8950 }
8951
8952 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008953 if (hasControl) {
8954 *left = mNewLeftVolume;
8955 *right = mNewRightVolume;
8956 }
8957 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008958 }
8959
8960 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008961 mLeftVolume = newLeft;
8962 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008963
8964 // second get volume update from volume controller
8965 if (ctrlIdx >= 0) {
8966 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008967 mNewLeftVolume = newLeft;
8968 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969 }
8970 // then indicate volume to all other effects in chain.
8971 // Pass altered volume to effects before volume controller
8972 // and requested volume to effects after controller
8973 uint32_t lVol = newLeft;
8974 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008975
Mathias Agopian65ab4712010-07-14 17:59:35 -07008976 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008977 if ((int)i == ctrlIdx) continue;
8978 // this also works for ctrlIdx == -1 when there is no volume controller
8979 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 lVol = *left;
8981 rVol = *right;
8982 }
8983 mEffects[i]->setVolume(&lVol, &rVol, false);
8984 }
8985 *left = newLeft;
8986 *right = newRight;
8987
8988 return hasControl;
8989}
8990
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8992{
8993 const size_t SIZE = 256;
8994 char buffer[SIZE];
8995 String8 result;
8996
8997 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8998 result.append(buffer);
8999
9000 bool locked = tryLock(mLock);
9001 // failed to lock - AudioFlinger is probably deadlocked
9002 if (!locked) {
9003 result.append("\tCould not lock mutex:\n");
9004 }
9005
Eric Laurentcab11242010-07-15 12:50:15 -07009006 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9007 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009008 mEffects.size(),
9009 (uint32_t)mInBuffer,
9010 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009011 mActiveTrackCnt);
9012 result.append(buffer);
9013 write(fd, result.string(), result.size());
9014
9015 for (size_t i = 0; i < mEffects.size(); ++i) {
9016 sp<EffectModule> effect = mEffects[i];
9017 if (effect != 0) {
9018 effect->dump(fd, args);
9019 }
9020 }
9021
9022 if (locked) {
9023 mLock.unlock();
9024 }
9025
9026 return NO_ERROR;
9027}
9028
Eric Laurent59255e42011-07-27 19:49:51 -07009029// must be called with ThreadBase::mLock held
9030void AudioFlinger::EffectChain::setEffectSuspended_l(
9031 const effect_uuid_t *type, bool suspend)
9032{
9033 sp<SuspendedEffectDesc> desc;
9034 // use effect type UUID timelow as key as there is no real risk of identical
9035 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009036 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009037 if (suspend) {
9038 if (index >= 0) {
9039 desc = mSuspendedEffects.valueAt(index);
9040 } else {
9041 desc = new SuspendedEffectDesc();
9042 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9043 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009044 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009045 }
9046 if (desc->mRefCount++ == 0) {
9047 sp<EffectModule> effect = getEffectIfEnabled(type);
9048 if (effect != 0) {
9049 desc->mEffect = effect;
9050 effect->setSuspended(true);
9051 effect->setEnabled(false);
9052 }
9053 }
9054 } else {
9055 if (index < 0) {
9056 return;
9057 }
9058 desc = mSuspendedEffects.valueAt(index);
9059 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009060 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009061 desc->mRefCount = 1;
9062 }
9063 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009064 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009065 if (desc->mEffect != 0) {
9066 sp<EffectModule> effect = desc->mEffect.promote();
9067 if (effect != 0) {
9068 effect->setSuspended(false);
9069 sp<EffectHandle> handle = effect->controlHandle();
9070 if (handle != 0) {
9071 effect->setEnabled(handle->enabled());
9072 }
9073 }
9074 desc->mEffect.clear();
9075 }
9076 mSuspendedEffects.removeItemsAt(index);
9077 }
9078 }
9079}
9080
9081// must be called with ThreadBase::mLock held
9082void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9083{
9084 sp<SuspendedEffectDesc> desc;
9085
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009086 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009087 if (suspend) {
9088 if (index >= 0) {
9089 desc = mSuspendedEffects.valueAt(index);
9090 } else {
9091 desc = new SuspendedEffectDesc();
9092 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009093 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009094 }
9095 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009096 Vector< sp<EffectModule> > effects;
9097 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009098 for (size_t i = 0; i < effects.size(); i++) {
9099 setEffectSuspended_l(&effects[i]->desc().type, true);
9100 }
9101 }
9102 } else {
9103 if (index < 0) {
9104 return;
9105 }
9106 desc = mSuspendedEffects.valueAt(index);
9107 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009108 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009109 desc->mRefCount = 1;
9110 }
9111 if (--desc->mRefCount == 0) {
9112 Vector<const effect_uuid_t *> types;
9113 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9114 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9115 continue;
9116 }
9117 types.add(&mSuspendedEffects.valueAt(i)->mType);
9118 }
9119 for (size_t i = 0; i < types.size(); i++) {
9120 setEffectSuspended_l(types[i], false);
9121 }
Steve Block3856b092011-10-20 11:56:00 +01009122 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009123 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9124 }
9125 }
9126}
9127
Eric Laurent6bffdb82011-09-23 08:40:41 -07009128
9129// The volume effect is used for automated tests only
9130#ifndef OPENSL_ES_H_
9131static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9132 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9133const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9134#endif //OPENSL_ES_H_
9135
Eric Laurentdb7c0792011-08-10 10:37:50 -07009136bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9137{
9138 // auxiliary effects and visualizer are never suspended on output mix
9139 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9140 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009141 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9142 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009143 return false;
9144 }
9145 return true;
9146}
9147
Glenn Kastend0539712012-01-30 12:56:03 -08009148void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009149{
Glenn Kastend0539712012-01-30 12:56:03 -08009150 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009151 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009152 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9153 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009154 }
Eric Laurent59255e42011-07-27 19:49:51 -07009155 }
Eric Laurent59255e42011-07-27 19:49:51 -07009156}
9157
9158sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9159 const effect_uuid_t *type)
9160{
Glenn Kasten090f0192012-01-30 13:00:02 -08009161 sp<EffectModule> effect = getEffectFromType_l(type);
9162 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009163}
9164
9165void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9166 bool enabled)
9167{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009168 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009169 if (enabled) {
9170 if (index < 0) {
9171 // if the effect is not suspend check if all effects are suspended
9172 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9173 if (index < 0) {
9174 return;
9175 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009176 if (!isEffectEligibleForSuspend(effect->desc())) {
9177 return;
9178 }
Eric Laurent59255e42011-07-27 19:49:51 -07009179 setEffectSuspended_l(&effect->desc().type, enabled);
9180 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009181 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009182 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009183 return;
9184 }
Eric Laurent59255e42011-07-27 19:49:51 -07009185 }
Steve Block3856b092011-10-20 11:56:00 +01009186 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009187 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009188 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9189 // if effect is requested to suspended but was not yet enabled, supend it now.
9190 if (desc->mEffect == 0) {
9191 desc->mEffect = effect;
9192 effect->setEnabled(false);
9193 effect->setSuspended(true);
9194 }
9195 } else {
9196 if (index < 0) {
9197 return;
9198 }
Steve Block3856b092011-10-20 11:56:00 +01009199 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009200 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009201 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9202 desc->mEffect.clear();
9203 effect->setSuspended(false);
9204 }
9205}
9206
Mathias Agopian65ab4712010-07-14 17:59:35 -07009207#undef LOG_TAG
9208#define LOG_TAG "AudioFlinger"
9209
9210// ----------------------------------------------------------------------------
9211
9212status_t AudioFlinger::onTransact(
9213 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9214{
9215 return BnAudioFlinger::onTransact(code, data, reply, flags);
9216}
9217
Mathias Agopian65ab4712010-07-14 17:59:35 -07009218}; // namespace android