blob: eb37028c2c8574abdaa29427cb6397d60d4c5280 [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 Kasten58912562012-04-03 10:45:00 -07001495 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1496 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1497 mFastTrackNewMask(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498{
Glenn Kasten58912562012-04-03 10:45:00 -07001499#if !LOG_NDEBUG
1500 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
1501#endif
Glenn Kasten480b4682012-02-28 12:30:08 -08001502 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001503
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 readOutputParameters();
1505
Glenn Kasten263709e2012-01-06 08:40:01 -08001506 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001507 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1508 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1509 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001510 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1511 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001513 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1514 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515}
1516
1517AudioFlinger::PlaybackThread::~PlaybackThread()
1518{
1519 delete [] mMixBuffer;
1520}
1521
1522status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1523{
1524 dumpInternals(fd, args);
1525 dumpTracks(fd, args);
1526 dumpEffectChains(fd, args);
1527 return NO_ERROR;
1528}
1529
1530status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1531{
1532 const size_t SIZE = 256;
1533 char buffer[SIZE];
1534 String8 result;
1535
Glenn Kasten58912562012-04-03 10:45:00 -07001536 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1537 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1538 const stream_type_t *st = &mStreamTypes[i];
1539 if (i > 0) {
1540 result.appendFormat(", ");
1541 }
1542 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1543 if (st->mute) {
1544 result.append("M");
1545 }
1546 }
1547 result.append("\n");
1548 write(fd, result.string(), result.length());
1549 result.clear();
1550
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1552 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001553 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1554 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 for (size_t i = 0; i < mTracks.size(); ++i) {
1556 sp<Track> track = mTracks[i];
1557 if (track != 0) {
1558 track->dump(buffer, SIZE);
1559 result.append(buffer);
1560 }
1561 }
1562
1563 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1564 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001565 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1566 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001568 sp<Track> track = mActiveTracks[i].promote();
1569 if (track != 0) {
1570 track->dump(buffer, SIZE);
1571 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 }
1573 }
1574 write(fd, result.string(), result.size());
1575 return NO_ERROR;
1576}
1577
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1579{
1580 const size_t SIZE = 256;
1581 char buffer[SIZE];
1582 String8 result;
1583
1584 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1585 result.append(buffer);
1586 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1587 result.append(buffer);
1588 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1589 result.append(buffer);
1590 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1591 result.append(buffer);
1592 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1593 result.append(buffer);
1594 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1595 result.append(buffer);
1596 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1597 result.append(buffer);
1598 write(fd, result.string(), result.size());
1599
1600 dumpBase(fd, args);
1601
1602 return NO_ERROR;
1603}
1604
1605// Thread virtuals
1606status_t AudioFlinger::PlaybackThread::readyToRun()
1607{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001608 status_t status = initCheck();
1609 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001610 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001611 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001612 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001614 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615}
1616
1617void AudioFlinger::PlaybackThread::onFirstRef()
1618{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001619 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620}
1621
1622// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001623sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001625 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001627 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001628 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 int frameCount,
1630 const sp<IMemory>& sharedBuffer,
1631 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001632 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001633 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634 status_t *status)
1635{
1636 sp<Track> track;
1637 status_t lStatus;
1638
Glenn Kasten73d22752012-03-19 13:38:30 -07001639 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1640
1641 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001642 if (flags & IAudioFlinger::TRACK_FAST) {
1643 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001644 // not timed
1645 (!isTimed) &&
1646 // either of these use cases:
1647 (
1648 // use case 1: shared buffer with any frame count
1649 (
1650 (sharedBuffer != 0)
1651 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001652 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001653 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001654 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001655 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001656 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001657 )
1658 ) &&
1659 // PCM data
1660 audio_is_linear_pcm(format) &&
1661 // mono or stereo
1662 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1663 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001664#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001665 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001666 (sampleRate == mSampleRate) &&
1667#endif
1668 // normal mixer has an associated fast mixer
1669 hasFastMixer() &&
1670 // there are sufficient fast track slots available
1671 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001672 // FIXME test that MixerThread for this fast track has a capable output HAL
1673 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001674 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001675 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1676 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001677 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001678 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001679 ALOGI("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1680 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 } else {
1682 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001683 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1684 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1685 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1686 audio_is_linear_pcm(format),
1687 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001688 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001689 // For compatibility with AudioTrack calculation, buffer depth is forced
1690 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1691 // This is probably too conservative, but legacy application code may depend on it.
1692 // If you change this calculation, also review the start threshold which is related.
1693 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1694 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1695 if (minBufCount < 2) {
1696 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001697 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001698 int minFrameCount = mNormalFrameCount * minBufCount;
1699 if (frameCount < minFrameCount) {
1700 frameCount = minFrameCount;
1701 }
1702 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001703 }
1704
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001706 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1707 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001708 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001709 "for output %p with format %d",
1710 sampleRate, format, channelMask, mOutput, mFormat);
1711 lStatus = BAD_VALUE;
1712 goto Exit;
1713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 }
1715 } else {
1716 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1717 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001718 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 lStatus = BAD_VALUE;
1720 goto Exit;
1721 }
1722 }
1723
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001724 lStatus = initCheck();
1725 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001726 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 goto Exit;
1728 }
1729
1730 { // scope for mLock
1731 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001732
1733 // all tracks in same audio session must share the same routing strategy otherwise
1734 // conflicts will happen when tracks are moved from one output to another by audio policy
1735 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001736 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001737 for (size_t i = 0; i < mTracks.size(); ++i) {
1738 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001739 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001740 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001741 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001742 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001743 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001744 lStatus = BAD_VALUE;
1745 goto Exit;
1746 }
1747 }
1748 }
1749
John Grossman4ff14ba2012-02-08 16:37:41 -08001750 if (!isTimed) {
1751 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001752 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001753 } else {
1754 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1755 channelMask, frameCount, sharedBuffer, sessionId);
1756 }
1757 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 lStatus = NO_MEMORY;
1759 goto Exit;
1760 }
1761 mTracks.add(track);
1762
1763 sp<EffectChain> chain = getEffectChain_l(sessionId);
1764 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001765 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001767 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001768 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 }
1770 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001771
1772#ifdef HAVE_REQUEST_PRIORITY
1773 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1774 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1775 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1776 // so ask activity manager to do this on our behalf
1777 int err = requestPriority(callingPid, tid, 1);
1778 if (err != 0) {
1779 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1780 1, callingPid, tid, err);
1781 }
1782 }
1783#endif
1784
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 lStatus = NO_ERROR;
1786
1787Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001788 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 *status = lStatus;
1790 }
1791 return track;
1792}
1793
1794uint32_t AudioFlinger::PlaybackThread::latency() const
1795{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001796 Mutex::Autolock _l(mLock);
1797 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001798 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001799 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 return 0;
1801 }
1802}
1803
Glenn Kasten6637baa2012-01-09 09:40:36 -08001804void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001806 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808}
1809
Glenn Kasten6637baa2012-01-09 09:40:36 -08001810void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001812 Mutex::Autolock _l(mLock);
1813 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814}
1815
Glenn Kasten6637baa2012-01-09 09:40:36 -08001816void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001818 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820}
1821
Glenn Kasten6637baa2012-01-09 09:40:36 -08001822void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001824 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826}
1827
Glenn Kastenfff6d712012-01-12 16:38:12 -08001828float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001830 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 return mStreamTypes[stream].volume;
1832}
1833
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834// addTrack_l() must be called with ThreadBase::mLock held
1835status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1836{
1837 status_t status = ALREADY_EXISTS;
1838
1839 // set retry count for buffer fill
1840 track->mRetryCount = kMaxTrackStartupRetries;
1841 if (mActiveTracks.indexOf(track) < 0) {
1842 // the track is newly added, make sure it fills up all its
1843 // buffers before playing. This is to ensure the client will
1844 // effectively get the latency it requested.
1845 track->mFillingUpStatus = Track::FS_FILLING;
1846 track->mResetDone = false;
1847 mActiveTracks.add(track);
1848 if (track->mainBuffer() != mMixBuffer) {
1849 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1850 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001851 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001852 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 }
1854 }
1855
1856 status = NO_ERROR;
1857 }
1858
Steve Block3856b092011-10-20 11:56:00 +01001859 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 mWaitWorkCV.broadcast();
1861
1862 return status;
1863}
1864
1865// destroyTrack_l() must be called with ThreadBase::mLock held
1866void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1867{
1868 track->mState = TrackBase::TERMINATED;
1869 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001870 removeTrack_l(track);
1871 }
1872}
1873
1874void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1875{
1876 mTracks.remove(track);
1877 deleteTrackName_l(track->name());
1878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1879 if (chain != 0) {
1880 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 }
1882}
1883
1884String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1885{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001886 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001887 char *s;
1888
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001889 Mutex::Autolock _l(mLock);
1890 if (initCheck() != NO_ERROR) {
1891 return out_s8;
1892 }
1893
Dima Zavin799a70e2011-04-18 16:57:27 -07001894 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001895 out_s8 = String8(s);
1896 free(s);
1897 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898}
1899
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001900// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1902 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001903 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904
Steve Block3856b092011-10-20 11:56:00 +01001905 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906
1907 switch (event) {
1908 case AudioSystem::OUTPUT_OPENED:
1909 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001910 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911 desc.samplingRate = mSampleRate;
1912 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001913 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 desc.latency = latency();
1915 param2 = &desc;
1916 break;
1917
1918 case AudioSystem::STREAM_CONFIG_CHANGED:
1919 param2 = &param;
1920 case AudioSystem::OUTPUT_CLOSED:
1921 default:
1922 break;
1923 }
1924 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1925}
1926
1927void AudioFlinger::PlaybackThread::readOutputParameters()
1928{
Dima Zavin799a70e2011-04-18 16:57:27 -07001929 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001930 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1931 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001932 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001933 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001934 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001935 if (mFrameCount & 15) {
1936 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1937 mFrameCount);
1938 }
1939
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001940 // Calculate size of normal mix buffer relative to the HAL output buffer size
1941 uint32_t multiple = 1;
1942 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001943 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001944 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1945 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1946 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1947 // FIXME this rounding up should not be done if no HAL SRC
1948 if ((multiple > 2) && (multiple & 1)) {
1949 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001950 }
Glenn Kasten58912562012-04-03 10:45:00 -07001951 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001952 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001953 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954
1955 // FIXME - Current mixer implementation only supports stereo output: Always
1956 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001957 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001958 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1959 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
Eric Laurentde070132010-07-13 04:45:46 -07001961 // force reconfiguration of effect chains and engines to take new buffer size and audio
1962 // parameters into account
1963 // Note that mLock is not held when readOutputParameters() is called from the constructor
1964 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1965 // matter.
1966 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1967 Vector< sp<EffectChain> > effectChains = mEffectChains;
1968 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001969 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971}
1972
1973status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1974{
Glenn Kastena0d68332012-01-27 16:47:15 -08001975 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 return BAD_VALUE;
1977 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001978 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001979 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 return INVALID_OPERATION;
1981 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001982 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985}
1986
Eric Laurent39e94f82010-07-28 01:32:47 -07001987uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988{
1989 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001990 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001992 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 }
1994
1995 for (size_t i = 0; i < mTracks.size(); ++i) {
1996 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001997 if (sessionId == track->sessionId() &&
1998 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001999 result |= TRACK_SESSION;
2000 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 }
2002 }
2003
Eric Laurent39e94f82010-07-28 01:32:47 -07002004 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005}
2006
Eric Laurentde070132010-07-13 04:45:46 -07002007uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2008{
Dima Zavinfce7a472011-04-19 22:30:36 -07002009 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002010 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002011 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2012 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002013 }
2014 for (size_t i = 0; i < mTracks.size(); i++) {
2015 sp<Track> track = mTracks[i];
2016 if (sessionId == track->sessionId() &&
2017 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002018 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002019 }
2020 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002021 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002022}
2023
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024
Glenn Kastenaed850d2012-01-26 09:46:34 -08002025AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002026{
2027 Mutex::Autolock _l(mLock);
2028 return mOutput;
2029}
2030
2031AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2032{
2033 Mutex::Autolock _l(mLock);
2034 AudioStreamOut *output = mOutput;
2035 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002036 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2037 // must push a NULL and wait for ack
2038 mOutputSink.clear();
2039 mPipeSink.clear();
2040 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002041 return output;
2042}
2043
2044// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002045audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002046{
2047 if (mOutput == NULL) {
2048 return NULL;
2049 }
2050 return &mOutput->stream->common;
2051}
2052
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002053uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002054{
2055 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2056 // decoding and transfer time. So sleeping for half of the latency would likely cause
2057 // underruns
2058 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002059 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002060 } else {
2061 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2062 }
2063}
2064
Eric Laurenta011e352012-03-29 15:51:43 -07002065status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2066{
2067 if (!isValidSyncEvent(event)) {
2068 return BAD_VALUE;
2069 }
2070
2071 Mutex::Autolock _l(mLock);
2072
2073 for (size_t i = 0; i < mTracks.size(); ++i) {
2074 sp<Track> track = mTracks[i];
2075 if (event->triggerSession() == track->sessionId()) {
2076 track->setSyncEvent(event);
2077 return NO_ERROR;
2078 }
2079 }
2080
2081 return NAME_NOT_FOUND;
2082}
2083
2084bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2085{
2086 switch (event->type()) {
2087 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2088 return true;
2089 default:
2090 break;
2091 }
2092 return false;
2093}
2094
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095// ----------------------------------------------------------------------------
2096
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002097AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002098 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002099 : PlaybackThread(audioFlinger, output, id, device, type),
2100 // mAudioMixer below
2101#ifdef SOAKER
2102 mSoaker(NULL),
2103#endif
2104 // mFastMixer below
2105 mFastMixerFutex(0)
2106 // mOutputSink below
2107 // mPipeSink below
2108 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109{
Glenn Kasten58912562012-04-03 10:45:00 -07002110 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2111 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2112 "mFrameCount=%d, mNormalFrameCount=%d",
2113 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2114 mNormalFrameCount);
2115 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2116
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 // FIXME - Current mixer implementation only supports stereo output
2118 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002119 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 }
Glenn Kasten58912562012-04-03 10:45:00 -07002121
2122 // create an NBAIO sink for the HAL output stream, and negotiate
2123 mOutputSink = new AudioStreamOutSink(output->stream);
2124 size_t numCounterOffers = 0;
2125 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2126 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2127 ALOG_ASSERT(index == 0);
2128
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002129 // initialize fast mixer depending on configuration
2130 bool initFastMixer;
2131 switch (kUseFastMixer) {
2132 case FastMixer_Never:
2133 initFastMixer = false;
2134 break;
2135 case FastMixer_Always:
2136 initFastMixer = true;
2137 break;
2138 case FastMixer_Static:
2139 case FastMixer_Dynamic:
2140 initFastMixer = mFrameCount < mNormalFrameCount;
2141 break;
2142 }
2143 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002144
2145 // create a MonoPipe to connect our submix to FastMixer
2146 NBAIO_Format format = mOutputSink->format();
2147 // frame count will be rounded up to a power of 2, so this formula should work well
2148 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2149 true /*writeCanBlock*/);
2150 const NBAIO_Format offers[1] = {format};
2151 size_t numCounterOffers = 0;
2152 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2153 ALOG_ASSERT(index == 0);
2154 mPipeSink = monoPipe;
2155
2156#ifdef SOAKER
2157 // create a soaker as workaround for governor issues
2158 mSoaker = new Soaker();
2159 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2160 mSoaker->run("Soaker", PRIORITY_LOWEST);
2161#endif
2162
2163 // create fast mixer and configure it initially with just one fast track for our submix
2164 mFastMixer = new FastMixer();
2165 FastMixerStateQueue *sq = mFastMixer->sq();
2166 FastMixerState *state = sq->begin();
2167 FastTrack *fastTrack = &state->mFastTracks[0];
2168 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2169 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2170 fastTrack->mVolumeProvider = NULL;
2171 fastTrack->mGeneration++;
2172 state->mFastTracksGen++;
2173 state->mTrackMask = 1;
2174 // fast mixer will use the HAL output sink
2175 state->mOutputSink = mOutputSink.get();
2176 state->mOutputSinkGen++;
2177 state->mFrameCount = mFrameCount;
2178 state->mCommand = FastMixerState::COLD_IDLE;
2179 // already done in constructor initialization list
2180 //mFastMixerFutex = 0;
2181 state->mColdFutexAddr = &mFastMixerFutex;
2182 state->mColdGen++;
2183 state->mDumpState = &mFastMixerDumpState;
2184 sq->end();
2185 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2186
2187 // start the fast mixer
2188 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2189#ifdef HAVE_REQUEST_PRIORITY
2190 pid_t tid = mFastMixer->getTid();
2191 int err = requestPriority(getpid_cached, tid, 2);
2192 if (err != 0) {
2193 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2194 2, getpid_cached, tid, err);
2195 }
2196#endif
2197
2198 } else {
2199 mFastMixer = NULL;
2200 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002201
2202 switch (kUseFastMixer) {
2203 case FastMixer_Never:
2204 case FastMixer_Dynamic:
2205 mNormalSink = mOutputSink;
2206 break;
2207 case FastMixer_Always:
2208 mNormalSink = mPipeSink;
2209 break;
2210 case FastMixer_Static:
2211 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2212 break;
2213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214}
2215
2216AudioFlinger::MixerThread::~MixerThread()
2217{
Glenn Kasten58912562012-04-03 10:45:00 -07002218 if (mFastMixer != NULL) {
2219 FastMixerStateQueue *sq = mFastMixer->sq();
2220 FastMixerState *state = sq->begin();
2221 if (state->mCommand == FastMixerState::COLD_IDLE) {
2222 int32_t old = android_atomic_inc(&mFastMixerFutex);
2223 if (old == -1) {
2224 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2225 }
2226 }
2227 state->mCommand = FastMixerState::EXIT;
2228 sq->end();
2229 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2230 mFastMixer->join();
2231 // Though the fast mixer thread has exited, it's state queue is still valid.
2232 // We'll use that extract the final state which contains one remaining fast track
2233 // corresponding to our sub-mix.
2234 state = sq->begin();
2235 ALOG_ASSERT(state->mTrackMask == 1);
2236 FastTrack *fastTrack = &state->mFastTracks[0];
2237 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2238 delete fastTrack->mBufferProvider;
2239 sq->end(false /*didModify*/);
2240 delete mFastMixer;
2241#ifdef SOAKER
2242 if (mSoaker != NULL) {
2243 mSoaker->requestExitAndWait();
2244 }
2245 delete mSoaker;
2246#endif
2247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 delete mAudioMixer;
2249}
2250
Glenn Kasten83efdd02012-02-24 07:21:32 -08002251class CpuStats {
2252public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002253 CpuStats();
2254 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002255#ifdef DEBUG_CPU_USAGE
2256private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002257 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2258 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2259
2260 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2261
2262 int mCpuNum; // thread's current CPU number
2263 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002264#endif
2265};
2266
Glenn Kasten190a46f2012-03-06 11:27:10 -08002267CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002268#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002269 : mCpuNum(-1), mCpukHz(-1)
2270#endif
2271{
2272}
2273
2274void CpuStats::sample(const String8 &title) {
2275#ifdef DEBUG_CPU_USAGE
2276 // get current thread's delta CPU time in wall clock ns
2277 double wcNs;
2278 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2279
2280 // record sample for wall clock statistics
2281 if (valid) {
2282 mWcStats.sample(wcNs);
2283 }
2284
2285 // get the current CPU number
2286 int cpuNum = sched_getcpu();
2287
2288 // get the current CPU frequency in kHz
2289 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2290
2291 // check if either CPU number or frequency changed
2292 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2293 mCpuNum = cpuNum;
2294 mCpukHz = cpukHz;
2295 // ignore sample for purposes of cycles
2296 valid = false;
2297 }
2298
2299 // if no change in CPU number or frequency, then record sample for cycle statistics
2300 if (valid && mCpukHz > 0) {
2301 double cycles = wcNs * cpukHz * 0.000001;
2302 mHzStats.sample(cycles);
2303 }
2304
2305 unsigned n = mWcStats.n();
2306 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002307 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002308 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002309 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2310 double perLoop = elapsed / (double) n;
2311 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002312 double perLoop1k = perLoop * 0.001;
2313 double mean = mWcStats.mean();
2314 double stddev = mWcStats.stddev();
2315 double minimum = mWcStats.minimum();
2316 double maximum = mWcStats.maximum();
2317 double meanCycles = mHzStats.mean();
2318 double stddevCycles = mHzStats.stddev();
2319 double minCycles = mHzStats.minimum();
2320 double maxCycles = mHzStats.maximum();
2321 mCpuUsage.resetElapsed();
2322 mWcStats.reset();
2323 mHzStats.reset();
2324 ALOGD("CPU usage for %s over past %.1f secs\n"
2325 " (%u mixer loops at %.1f mean ms per loop):\n"
2326 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2327 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2328 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2329 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002330 elapsed * .000000001, n, perLoop * .000001,
2331 mean * .001,
2332 stddev * .001,
2333 minimum * .001,
2334 maximum * .001,
2335 mean / perLoop100,
2336 stddev / perLoop100,
2337 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002338 maximum / perLoop100,
2339 meanCycles / perLoop1k,
2340 stddevCycles / perLoop1k,
2341 minCycles / perLoop1k,
2342 maxCycles / perLoop1k);
2343
Glenn Kasten83efdd02012-02-24 07:21:32 -08002344 }
2345 }
2346#endif
2347};
2348
Glenn Kasten37d825e2012-02-24 07:21:48 -08002349void AudioFlinger::PlaybackThread::checkSilentMode_l()
2350{
2351 if (!mMasterMute) {
2352 char value[PROPERTY_VALUE_MAX];
2353 if (property_get("ro.audio.silent", value, "0") > 0) {
2354 char *endptr;
2355 unsigned long ul = strtoul(value, &endptr, 0);
2356 if (*endptr == '\0' && ul != 0) {
2357 ALOGD("Silence is golden");
2358 // The setprop command will not allow a property to be changed after
2359 // the first time it is set, so we don't have to worry about un-muting.
2360 setMasterMute_l(true);
2361 }
2362 }
2363 }
2364}
2365
Glenn Kasten000f0e32012-03-01 17:10:56 -08002366bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367{
2368 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002369
Glenn Kasten000f0e32012-03-01 17:10:56 -08002370 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002371
2372 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002374if (mType == MIXER) {
2375 longStandbyExit = false;
2376}
Glenn Kasten688a6402012-02-29 07:57:06 -08002377
Glenn Kasten000f0e32012-03-01 17:10:56 -08002378 // DUPLICATING
2379 // FIXME could this be made local to while loop?
2380 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002381
Glenn Kasten66fcab92012-02-24 14:59:21 -08002382 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002383 sleepTime = idleSleepTime;
2384
2385if (mType == MIXER) {
2386 sleepTimeShift = 0;
2387}
2388
Glenn Kasten83efdd02012-02-24 07:21:32 -08002389 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391
Eric Laurentfeb0db62011-07-22 09:04:31 -07002392 acquireWakeLock();
2393
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 while (!exitPending())
2395 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002396 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002397
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002398 Vector< sp<EffectChain> > effectChains;
2399
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 processConfigEvents();
2401
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402 { // scope for mLock
2403
2404 Mutex::Autolock _l(mLock);
2405
2406 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002407 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 }
2409
Glenn Kastenfa26a852012-03-06 11:28:04 -08002410 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002411
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002413 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002414 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002416
2417 threadLoop_standby();
2418
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 mStandby = true;
2420 mBytesWritten = 0;
2421 }
2422
Glenn Kasten3e074702012-02-28 18:40:35 -08002423 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // we're about to wait, flush the binder command buffer
2425 IPCThreadState::self()->flushCommands();
2426
Glenn Kastenfa26a852012-03-06 11:28:04 -08002427 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002428
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 if (exitPending()) break;
2430
Eric Laurentfeb0db62011-07-22 09:04:31 -07002431 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002433 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002435 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002436 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437
Eric Laurentda747442012-04-25 18:53:13 -07002438 mMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002439
Glenn Kasten37d825e2012-02-24 07:21:48 -08002440 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441
Glenn Kasten000f0e32012-03-01 17:10:56 -08002442 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002444 if (mType == MIXER) {
2445 sleepTimeShift = 0;
2446 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002447
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448 continue;
2449 }
2450 }
2451
Eric Laurentda747442012-04-25 18:53:13 -07002452 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453
2454 // prevent any changes in effect chain list and in each effect chain
2455 // during mixing and effect process as the audio buffers could be deleted
2456 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002457 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459
Glenn Kastenfec279f2012-03-08 07:47:15 -08002460 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002461 threadLoop_mix();
2462 } else {
2463 threadLoop_sleepTime();
2464 }
2465
2466 if (mSuspended > 0) {
2467 sleepTime = suspendSleepTimeUs();
2468 }
2469
2470 // only process effects if we're going to write
2471 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002472 for (size_t i = 0; i < effectChains.size(); i ++) {
2473 effectChains[i]->process_l();
2474 }
2475 }
2476
2477 // enable changes in effect chain
2478 unlockEffectChains(effectChains);
2479
2480 // sleepTime == 0 means we must write to audio hardware
2481 if (sleepTime == 0) {
2482
2483 threadLoop_write();
2484
2485if (mType == MIXER) {
2486 // write blocked detection
2487 nsecs_t now = systemTime();
2488 nsecs_t delta = now - mLastWriteTime;
2489 if (!mStandby && delta > maxPeriod) {
2490 mNumDelayedWrites++;
2491 if ((now - lastWarning) > kWarningThrottleNs) {
2492 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2493 ns2ms(delta), mNumDelayedWrites, this);
2494 lastWarning = now;
2495 }
2496 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2497 // a different threshold. Or completely removed for what it is worth anyway...
2498 if (mStandby) {
2499 longStandbyExit = true;
2500 }
2501 }
2502}
2503
2504 mStandby = false;
2505 } else {
2506 usleep(sleepTime);
2507 }
2508
Glenn Kasten58912562012-04-03 10:45:00 -07002509 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002510 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002511 // same lock. This will also mutate and push a new fast mixer state.
2512 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002513 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002514
Glenn Kastenfa26a852012-03-06 11:28:04 -08002515 // FIXME I don't understand the need for this here;
2516 // it was in the original code but maybe the
2517 // assignment in saveOutputTracks() makes this unnecessary?
2518 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002519
2520 // Effect chains will be actually deleted here if they were removed from
2521 // mEffectChains list during mixing or effects processing
2522 effectChains.clear();
2523
2524 // FIXME Note that the above .clear() is no longer necessary since effectChains
2525 // is now local to this block, but will keep it for now (at least until merge done).
2526 }
2527
2528if (mType == MIXER || mType == DIRECT) {
2529 // put output stream into standby mode
2530 if (!mStandby) {
2531 mOutput->stream->common.standby(&mOutput->stream->common);
2532 }
2533}
2534if (mType == DUPLICATING) {
2535 // for DuplicatingThread, standby mode is handled by the outputTracks
2536}
2537
2538 releaseWakeLock();
2539
2540 ALOGV("Thread %p type %d exiting", this, mType);
2541 return false;
2542}
2543
Glenn Kasten58912562012-04-03 10:45:00 -07002544// FIXME This method needs a better name.
2545// It pushes a new fast mixer state and returns (via tracksToRemove) a set of tracks to remove.
2546void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2547{
2548 // were any of the removed tracks also fast tracks?
2549 unsigned removedMask = 0;
2550 for (size_t i = 0; i < tracksToRemove.size(); ++i) {
2551 if (tracksToRemove[i]->isFastTrack()) {
2552 int j = tracksToRemove[i]->mFastIndex;
2553 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2554 removedMask |= 1 << j;
2555 }
2556 }
2557 Track* newArray[FastMixerState::kMaxFastTracks];
2558 unsigned newMask;
2559 {
2560 AutoMutex _l(mLock);
2561 mFastTrackAvailMask |= removedMask;
2562 newMask = mFastTrackNewMask;
2563 if (newMask) {
2564 mFastTrackNewMask = 0;
2565 memcpy(newArray, mFastTrackNewArray, sizeof(mFastTrackNewArray));
2566#if !LOG_NDEBUG
2567 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
2568#endif
2569 }
2570 }
2571 unsigned changedMask = newMask | removedMask;
2572 // are there any newly added or removed fast tracks?
2573 if (changedMask) {
2574
2575 // This assert would be incorrect because it's theoretically possible (though unlikely)
2576 // for a track to be created and then removed within the same normal mix cycle:
2577 // ALOG_ASSERT(!(newMask & removedMask));
2578 // The converse, of removing a track and then creating a new track at the identical slot
2579 // within the same normal mix cycle, is impossible because the slot isn't marked available.
2580
2581 // prepare a new state to push
2582 FastMixerStateQueue *sq = mFastMixer->sq();
2583 FastMixerState *state = sq->begin();
2584 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2585 while (changedMask) {
2586 int j = __builtin_ctz(changedMask);
2587 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2588 changedMask &= ~(1 << j);
2589 FastTrack *fastTrack = &state->mFastTracks[j];
2590 // must first do new tracks, then removed tracks, in case same track in both
2591 if (newMask & (1 << j)) {
2592 ALOG_ASSERT(!(state->mTrackMask & (1 << j)));
2593 ALOG_ASSERT(fastTrack->mBufferProvider == NULL &&
2594 fastTrack->mVolumeProvider == NULL);
2595 Track *track = newArray[j];
2596 AudioBufferProvider *abp = track;
2597 VolumeProvider *vp = track;
2598 fastTrack->mBufferProvider = abp;
2599 fastTrack->mVolumeProvider = vp;
2600 fastTrack->mSampleRate = track->mSampleRate;
2601 fastTrack->mChannelMask = track->mChannelMask;
2602 state->mTrackMask |= 1 << j;
2603 }
2604 if (removedMask & (1 << j)) {
2605 ALOG_ASSERT(state->mTrackMask & (1 << j));
2606 ALOG_ASSERT(fastTrack->mBufferProvider != NULL &&
2607 fastTrack->mVolumeProvider != NULL);
2608 fastTrack->mBufferProvider = NULL;
2609 fastTrack->mVolumeProvider = NULL;
2610 fastTrack->mSampleRate = mSampleRate;
2611 fastTrack->mChannelMask = AUDIO_CHANNEL_OUT_STEREO;
2612 state->mTrackMask &= ~(1 << j);
2613 }
2614 fastTrack->mGeneration++;
2615 }
2616 state->mFastTracksGen++;
2617 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002618 if (kUseFastMixer == FastMixer_Dynamic &&
2619 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
Glenn Kasten58912562012-04-03 10:45:00 -07002620 state->mCommand = FastMixerState::COLD_IDLE;
2621 state->mColdFutexAddr = &mFastMixerFutex;
2622 state->mColdGen++;
2623 mFastMixerFutex = 0;
2624 mNormalSink = mOutputSink;
2625 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2626 }
2627 sq->end();
2628 // If any fast tracks were removed, we must wait for acknowledgement
2629 // because we're about to decrement the last sp<> on those tracks.
2630 // Similarly if we put it into cold idle, need to wait for acknowledgement
2631 // so that it stops doing I/O.
2632 if (removedMask) {
2633 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2634 }
2635 sq->push(block);
2636 }
2637 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2638}
2639
2640void AudioFlinger::MixerThread::threadLoop_write()
2641{
2642 // FIXME we should only do one push per cycle; confirm this is true
2643 // Start the fast mixer if it's not already running
2644 if (mFastMixer != NULL) {
2645 FastMixerStateQueue *sq = mFastMixer->sq();
2646 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002647 if (state->mCommand != FastMixerState::MIX_WRITE &&
2648 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002649 if (state->mCommand == FastMixerState::COLD_IDLE) {
2650 int32_t old = android_atomic_inc(&mFastMixerFutex);
2651 if (old == -1) {
2652 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2653 }
2654 }
2655 state->mCommand = FastMixerState::MIX_WRITE;
2656 sq->end();
2657 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002658 if (kUseFastMixer == FastMixer_Dynamic) {
2659 mNormalSink = mPipeSink;
2660 }
Glenn Kasten58912562012-04-03 10:45:00 -07002661 } else {
2662 sq->end(false /*didModify*/);
2663 }
2664 }
2665 PlaybackThread::threadLoop_write();
2666}
2667
Glenn Kasten000f0e32012-03-01 17:10:56 -08002668// shared by MIXER and DIRECT, overridden by DUPLICATING
2669void AudioFlinger::PlaybackThread::threadLoop_write()
2670{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002671 // FIXME rewrite to reduce number of system calls
2672 mLastWriteTime = systemTime();
2673 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002674
Glenn Kasten58912562012-04-03 10:45:00 -07002675#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002676 size_t count = mixBufferSize >> mBitShift;
2677 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2678 if (framesWritten > 0) {
2679 size_t bytesWritten = framesWritten << mBitShift;
2680 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002681 }
2682
Glenn Kasten952eeb22012-03-06 11:30:57 -08002683 mNumWrites++;
2684 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002685}
2686
Glenn Kasten58912562012-04-03 10:45:00 -07002687void AudioFlinger::MixerThread::threadLoop_standby()
2688{
2689 // Idle the fast mixer if it's currently running
2690 if (mFastMixer != NULL) {
2691 FastMixerStateQueue *sq = mFastMixer->sq();
2692 FastMixerState *state = sq->begin();
2693 if (!(state->mCommand & FastMixerState::IDLE)) {
2694 state->mCommand = FastMixerState::COLD_IDLE;
2695 state->mColdFutexAddr = &mFastMixerFutex;
2696 state->mColdGen++;
2697 mFastMixerFutex = 0;
2698 sq->end();
2699 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2700 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002701 if (kUseFastMixer == FastMixer_Dynamic) {
2702 mNormalSink = mOutputSink;
2703 }
Glenn Kasten58912562012-04-03 10:45:00 -07002704 } else {
2705 sq->end(false /*didModify*/);
2706 }
2707 }
2708 PlaybackThread::threadLoop_standby();
2709}
2710
Glenn Kasten000f0e32012-03-01 17:10:56 -08002711// shared by MIXER and DIRECT, overridden by DUPLICATING
2712void AudioFlinger::PlaybackThread::threadLoop_standby()
2713{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002714 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2715 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002716}
2717
2718void AudioFlinger::MixerThread::threadLoop_mix()
2719{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002720 // obtain the presentation timestamp of the next output buffer
2721 int64_t pts;
2722 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002723
Glenn Kasten952eeb22012-03-06 11:30:57 -08002724 if (NULL != mOutput->stream->get_next_write_timestamp) {
2725 status = mOutput->stream->get_next_write_timestamp(
2726 mOutput->stream, &pts);
2727 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002728
Glenn Kasten952eeb22012-03-06 11:30:57 -08002729 if (status != NO_ERROR) {
2730 pts = AudioBufferProvider::kInvalidPTS;
2731 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002732
Glenn Kasten952eeb22012-03-06 11:30:57 -08002733 // mix buffers...
2734 mAudioMixer->process(pts);
2735 // increase sleep time progressively when application underrun condition clears.
2736 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2737 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2738 // such that we would underrun the audio HAL.
2739 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2740 sleepTimeShift--;
2741 }
2742 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002743 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002744 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002745}
2746
2747void AudioFlinger::MixerThread::threadLoop_sleepTime()
2748{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002749 // If no tracks are ready, sleep once for the duration of an output
2750 // buffer size, then write 0s to the output
2751 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002752 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002753 sleepTime = activeSleepTime >> sleepTimeShift;
2754 if (sleepTime < kMinThreadSleepTimeUs) {
2755 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002757 // reduce sleep time in case of consecutive application underruns to avoid
2758 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2759 // duration we would end up writing less data than needed by the audio HAL if
2760 // the condition persists.
2761 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2762 sleepTimeShift++;
2763 }
2764 } else {
2765 sleepTime = idleSleepTime;
2766 }
2767 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002768 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 memset (mMixBuffer, 0, mixBufferSize);
2770 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002771 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002772 }
2773 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774}
2775
2776// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002777AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002778 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779{
2780
Glenn Kasten29c23c32012-01-26 13:37:52 -08002781 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002783 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 size_t mixedTracks = 0;
2785 size_t tracksWithEffect = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07002786 size_t fastTracks = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787
2788 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002789 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790
Eric Laurent571d49c2010-08-11 05:20:11 -07002791 if (masterMute) {
2792 masterVolume = 0;
2793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002795 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002797 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002798 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 masterVolume = (float)((v + (1 << 23)) >> 24);
2800 chain.clear();
2801 }
2802
2803 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002804 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 if (t == 0) continue;
2806
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002807 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002809
2810 if (track->isFastTrack()) {
2811 // cache the combined master volume and stream type volume for fast mixer;
2812 // this lacks any synchronization or barrier so VolumeProvider may read a stale value
2813 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2814 ++fastTracks;
2815 if (track->isTerminated()) {
2816 tracksToRemove->add(track);
2817 }
2818 continue;
2819 }
2820
2821 { // local variable scope to avoid goto warning
2822
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 audio_track_cblk_t* cblk = track->cblk();
2824
2825 // The first time a track is added we wait
2826 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002827 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002828 // make sure that we have enough frames to mix one full buffer.
2829 // enforce this condition only once to enable draining the buffer in case the client
2830 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002831 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002832 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002833 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002834 if (!track->isStopped() && !track->isPausing() &&
Eric Laurentda747442012-04-25 18:53:13 -07002835 (mMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002836 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002837 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002838 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002839 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002840 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002841 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002842 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002843 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2844 // the minimum track buffer size is normally twice the number of frames necessary
2845 // to fill one buffer and the resampler should not leave more than one buffer worth
2846 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002847 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002848 }
2849 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002850 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 !track->isPaused() && !track->isTerminated())
2852 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002853 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854
2855 mixedTracks++;
2856
2857 // track->mainBuffer() != mMixBuffer means there is an effect chain
2858 // connected to the track
2859 chain.clear();
2860 if (track->mainBuffer() != mMixBuffer) {
2861 chain = getEffectChain_l(track->sessionId());
2862 // Delegate volume control to effect in track effect chain if needed
2863 if (chain != 0) {
2864 tracksWithEffect++;
2865 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002866 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002867 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 }
2869 }
2870
2871
2872 int param = AudioMixer::VOLUME;
2873 if (track->mFillingUpStatus == Track::FS_FILLED) {
2874 // no ramp for the first volume setting
2875 track->mFillingUpStatus = Track::FS_ACTIVE;
2876 if (track->mState == TrackBase::RESUMING) {
2877 track->mState = TrackBase::ACTIVE;
2878 param = AudioMixer::RAMP_VOLUME;
2879 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002880 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 } else if (cblk->server != 0) {
2882 // If the track is stopped before the first frame was mixed,
2883 // do not apply ramp
2884 param = AudioMixer::RAMP_VOLUME;
2885 }
2886
2887 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002888 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002889 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002890 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002891 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 if (track->isPausing()) {
2893 track->setPaused();
2894 }
2895 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002896
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002898 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002900 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002901 vl = vlr & 0xFFFF;
2902 vr = vlr >> 16;
2903 // track volumes come from shared memory, so can't be trusted and must be clamped
2904 if (vl > MAX_GAIN_INT) {
2905 ALOGV("Track left volume out of range: %04X", vl);
2906 vl = MAX_GAIN_INT;
2907 }
2908 if (vr > MAX_GAIN_INT) {
2909 ALOGV("Track right volume out of range: %04X", vr);
2910 vr = MAX_GAIN_INT;
2911 }
2912 // now apply the master volume and stream type volume
2913 vl = (uint32_t)(v * vl) << 12;
2914 vr = (uint32_t)(v * vr) << 12;
2915 // assuming master volume and stream type volume each go up to 1.0,
2916 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917
Glenn Kasten05632a52012-01-03 14:22:33 -08002918 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2919 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002920 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002921 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002922 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002923 }
2924 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002926 // Delegate volume control to effect in track effect chain if needed
2927 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2928 // Do not ramp volume if volume is controlled by effect
2929 param = AudioMixer::VOLUME;
2930 track->mHasVolumeController = true;
2931 } else {
2932 // force no volume ramp when volume controller was just disabled or removed
2933 // from effect chain to avoid volume spike
2934 if (track->mHasVolumeController) {
2935 param = AudioMixer::VOLUME;
2936 }
2937 track->mHasVolumeController = false;
2938 }
2939
2940 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002941 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002942 vl = (vl + (1 << 11)) >> 12;
2943 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2944 vr = (vr + (1 << 11)) >> 12;
2945 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002946
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002947 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 -07002948
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002950 mAudioMixer->setBufferProvider(name, track);
2951 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002953 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2954 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2955 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002957 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 AudioMixer::TRACK,
2959 AudioMixer::FORMAT, (void *)track->format());
2960 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002961 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002963 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002965 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 AudioMixer::RESAMPLE,
2967 AudioMixer::SAMPLE_RATE,
2968 (void *)(cblk->sampleRate));
2969 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002970 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 AudioMixer::TRACK,
2972 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2973 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002974 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 AudioMixer::TRACK,
2976 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2977
2978 // reset retry count
2979 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002980
Eric Laurent27741442012-01-17 19:20:12 -08002981 // If one track is ready, set the mixer ready if:
2982 // - the mixer was not ready during previous round OR
2983 // - no other track is not ready
Eric Laurentda747442012-04-25 18:53:13 -07002984 if (mMixerStatus != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08002985 mixerStatus != MIXER_TRACKS_ENABLED) {
2986 mixerStatus = MIXER_TRACKS_READY;
2987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002989 //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 -07002990 if (track->isStopped()) {
2991 track->reset();
2992 }
2993 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2994 // We have consumed all the buffers of this track.
2995 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002996 // TODO: use actual buffer filling status instead of latency when available from
2997 // audio HAL
2998 size_t audioHALFrames =
2999 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3000 size_t framesWritten =
3001 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3002 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3003 tracksToRemove->add(track);
3004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 } else {
3006 // No buffers for this track. Give it a few chances to
3007 // fill a buffer, then remove it from active list.
3008 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003009 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07003011 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07003012 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003013 // If one track is not ready, mark the mixer also not ready if:
3014 // - the mixer was ready during previous round OR
3015 // - no other track is ready
Eric Laurentda747442012-04-25 18:53:13 -07003016 } else if (mMixerStatus == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003017 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018 mixerStatus = MIXER_TRACKS_ENABLED;
3019 }
3020 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003021 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 }
Glenn Kasten58912562012-04-03 10:45:00 -07003023
3024 } // local variable scope to avoid goto warning
3025track_is_ready: ;
3026
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 }
3028
Glenn Kasten58912562012-04-03 10:45:00 -07003029 // FIXME Here is where we would push the new FastMixer state if necessary
3030
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031 // remove all the tracks that need to be...
3032 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003033 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 for (size_t i=0 ; i<count ; i++) {
3035 const sp<Track>& track = tracksToRemove->itemAt(i);
3036 mActiveTracks.remove(track);
3037 if (track->mainBuffer() != mMixBuffer) {
3038 chain = getEffectChain_l(track->sessionId());
3039 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003040 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003041 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 }
3043 }
3044 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003045 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 }
3047 }
3048 }
3049
3050 // mix buffer must be cleared if all tracks are connected to an
3051 // effect chain as in this case the mixer will not write to
3052 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003053 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3054 // FIXME as a performance optimization, should remember previous zero status
3055 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 }
3057
Glenn Kasten58912562012-04-03 10:45:00 -07003058 // if any fast tracks, then status is ready
3059 if (fastTracks > 0) {
3060 mixerStatus = MIXER_TRACKS_READY;
3061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 return mixerStatus;
3063}
3064
Glenn Kasten66fcab92012-02-24 14:59:21 -08003065/*
3066The derived values that are cached:
3067 - mixBufferSize from frame count * frame size
3068 - activeSleepTime from activeSleepTimeUs()
3069 - idleSleepTime from idleSleepTimeUs()
3070 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3071 - maxPeriod from frame count and sample rate (MIXER only)
3072
3073The parameters that affect these derived values are:
3074 - frame count
3075 - frame size
3076 - sample rate
3077 - device type: A2DP or not
3078 - device latency
3079 - format: PCM or not
3080 - active sleep time
3081 - idle sleep time
3082*/
3083
3084void AudioFlinger::PlaybackThread::cacheParameters_l()
3085{
Glenn Kasten58912562012-04-03 10:45:00 -07003086 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003087 activeSleepTime = activeSleepTimeUs();
3088 idleSleepTime = idleSleepTimeUs();
3089}
3090
Glenn Kastenfff6d712012-01-12 16:38:12 -08003091void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092{
Steve Block3856b092011-10-20 11:56:00 +01003093 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003094 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003096
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 size_t size = mTracks.size();
3098 for (size_t i = 0; i < size; i++) {
3099 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003100 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003101 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 }
3104 }
3105}
3106
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003108int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003110 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111}
3112
3113// deleteTrackName_l() must be called with ThreadBase::mLock held
3114void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3115{
Steve Block3856b092011-10-20 11:56:00 +01003116 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 mAudioMixer->deleteTrackName(name);
3118}
3119
3120// checkForNewParameters_l() must be called with ThreadBase::mLock held
3121bool AudioFlinger::MixerThread::checkForNewParameters_l()
3122{
Glenn Kasten58912562012-04-03 10:45:00 -07003123 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3124 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 bool reconfig = false;
3126
3127 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003128
3129 if (mFastMixer != NULL) {
3130 FastMixerStateQueue *sq = mFastMixer->sq();
3131 FastMixerState *state = sq->begin();
3132 if (!(state->mCommand & FastMixerState::IDLE)) {
3133 previousCommand = state->mCommand;
3134 state->mCommand = FastMixerState::HOT_IDLE;
3135 sq->end();
3136 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3137 } else {
3138 sq->end(false /*didModify*/);
3139 }
3140 }
3141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 status_t status = NO_ERROR;
3143 String8 keyValuePair = mNewParameters[0];
3144 AudioParameter param = AudioParameter(keyValuePair);
3145 int value;
3146
3147 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3148 reconfig = true;
3149 }
3150 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003151 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 status = BAD_VALUE;
3153 } else {
3154 reconfig = true;
3155 }
3156 }
3157 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003158 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 status = BAD_VALUE;
3160 } else {
3161 reconfig = true;
3162 }
3163 }
3164 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3165 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003166 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 // if frame count is changed after track creation
3168 if (!mTracks.isEmpty()) {
3169 status = INVALID_OPERATION;
3170 } else {
3171 reconfig = true;
3172 }
3173 }
3174 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003175#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003176 // when changing the audio output device, call addBatteryData to notify
3177 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003178 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003179 uint32_t params = 0;
3180 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003181 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003182 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3183 }
3184
3185 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003186 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003187 // check if any other device (except speaker) is on
3188 if (value & deviceWithoutSpeaker ) {
3189 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3190 }
3191
3192 if (params != 0) {
3193 addBatteryData(params);
3194 }
3195 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003196#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003197
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 // forward device change to effects that have requested to be
3199 // aware of attached audio device.
3200 mDevice = (uint32_t)value;
3201 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003202 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 }
3204 }
3205
3206 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003207 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003208 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003210 mOutput->stream->common.standby(&mOutput->stream->common);
3211 mStandby = true;
3212 mBytesWritten = 0;
3213 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003214 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 }
3216 if (status == NO_ERROR && reconfig) {
3217 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003218 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3219 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003221 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003223 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 if (name < 0) break;
3225 mTracks[i]->mName = name;
3226 // limit track sample rate to 2 x new output sample rate
3227 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3228 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3229 }
3230 }
3231 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3232 }
3233 }
3234
3235 mNewParameters.removeAt(0);
3236
3237 mParamStatus = status;
3238 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003239 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3240 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003241 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 }
Glenn Kasten58912562012-04-03 10:45:00 -07003243
3244 if (!(previousCommand & FastMixerState::IDLE)) {
3245 ALOG_ASSERT(mFastMixer != NULL);
3246 FastMixerStateQueue *sq = mFastMixer->sq();
3247 FastMixerState *state = sq->begin();
3248 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3249 state->mCommand = previousCommand;
3250 sq->end();
3251 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3252 }
3253
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 return reconfig;
3255}
3256
3257status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3258{
3259 const size_t SIZE = 256;
3260 char buffer[SIZE];
3261 String8 result;
3262
3263 PlaybackThread::dumpInternals(fd, args);
3264
3265 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3266 result.append(buffer);
3267 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003268
3269 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3270 FastMixerDumpState copy = mFastMixerDumpState;
3271 copy.dump(fd);
3272
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 return NO_ERROR;
3274}
3275
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003276uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277{
Glenn Kasten58912562012-04-03 10:45:00 -07003278 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279}
3280
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003281uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003282{
Glenn Kasten58912562012-04-03 10:45:00 -07003283 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003284}
3285
Glenn Kasten66fcab92012-02-24 14:59:21 -08003286void AudioFlinger::MixerThread::cacheParameters_l()
3287{
3288 PlaybackThread::cacheParameters_l();
3289
3290 // FIXME: Relaxed timing because of a certain device that can't meet latency
3291 // Should be reduced to 2x after the vendor fixes the driver issue
3292 // increase threshold again due to low power audio mode. The way this warning
3293 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003294 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003295}
3296
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003298AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3299 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003300 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003301 // mLeftVolFloat, mRightVolFloat
3302 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304}
3305
3306AudioFlinger::DirectOutputThread::~DirectOutputThread()
3307{
3308}
3309
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003310AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3311 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003312)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003314 sp<Track> trackToRemove;
3315
Glenn Kastenfec279f2012-03-08 07:47:15 -08003316 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317
Glenn Kasten952eeb22012-03-06 11:30:57 -08003318 // find out which tracks need to be processed
3319 if (mActiveTracks.size() != 0) {
3320 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003321 // The track died recently
3322 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323
Glenn Kasten952eeb22012-03-06 11:30:57 -08003324 Track* const track = t.get();
3325 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326
Glenn Kasten952eeb22012-03-06 11:30:57 -08003327 // The first time a track is added we wait
3328 // for all its buffers to be filled before processing it
3329 if (cblk->framesReady() && track->isReady() &&
3330 !track->isPaused() && !track->isTerminated())
3331 {
3332 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333
Glenn Kasten952eeb22012-03-06 11:30:57 -08003334 if (track->mFillingUpStatus == Track::FS_FILLED) {
3335 track->mFillingUpStatus = Track::FS_ACTIVE;
3336 mLeftVolFloat = mRightVolFloat = 0;
3337 mLeftVolShort = mRightVolShort = 0;
3338 if (track->mState == TrackBase::RESUMING) {
3339 track->mState = TrackBase::ACTIVE;
3340 rampVolume = true;
3341 }
3342 } else if (cblk->server != 0) {
3343 // If the track is stopped before the first frame was mixed,
3344 // do not apply ramp
3345 rampVolume = true;
3346 }
3347 // compute volume for this track
3348 float left, right;
3349 if (track->isMuted() || mMasterMute || track->isPausing() ||
3350 mStreamTypes[track->streamType()].mute) {
3351 left = right = 0;
3352 if (track->isPausing()) {
3353 track->setPaused();
3354 }
3355 } else {
3356 float typeVolume = mStreamTypes[track->streamType()].volume;
3357 float v = mMasterVolume * typeVolume;
3358 uint32_t vlr = cblk->getVolumeLR();
3359 float v_clamped = v * (vlr & 0xFFFF);
3360 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3361 left = v_clamped/MAX_GAIN;
3362 v_clamped = v * (vlr >> 16);
3363 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3364 right = v_clamped/MAX_GAIN;
3365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366
Glenn Kasten952eeb22012-03-06 11:30:57 -08003367 if (left != mLeftVolFloat || right != mRightVolFloat) {
3368 mLeftVolFloat = left;
3369 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370
Glenn Kasten952eeb22012-03-06 11:30:57 -08003371 // If audio HAL implements volume control,
3372 // force software volume to nominal value
3373 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3374 left = 1.0f;
3375 right = 1.0f;
3376 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377
Glenn Kasten952eeb22012-03-06 11:30:57 -08003378 // Convert volumes from float to 8.24
3379 uint32_t vl = (uint32_t)(left * (1 << 24));
3380 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381
Glenn Kasten952eeb22012-03-06 11:30:57 -08003382 // Delegate volume control to effect in track effect chain if needed
3383 // only one effect chain can be present on DirectOutputThread, so if
3384 // there is one, the track is connected to it
3385 if (!mEffectChains.isEmpty()) {
3386 // Do not ramp volume if volume is controlled by effect
3387 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 rampVolume = false;
3389 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391
Glenn Kasten952eeb22012-03-06 11:30:57 -08003392 // Convert volumes from 8.24 to 4.12 format
3393 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3394 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3395 leftVol = (uint16_t)v_clamped;
3396 v_clamped = (vr + (1 << 11)) >> 12;
3397 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3398 rightVol = (uint16_t)v_clamped;
3399 } else {
3400 leftVol = mLeftVolShort;
3401 rightVol = mRightVolShort;
3402 rampVolume = false;
3403 }
3404
3405 // reset retry count
3406 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003407 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003408 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003409 } else {
3410 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3411 if (track->isStopped()) {
3412 track->reset();
3413 }
3414 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3415 // We have consumed all the buffers of this track.
3416 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003417 // TODO: implement behavior for compressed audio
3418 size_t audioHALFrames =
3419 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3420 size_t framesWritten =
3421 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3422 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3423 trackToRemove = track;
3424 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003425 } else {
3426 // No buffers for this track. Give it a few chances to
3427 // fill a buffer, then remove it from active list.
3428 if (--(track->mRetryCount) <= 0) {
3429 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3430 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003432 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 }
3434 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003435 }
3436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003438 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003439 // remove all the tracks that need to be...
3440 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003441 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003442 mActiveTracks.remove(trackToRemove);
3443 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003444 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003445 trackToRemove->sessionId());
3446 mEffectChains[0]->decActiveTrackCnt();
3447 }
3448 if (trackToRemove->isTerminated()) {
3449 removeTrack_l(trackToRemove);
3450 }
3451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452
Glenn Kastenfec279f2012-03-08 07:47:15 -08003453 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003454}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455
Glenn Kasten000f0e32012-03-01 17:10:56 -08003456void AudioFlinger::DirectOutputThread::threadLoop_mix()
3457{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003458 AudioBufferProvider::Buffer buffer;
3459 size_t frameCount = mFrameCount;
3460 int8_t *curBuf = (int8_t *)mMixBuffer;
3461 // output audio to hardware
3462 while (frameCount) {
3463 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003464 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003465 if (CC_UNLIKELY(buffer.raw == NULL)) {
3466 memset(curBuf, 0, frameCount * mFrameSize);
3467 break;
3468 }
3469 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3470 frameCount -= buffer.frameCount;
3471 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003472 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003473 }
3474 sleepTime = 0;
3475 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003476 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003477
3478 // apply volume
3479
3480 // Do not apply volume on compressed audio
3481 if (!audio_is_linear_pcm(mFormat)) {
3482 return;
3483 }
3484
3485 // convert to signed 16 bit before volume calculation
3486 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3487 size_t count = mFrameCount * mChannelCount;
3488 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3489 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003490 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003491 *dst-- = (int16_t)(*src--^0x80) << 8;
3492 }
3493 }
3494
3495 frameCount = mFrameCount;
3496 int16_t *out = mMixBuffer;
3497 if (rampVolume) {
3498 if (mChannelCount == 1) {
3499 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3500 int32_t vlInc = d / (int32_t)frameCount;
3501 int32_t vl = ((int32_t)mLeftVolShort << 16);
3502 do {
3503 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3504 out++;
3505 vl += vlInc;
3506 } while (--frameCount);
3507
3508 } else {
3509 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3510 int32_t vlInc = d / (int32_t)frameCount;
3511 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3512 int32_t vrInc = d / (int32_t)frameCount;
3513 int32_t vl = ((int32_t)mLeftVolShort << 16);
3514 int32_t vr = ((int32_t)mRightVolShort << 16);
3515 do {
3516 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3517 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3518 out += 2;
3519 vl += vlInc;
3520 vr += vrInc;
3521 } while (--frameCount);
3522 }
3523 } else {
3524 if (mChannelCount == 1) {
3525 do {
3526 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3527 out++;
3528 } while (--frameCount);
3529 } else {
3530 do {
3531 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3532 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3533 out += 2;
3534 } while (--frameCount);
3535 }
3536 }
3537
3538 // convert back to unsigned 8 bit after volume calculation
3539 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3540 size_t count = mFrameCount * mChannelCount;
3541 int16_t *src = mMixBuffer;
3542 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003543 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003544 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3545 }
3546 }
3547
3548 mLeftVolShort = leftVol;
3549 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003550}
3551
3552void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3553{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003554 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003555 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003556 sleepTime = activeSleepTime;
3557 } else {
3558 sleepTime = idleSleepTime;
3559 }
3560 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003561 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003562 sleepTime = 0;
3563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564}
3565
3566// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003567int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568{
3569 return 0;
3570}
3571
3572// deleteTrackName_l() must be called with ThreadBase::mLock held
3573void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3574{
3575}
3576
3577// checkForNewParameters_l() must be called with ThreadBase::mLock held
3578bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3579{
3580 bool reconfig = false;
3581
3582 while (!mNewParameters.isEmpty()) {
3583 status_t status = NO_ERROR;
3584 String8 keyValuePair = mNewParameters[0];
3585 AudioParameter param = AudioParameter(keyValuePair);
3586 int value;
3587
3588 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3589 // do not accept frame count changes if tracks are open as the track buffer
3590 // size depends on frame count and correct behavior would not be garantied
3591 // if frame count is changed after track creation
3592 if (!mTracks.isEmpty()) {
3593 status = INVALID_OPERATION;
3594 } else {
3595 reconfig = true;
3596 }
3597 }
3598 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003599 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003600 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003602 mOutput->stream->common.standby(&mOutput->stream->common);
3603 mStandby = true;
3604 mBytesWritten = 0;
3605 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003606 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 }
3608 if (status == NO_ERROR && reconfig) {
3609 readOutputParameters();
3610 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3611 }
3612 }
3613
3614 mNewParameters.removeAt(0);
3615
3616 mParamStatus = status;
3617 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003618 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3619 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003620 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621 }
3622 return reconfig;
3623}
3624
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003625uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626{
3627 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003628 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003629 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 } else {
3631 time = 10000;
3632 }
3633 return time;
3634}
3635
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003636uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637{
3638 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003639 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003640 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 } else {
3642 time = 10000;
3643 }
3644 return time;
3645}
3646
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003647uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003648{
3649 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003650 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003651 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3652 } else {
3653 time = 10000;
3654 }
3655 return time;
3656}
3657
Glenn Kasten66fcab92012-02-24 14:59:21 -08003658void AudioFlinger::DirectOutputThread::cacheParameters_l()
3659{
3660 PlaybackThread::cacheParameters_l();
3661
3662 // use shorter standby delay as on normal output to release
3663 // hardware resources as soon as possible
3664 standbyDelay = microseconds(activeSleepTime*2);
3665}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003666
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667// ----------------------------------------------------------------------------
3668
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003669AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003670 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003671 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3672 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 addOutputTrack(mainThread);
3675}
3676
3677AudioFlinger::DuplicatingThread::~DuplicatingThread()
3678{
3679 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3680 mOutputTracks[i]->destroy();
3681 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682}
3683
Glenn Kasten000f0e32012-03-01 17:10:56 -08003684void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 // mix buffers...
3687 if (outputsReady(outputTracks)) {
3688 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3689 } else {
3690 memset(mMixBuffer, 0, mixBufferSize);
3691 }
3692 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003693 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003694}
3695
3696void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3697{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003698 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003699 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 sleepTime = activeSleepTime;
3701 } else {
3702 sleepTime = idleSleepTime;
3703 }
3704 } else if (mBytesWritten != 0) {
3705 // flush remaining overflow buffers in output tracks
3706 for (size_t i = 0; i < outputTracks.size(); i++) {
3707 if (outputTracks[i]->isActive()) {
3708 sleepTime = 0;
3709 writeFrames = 0;
3710 memset(mMixBuffer, 0, mixBufferSize);
3711 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003713 }
3714 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003715}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716
Glenn Kasten000f0e32012-03-01 17:10:56 -08003717void AudioFlinger::DuplicatingThread::threadLoop_write()
3718{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003719 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003720 for (size_t i = 0; i < outputTracks.size(); i++) {
3721 outputTracks[i]->write(mMixBuffer, writeFrames);
3722 }
3723 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003724}
Glenn Kasten688a6402012-02-29 07:57:06 -08003725
Glenn Kasten000f0e32012-03-01 17:10:56 -08003726void AudioFlinger::DuplicatingThread::threadLoop_standby()
3727{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003728 // DuplicatingThread implements standby by stopping all tracks
3729 for (size_t i = 0; i < outputTracks.size(); i++) {
3730 outputTracks[i]->stop();
3731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732}
3733
Glenn Kastenfa26a852012-03-06 11:28:04 -08003734void AudioFlinger::DuplicatingThread::saveOutputTracks()
3735{
3736 outputTracks = mOutputTracks;
3737}
3738
3739void AudioFlinger::DuplicatingThread::clearOutputTracks()
3740{
3741 outputTracks.clear();
3742}
3743
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3745{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003746 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003747 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003748 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003749 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 this,
3751 mSampleRate,
3752 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003753 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754 frameCount);
3755 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003756 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003758 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003759 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 }
3761}
3762
3763void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3764{
3765 Mutex::Autolock _l(mLock);
3766 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003767 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 mOutputTracks[i]->destroy();
3769 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003770 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 return;
3772 }
3773 }
Steve Block3856b092011-10-20 11:56:00 +01003774 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775}
3776
Glenn Kasten438b0362012-03-06 11:24:48 -08003777// caller must hold mLock
3778void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779{
3780 mWaitTimeMs = UINT_MAX;
3781 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3782 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003783 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3785 if (waitTimeMs < mWaitTimeMs) {
3786 mWaitTimeMs = waitTimeMs;
3787 }
3788 }
3789 }
3790}
3791
3792
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003793bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794{
3795 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003796 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003798 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 return false;
3800 }
3801 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3802 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003803 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003804 return false;
3805 }
3806 }
3807 return true;
3808}
3809
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003810uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003811{
3812 return (mWaitTimeMs * 1000) / 2;
3813}
3814
Glenn Kasten66fcab92012-02-24 14:59:21 -08003815void AudioFlinger::DuplicatingThread::cacheParameters_l()
3816{
3817 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3818 updateWaitTime_l();
3819
3820 MixerThread::cacheParameters_l();
3821}
3822
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823// ----------------------------------------------------------------------------
3824
3825// TrackBase constructor must be called with AudioFlinger::mLock held
3826AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003827 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828 const sp<Client>& client,
3829 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003830 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003831 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 const sp<IMemory>& sharedBuffer,
3834 int sessionId)
3835 : RefBase(),
3836 mThread(thread),
3837 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003838 mCblk(NULL),
3839 // mBuffer
3840 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841 mFrameCount(0),
3842 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003843 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003845 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003847 // mChannelCount
3848 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003849{
Steve Block3856b092011-10-20 11:56:00 +01003850 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003851
Steve Blockb8a80522011-12-20 16:23:08 +00003852 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003853 size_t size = sizeof(audio_track_cblk_t);
3854 uint8_t channelCount = popcount(channelMask);
3855 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3856 if (sharedBuffer == 0) {
3857 size += bufferSize;
3858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003860 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 mCblkMemory = client->heap()->allocate(size);
3862 if (mCblkMemory != 0) {
3863 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003864 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 new(mCblk) audio_track_cblk_t();
3866 // clear all buffers
3867 mCblk->frameCount = frameCount;
3868 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003869// uncomment the following lines to quickly test 32-bit wraparound
3870// mCblk->user = 0xffff0000;
3871// mCblk->server = 0xffff0000;
3872// mCblk->userBase = 0xffff0000;
3873// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003874 mChannelCount = channelCount;
3875 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876 if (sharedBuffer == 0) {
3877 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3878 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3879 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003880 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881 mCblk->flags = CBLK_UNDERRUN_ON;
3882 } else {
3883 mBuffer = sharedBuffer->pointer();
3884 }
3885 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3886 }
3887 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003888 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 client->heap()->dump("AudioTrack");
3890 return;
3891 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003892 } else {
3893 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003894 // construct the shared structure in-place.
3895 new(mCblk) audio_track_cblk_t();
3896 // clear all buffers
3897 mCblk->frameCount = frameCount;
3898 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003899// uncomment the following lines to quickly test 32-bit wraparound
3900// mCblk->user = 0xffff0000;
3901// mCblk->server = 0xffff0000;
3902// mCblk->userBase = 0xffff0000;
3903// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003904 mChannelCount = channelCount;
3905 mChannelMask = channelMask;
3906 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3907 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3908 // Force underrun condition to avoid false underrun callback until first data is
3909 // written to buffer (other flags are cleared)
3910 mCblk->flags = CBLK_UNDERRUN_ON;
3911 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913}
3914
3915AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3916{
Glenn Kastena0d68332012-01-27 16:47:15 -08003917 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003918 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003920 } else {
3921 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922 }
3923 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003924 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003925 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003926 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003928 // If the client's reference count drops to zero, the associated destructor
3929 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3930 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 mClient.clear();
3932 }
3933}
3934
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003935// AudioBufferProvider interface
3936// getNextBuffer() = 0;
3937// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3939{
Glenn Kastene0feee32011-12-13 11:53:26 -08003940 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003942 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943 buffer->frameCount = 0;
3944}
3945
3946bool AudioFlinger::ThreadBase::TrackBase::step() {
3947 bool result;
3948 audio_track_cblk_t* cblk = this->cblk();
3949
3950 result = cblk->stepServer(mFrameCount);
3951 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003952 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003953 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 }
3955 return result;
3956}
3957
3958void AudioFlinger::ThreadBase::TrackBase::reset() {
3959 audio_track_cblk_t* cblk = this->cblk();
3960
3961 cblk->user = 0;
3962 cblk->server = 0;
3963 cblk->userBase = 0;
3964 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003965 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003966 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967}
3968
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3970 return (int)mCblk->sampleRate;
3971}
3972
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3974 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003975 size_t frameSize = cblk->frameSize;
3976 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3977 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978
3979 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003980 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3981 "TrackBase::getBuffer buffer out of range:\n"
3982 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3983 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003985 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986
3987 return bufferStart;
3988}
3989
Eric Laurenta011e352012-03-29 15:51:43 -07003990status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3991{
3992 mSyncEvents.add(event);
3993 return NO_ERROR;
3994}
3995
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996// ----------------------------------------------------------------------------
3997
3998// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3999AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004000 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004002 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004004 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004005 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 int frameCount,
4007 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004008 int sessionId,
4009 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004010 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004011 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004012 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004013 // mRetryCount initialized later when needed
4014 mSharedBuffer(sharedBuffer),
4015 mStreamType(streamType),
4016 mName(-1), // see note below
4017 mMainBuffer(thread->mixBuffer()),
4018 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004019 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004020 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004021 mFlags(flags),
4022 mFastIndex(-1),
4023 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024{
4025 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4027 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004028 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004029 if (flags & IAudioFlinger::TRACK_FAST) {
4030 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4031 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4032 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4033 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
4034 mFastIndex = i;
4035 thread->mFastTrackAvailMask &= ~(1 << i);
4036 // Although we've allocated an index, we can't mutate or push a new fast track state
4037 // here, because that data structure can only be changed within the normal mixer
4038 // threadLoop(). So instead, make a note to mutate and push later.
4039 thread->mFastTrackNewArray[i] = this;
4040 thread->mFastTrackNewMask |= 1 << i;
4041 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004042 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004043 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004044 if (mName < 0) {
4045 ALOGE("no more track names available");
4046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004048 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049}
4050
4051AudioFlinger::PlaybackThread::Track::~Track()
4052{
Steve Block3856b092011-10-20 11:56:00 +01004053 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 sp<ThreadBase> thread = mThread.promote();
4055 if (thread != 0) {
4056 Mutex::Autolock _l(thread->mLock);
4057 mState = TERMINATED;
4058 }
4059}
4060
4061void AudioFlinger::PlaybackThread::Track::destroy()
4062{
4063 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4064 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004065 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 // we must acquire a strong reference on this Track before locking mLock
4067 // here so that the destructor is called only when exiting this function.
4068 // On the other hand, as long as Track::destroy() is only called by
4069 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4070 // this Track with its member mTrack.
4071 sp<Track> keep(this);
4072 { // scope for mLock
4073 sp<ThreadBase> thread = mThread.promote();
4074 if (thread != 0) {
4075 if (!isOutputTrack()) {
4076 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004077 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004078
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004079#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004080 // to track the speaker usage
4081 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004082#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 }
4084 AudioSystem::releaseOutput(thread->id());
4085 }
4086 Mutex::Autolock _l(thread->mLock);
4087 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4088 playbackThread->destroyTrack_l(this);
4089 }
4090 }
4091}
4092
4093void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4094{
Glenn Kasten83d86532012-01-17 14:39:34 -08004095 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004096 if (isFastTrack()) {
4097 strcpy(buffer, " fast");
4098 } else {
4099 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4100 }
4101 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %1d %1d %1d %5u %5.2g %5.2g 0x%08x 0x%08x 0x%08x 0x%08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004102 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 mStreamType,
4104 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004105 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 mSessionId,
4107 mFrameCount,
4108 mState,
4109 mMute,
4110 mFillingUpStatus,
4111 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004112 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4113 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 mCblk->server,
4115 mCblk->user,
4116 (int)mMainBuffer,
4117 (int)mAuxBuffer);
4118}
4119
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004120// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004121status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004122 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004124 audio_track_cblk_t* cblk = this->cblk();
4125 uint32_t framesReady;
4126 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004128 // Check if last stepServer failed, try to step now
4129 if (mStepServerFailed) {
4130 if (!step()) goto getNextBuffer_exit;
4131 ALOGV("stepServer recovered");
4132 mStepServerFailed = false;
4133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004135 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004137 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 uint32_t s = cblk->server;
4139 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4140
4141 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4142 if (framesReq > framesReady) {
4143 framesReq = framesReady;
4144 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004145 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 framesReq = bufferEnd - s;
4147 }
4148
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004149 buffer->raw = getBuffer(s, framesReq);
4150 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004152 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155
4156getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004157 buffer->raw = NULL;
4158 buffer->frameCount = 0;
4159 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4160 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161}
4162
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004163uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004164 return mCblk->framesReady();
4165}
4166
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004168 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169
John Grossman4ff14ba2012-02-08 16:37:41 -08004170 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4172 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004173 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 return true;
4175 }
4176 return false;
4177}
4178
Glenn Kasten3acbd052012-02-28 10:39:56 -08004179status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004180 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181{
4182 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004183 ALOGV("start(%d), calling pid %d session %d",
4184 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004185
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 sp<ThreadBase> thread = mThread.promote();
4187 if (thread != 0) {
4188 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004189 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 // here the track could be either new, or restarted
4191 // in both cases "unstop" the track
4192 if (mState == PAUSED) {
4193 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004194 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 } else {
4196 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004197 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 }
4199
4200 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4201 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004202 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004204
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004205#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004206 // to track the speaker usage
4207 if (status == NO_ERROR) {
4208 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4209 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004210#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 }
4212 if (status == NO_ERROR) {
4213 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4214 playbackThread->addTrack_l(this);
4215 } else {
4216 mState = state;
4217 }
4218 } else {
4219 status = BAD_VALUE;
4220 }
4221 return status;
4222}
4223
4224void AudioFlinger::PlaybackThread::Track::stop()
4225{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004226 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 sp<ThreadBase> thread = mThread.promote();
4228 if (thread != 0) {
4229 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004230 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 if (mState > STOPPED) {
4232 mState = STOPPED;
4233 // If the track is not active (PAUSED and buffers full), flush buffers
4234 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4235 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4236 reset();
4237 }
Steve Block3856b092011-10-20 11:56:00 +01004238 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 }
4240 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4241 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004242 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004244
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004245#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004246 // to track the speaker usage
4247 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004248#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 }
4250 }
4251}
4252
4253void AudioFlinger::PlaybackThread::Track::pause()
4254{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004255 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 sp<ThreadBase> thread = mThread.promote();
4257 if (thread != 0) {
4258 Mutex::Autolock _l(thread->mLock);
4259 if (mState == ACTIVE || mState == RESUMING) {
4260 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004261 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 if (!isOutputTrack()) {
4263 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004264 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004266
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004267#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004268 // to track the speaker usage
4269 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004270#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 }
4272 }
4273 }
4274}
4275
4276void AudioFlinger::PlaybackThread::Track::flush()
4277{
Steve Block3856b092011-10-20 11:56:00 +01004278 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 sp<ThreadBase> thread = mThread.promote();
4280 if (thread != 0) {
4281 Mutex::Autolock _l(thread->mLock);
4282 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4283 return;
4284 }
4285 // No point remaining in PAUSED state after a flush => go to
4286 // STOPPED state
4287 mState = STOPPED;
4288
Eric Laurent38ccae22011-03-28 18:37:07 -07004289 // do not reset the track if it is still in the process of being stopped or paused.
4290 // this will be done by prepareTracks_l() when the track is stopped.
4291 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4292 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4293 reset();
4294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295 }
4296}
4297
4298void AudioFlinger::PlaybackThread::Track::reset()
4299{
4300 // Do not reset twice to avoid discarding data written just after a flush and before
4301 // the audioflinger thread detects the track is stopped.
4302 if (!mResetDone) {
4303 TrackBase::reset();
4304 // Force underrun condition to avoid false underrun callback until first data is
4305 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004306 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4307 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 mFillingUpStatus = FS_FILLING;
4309 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004310 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311 }
4312}
4313
4314void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4315{
4316 mMute = muted;
4317}
4318
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4320{
4321 status_t status = DEAD_OBJECT;
4322 sp<ThreadBase> thread = mThread.promote();
4323 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004324 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4325 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 }
4327 return status;
4328}
4329
4330void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4331{
4332 mAuxEffectId = EffectId;
4333 mAuxBuffer = buffer;
4334}
4335
Eric Laurenta011e352012-03-29 15:51:43 -07004336bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4337 size_t audioHalFrames)
4338{
4339 // a track is considered presented when the total number of frames written to audio HAL
4340 // corresponds to the number of frames written when presentationComplete() is called for the
4341 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4342 if (mPresentationCompleteFrames == 0) {
4343 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4344 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4345 mPresentationCompleteFrames, audioHalFrames);
4346 }
4347 if (framesWritten >= mPresentationCompleteFrames) {
4348 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4349 mSessionId, framesWritten);
4350 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4351 mPresentationCompleteFrames = 0;
4352 return true;
4353 }
4354 return false;
4355}
4356
4357void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4358{
4359 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4360 if (mSyncEvents[i]->type() == type) {
4361 mSyncEvents[i]->trigger();
4362 mSyncEvents.removeAt(i);
4363 i--;
4364 }
4365 }
4366}
4367
Glenn Kasten58912562012-04-03 10:45:00 -07004368// implement VolumeBufferProvider interface
4369
4370uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4371{
4372 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4373 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4374 uint32_t vlr = mCblk->getVolumeLR();
4375 uint32_t vl = vlr & 0xFFFF;
4376 uint32_t vr = vlr >> 16;
4377 // track volumes come from shared memory, so can't be trusted and must be clamped
4378 if (vl > MAX_GAIN_INT) {
4379 vl = MAX_GAIN_INT;
4380 }
4381 if (vr > MAX_GAIN_INT) {
4382 vr = MAX_GAIN_INT;
4383 }
4384 // now apply the cached master volume and stream type volume;
4385 // this is trusted but lacks any synchronization or barrier so may be stale
4386 float v = mCachedVolume;
4387 vl *= v;
4388 vr *= v;
4389 // re-combine into U4.16
4390 vlr = (vr << 16) | (vl & 0xFFFF);
4391 // FIXME look at mute, pause, and stop flags
4392 return vlr;
4393}
Eric Laurenta011e352012-03-29 15:51:43 -07004394
John Grossman4ff14ba2012-02-08 16:37:41 -08004395// timed audio tracks
4396
4397sp<AudioFlinger::PlaybackThread::TimedTrack>
4398AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004399 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004400 const sp<Client>& client,
4401 audio_stream_type_t streamType,
4402 uint32_t sampleRate,
4403 audio_format_t format,
4404 uint32_t channelMask,
4405 int frameCount,
4406 const sp<IMemory>& sharedBuffer,
4407 int sessionId) {
4408 if (!client->reserveTimedTrack())
4409 return NULL;
4410
Glenn Kastena0356762012-03-19 10:38:51 -07004411 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004412 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4413 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004414}
4415
4416AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004417 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004418 const sp<Client>& client,
4419 audio_stream_type_t streamType,
4420 uint32_t sampleRate,
4421 audio_format_t format,
4422 uint32_t channelMask,
4423 int frameCount,
4424 const sp<IMemory>& sharedBuffer,
4425 int sessionId)
4426 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004427 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004428 mQueueHeadInFlight(false),
4429 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004430 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004431 mTimedSilenceBuffer(NULL),
4432 mTimedSilenceBufferSize(0),
4433 mTimedAudioOutputOnTime(false),
4434 mMediaTimeTransformValid(false)
4435{
4436 LocalClock lc;
4437 mLocalTimeFreq = lc.getLocalFreq();
4438
4439 mLocalTimeToSampleTransform.a_zero = 0;
4440 mLocalTimeToSampleTransform.b_zero = 0;
4441 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4442 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4443 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4444 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004445
4446 mMediaTimeToSampleTransform.a_zero = 0;
4447 mMediaTimeToSampleTransform.b_zero = 0;
4448 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4449 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4450 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4451 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004452}
4453
4454AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4455 mClient->releaseTimedTrack();
4456 delete [] mTimedSilenceBuffer;
4457}
4458
4459status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4460 size_t size, sp<IMemory>* buffer) {
4461
4462 Mutex::Autolock _l(mTimedBufferQueueLock);
4463
4464 trimTimedBufferQueue_l();
4465
4466 // lazily initialize the shared memory heap for timed buffers
4467 if (mTimedMemoryDealer == NULL) {
4468 const int kTimedBufferHeapSize = 512 << 10;
4469
4470 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4471 "AudioFlingerTimed");
4472 if (mTimedMemoryDealer == NULL)
4473 return NO_MEMORY;
4474 }
4475
4476 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4477 if (newBuffer == NULL) {
4478 newBuffer = mTimedMemoryDealer->allocate(size);
4479 if (newBuffer == NULL)
4480 return NO_MEMORY;
4481 }
4482
4483 *buffer = newBuffer;
4484 return NO_ERROR;
4485}
4486
4487// caller must hold mTimedBufferQueueLock
4488void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4489 int64_t mediaTimeNow;
4490 {
4491 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4492 if (!mMediaTimeTransformValid)
4493 return;
4494
4495 int64_t targetTimeNow;
4496 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4497 ? mCCHelper.getCommonTime(&targetTimeNow)
4498 : mCCHelper.getLocalTime(&targetTimeNow);
4499
4500 if (OK != res)
4501 return;
4502
4503 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4504 &mediaTimeNow)) {
4505 return;
4506 }
4507 }
4508
John Grossman1c345192012-03-27 14:00:17 -07004509 size_t trimEnd;
4510 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004511 int64_t bufEnd;
4512
John Grossmanc95cfbb2012-04-12 11:53:11 -07004513 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4514 // We have a next buffer. Just use its PTS as the PTS of the frame
4515 // following the last frame in this buffer. If the stream is sparse
4516 // (ie, there are deliberate gaps left in the stream which should be
4517 // filled with silence by the TimedAudioTrack), then this can result
4518 // in one extra buffer being left un-trimmed when it could have
4519 // been. In general, this is not typical, and we would rather
4520 // optimized away the TS calculation below for the more common case
4521 // where PTSes are contiguous.
4522 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4523 } else {
4524 // We have no next buffer. Compute the PTS of the frame following
4525 // the last frame in this buffer by computing the duration of of
4526 // this frame in media time units and adding it to the PTS of the
4527 // buffer.
4528 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4529 / mCblk->frameSize;
4530
4531 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4532 &bufEnd)) {
4533 ALOGE("Failed to convert frame count of %lld to media time"
4534 " duration" " (scale factor %d/%u) in %s",
4535 frameCount,
4536 mMediaTimeToSampleTransform.a_to_b_numer,
4537 mMediaTimeToSampleTransform.a_to_b_denom,
4538 __PRETTY_FUNCTION__);
4539 break;
4540 }
4541 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004542 }
John Grossman9fbdee12012-03-26 17:51:46 -07004543
4544 if (bufEnd > mediaTimeNow)
4545 break;
4546
4547 // Is the buffer we want to use in the middle of a mix operation right
4548 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4549 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004550 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004551 mTrimQueueHeadOnRelease = true;
4552 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004553 }
4554
John Grossman9fbdee12012-03-26 17:51:46 -07004555 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004556 if (trimStart < trimEnd) {
4557 // Update the bookkeeping for framesReady()
4558 for (size_t i = trimStart; i < trimEnd; ++i) {
4559 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4560 }
4561
4562 // Now actually remove the buffers from the queue.
4563 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004564 }
4565}
4566
John Grossman1c345192012-03-27 14:00:17 -07004567void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4568 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004569 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4570 "%s called (reason \"%s\"), but timed buffer queue has no"
4571 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004572
4573 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4574 mTimedBufferQueue.removeAt(0);
4575}
4576
4577void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4578 const TimedBuffer& buf,
4579 const char* logTag) {
4580 uint32_t bufBytes = buf.buffer()->size();
4581 uint32_t consumedAlready = buf.position();
4582
Eric Laurentb388e532012-04-14 13:32:48 -07004583 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004584 "Bad bookkeeping while updating frames pending. Timed buffer is"
4585 " only %u bytes long, but claims to have consumed %u"
4586 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004587 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004588
4589 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004590 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4591 "Bad bookkeeping while updating frames pending. Should have at"
4592 " least %u queued frames, but we think we have only %u. (update"
4593 " reason: \"%s\")",
4594 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004595
4596 mFramesPendingInQueue -= bufFrames;
4597}
4598
John Grossman4ff14ba2012-02-08 16:37:41 -08004599status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4600 const sp<IMemory>& buffer, int64_t pts) {
4601
4602 {
4603 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4604 if (!mMediaTimeTransformValid)
4605 return INVALID_OPERATION;
4606 }
4607
4608 Mutex::Autolock _l(mTimedBufferQueueLock);
4609
John Grossman1c345192012-03-27 14:00:17 -07004610 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4611 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004612 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4613
4614 return NO_ERROR;
4615}
4616
4617status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4618 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4619
John Grossman1c345192012-03-27 14:00:17 -07004620 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4621 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4622 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004623
4624 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4625 target == TimedAudioTrack::COMMON_TIME)) {
4626 return BAD_VALUE;
4627 }
4628
4629 Mutex::Autolock lock(mMediaTimeTransformLock);
4630 mMediaTimeTransform = xform;
4631 mMediaTimeTransformTarget = target;
4632 mMediaTimeTransformValid = true;
4633
4634 return NO_ERROR;
4635}
4636
4637#define min(a, b) ((a) < (b) ? (a) : (b))
4638
4639// implementation of getNextBuffer for tracks whose buffers have timestamps
4640status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4641 AudioBufferProvider::Buffer* buffer, int64_t pts)
4642{
4643 if (pts == AudioBufferProvider::kInvalidPTS) {
4644 buffer->raw = 0;
4645 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004646 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004647 return INVALID_OPERATION;
4648 }
4649
John Grossman4ff14ba2012-02-08 16:37:41 -08004650 Mutex::Autolock _l(mTimedBufferQueueLock);
4651
John Grossman9fbdee12012-03-26 17:51:46 -07004652 ALOG_ASSERT(!mQueueHeadInFlight,
4653 "getNextBuffer called without releaseBuffer!");
4654
John Grossman4ff14ba2012-02-08 16:37:41 -08004655 while (true) {
4656
4657 // if we have no timed buffers, then fail
4658 if (mTimedBufferQueue.isEmpty()) {
4659 buffer->raw = 0;
4660 buffer->frameCount = 0;
4661 return NOT_ENOUGH_DATA;
4662 }
4663
4664 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4665
4666 // calculate the PTS of the head of the timed buffer queue expressed in
4667 // local time
4668 int64_t headLocalPTS;
4669 {
4670 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4671
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004672 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004673
4674 if (mMediaTimeTransform.a_to_b_denom == 0) {
4675 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004676 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004677 return NO_ERROR;
4678 }
4679
4680 int64_t transformedPTS;
4681 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4682 &transformedPTS)) {
4683 // the transform failed. this shouldn't happen, but if it does
4684 // then just drop this buffer
4685 ALOGW("timedGetNextBuffer transform failed");
4686 buffer->raw = 0;
4687 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004688 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004689 return NO_ERROR;
4690 }
4691
4692 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4693 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4694 &headLocalPTS)) {
4695 buffer->raw = 0;
4696 buffer->frameCount = 0;
4697 return INVALID_OPERATION;
4698 }
4699 } else {
4700 headLocalPTS = transformedPTS;
4701 }
4702 }
4703
4704 // adjust the head buffer's PTS to reflect the portion of the head buffer
4705 // that has already been consumed
4706 int64_t effectivePTS = headLocalPTS +
4707 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4708
4709 // Calculate the delta in samples between the head of the input buffer
4710 // queue and the start of the next output buffer that will be written.
4711 // If the transformation fails because of over or underflow, it means
4712 // that the sample's position in the output stream is so far out of
4713 // whack that it should just be dropped.
4714 int64_t sampleDelta;
4715 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4716 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004717 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4718 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004719 continue;
4720 }
4721 if (!mLocalTimeToSampleTransform.doForwardTransform(
4722 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004723 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004724 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004725 continue;
4726 }
4727
John Grossman1c345192012-03-27 14:00:17 -07004728 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4729 " sampleDelta=[%d.%08x]",
4730 head.pts(), head.position(), pts,
4731 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4732 + (sampleDelta >> 32)),
4733 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004734
4735 // if the delta between the ideal placement for the next input sample and
4736 // the current output position is within this threshold, then we will
4737 // concatenate the next input samples to the previous output
4738 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004739 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004740
4741 // if this is the first buffer of audio that we're emitting from this track
4742 // then it should be almost exactly on time.
4743 const int64_t kSampleStartupThreshold = 1LL << 32;
4744
4745 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004746 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004747 // the next input is close enough to being on time, so concatenate it
4748 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004749 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004750
John Grossman1c345192012-03-27 14:00:17 -07004751 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4752 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004753 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004754 }
4755
4756 // Looks like our output is not on time. Reset our on timed status.
4757 // Next time we mix samples from our input queue, then should be within
4758 // the StartupThreshold.
4759 mTimedAudioOutputOnTime = false;
4760 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004761 // the gap between the current output position and the proper start of
4762 // the next input sample is too big, so fill it with silence
4763 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4764
John Grossman9fbdee12012-03-26 17:51:46 -07004765 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004766 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4767 return NO_ERROR;
4768 } else {
4769 // the next input sample is late
4770 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4771 size_t onTimeSamplePosition =
4772 head.position() + lateFrames * mCblk->frameSize;
4773
4774 if (onTimeSamplePosition > head.buffer()->size()) {
4775 // all the remaining samples in the head are too late, so
4776 // drop it and move on
4777 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004778 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004779 continue;
4780 } else {
4781 // skip over the late samples
4782 head.setPosition(onTimeSamplePosition);
4783
4784 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004785 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004786
4787 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4788 return NO_ERROR;
4789 }
4790 }
4791 }
4792}
4793
4794// Yield samples from the timed buffer queue head up to the given output
4795// buffer's capacity.
4796//
4797// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004798void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004799 AudioBufferProvider::Buffer* buffer) {
4800
4801 const TimedBuffer& head = mTimedBufferQueue[0];
4802
4803 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4804 head.position());
4805
4806 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4807 mCblk->frameSize);
4808 size_t framesRequested = buffer->frameCount;
4809 buffer->frameCount = min(framesLeftInHead, framesRequested);
4810
John Grossman9fbdee12012-03-26 17:51:46 -07004811 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004812 mTimedAudioOutputOnTime = true;
4813}
4814
4815// Yield samples of silence up to the given output buffer's capacity
4816//
4817// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004818void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004819 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4820
4821 // lazily allocate a buffer filled with silence
4822 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4823 delete [] mTimedSilenceBuffer;
4824 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4825 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4826 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4827 }
4828
4829 buffer->raw = mTimedSilenceBuffer;
4830 size_t framesRequested = buffer->frameCount;
4831 buffer->frameCount = min(numFrames, framesRequested);
4832
4833 mTimedAudioOutputOnTime = false;
4834}
4835
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004836// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004837void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4838 AudioBufferProvider::Buffer* buffer) {
4839
4840 Mutex::Autolock _l(mTimedBufferQueueLock);
4841
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004842 // If the buffer which was just released is part of the buffer at the head
4843 // of the queue, be sure to update the amt of the buffer which has been
4844 // consumed. If the buffer being returned is not part of the head of the
4845 // queue, its either because the buffer is part of the silence buffer, or
4846 // because the head of the timed queue was trimmed after the mixer called
4847 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004848 if (buffer->raw == mTimedSilenceBuffer) {
4849 ALOG_ASSERT(!mQueueHeadInFlight,
4850 "Queue head in flight during release of silence buffer!");
4851 goto done;
4852 }
4853
4854 ALOG_ASSERT(mQueueHeadInFlight,
4855 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4856 " head in flight.");
4857
4858 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004859 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004860
4861 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004862 void* end = reinterpret_cast<void*>(
4863 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4864 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004865
John Grossman9fbdee12012-03-26 17:51:46 -07004866 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4867 "released buffer not within the head of the timed buffer"
4868 " queue; qHead = [%p, %p], released buffer = %p",
4869 start, end, buffer->raw);
4870
4871 head.setPosition(head.position() +
4872 (buffer->frameCount * mCblk->frameSize));
4873 mQueueHeadInFlight = false;
4874
John Grossman1c345192012-03-27 14:00:17 -07004875 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4876 "Bad bookkeeping during releaseBuffer! Should have at"
4877 " least %u queued frames, but we think we have only %u",
4878 buffer->frameCount, mFramesPendingInQueue);
4879
4880 mFramesPendingInQueue -= buffer->frameCount;
4881
John Grossman9fbdee12012-03-26 17:51:46 -07004882 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4883 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004884 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004885 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004886 }
John Grossman9fbdee12012-03-26 17:51:46 -07004887 } else {
4888 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4889 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004890 }
4891
John Grossman9fbdee12012-03-26 17:51:46 -07004892done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004893 buffer->raw = 0;
4894 buffer->frameCount = 0;
4895}
4896
4897uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4898 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004899 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004900}
4901
4902AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4903 : mPTS(0), mPosition(0) {}
4904
4905AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4906 const sp<IMemory>& buffer, int64_t pts)
4907 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4908
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909// ----------------------------------------------------------------------------
4910
4911// RecordTrack constructor must be called with AudioFlinger::mLock held
4912AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004913 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 const sp<Client>& client,
4915 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004916 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004917 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004919 int sessionId)
4920 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004921 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 mOverflow(false)
4923{
4924 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004925 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4926 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4927 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4928 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4929 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4930 } else {
4931 mCblk->frameSize = sizeof(int8_t);
4932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 }
4934}
4935
4936AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4937{
4938 sp<ThreadBase> thread = mThread.promote();
4939 if (thread != 0) {
4940 AudioSystem::releaseInput(thread->id());
4941 }
4942}
4943
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004944// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004945status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946{
4947 audio_track_cblk_t* cblk = this->cblk();
4948 uint32_t framesAvail;
4949 uint32_t framesReq = buffer->frameCount;
4950
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004951 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004952 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004953 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004954 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004955 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004956 }
4957
4958 framesAvail = cblk->framesAvailable_l();
4959
Glenn Kastenf6b16782011-12-15 09:51:17 -08004960 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961 uint32_t s = cblk->server;
4962 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4963
4964 if (framesReq > framesAvail) {
4965 framesReq = framesAvail;
4966 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004967 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 framesReq = bufferEnd - s;
4969 }
4970
4971 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004972 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004973
4974 buffer->frameCount = framesReq;
4975 return NO_ERROR;
4976 }
4977
4978getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004979 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 buffer->frameCount = 0;
4981 return NOT_ENOUGH_DATA;
4982}
4983
Glenn Kasten3acbd052012-02-28 10:39:56 -08004984status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004985 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986{
4987 sp<ThreadBase> thread = mThread.promote();
4988 if (thread != 0) {
4989 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004990 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 } else {
4992 return BAD_VALUE;
4993 }
4994}
4995
4996void AudioFlinger::RecordThread::RecordTrack::stop()
4997{
4998 sp<ThreadBase> thread = mThread.promote();
4999 if (thread != 0) {
5000 RecordThread *recordThread = (RecordThread *)thread.get();
5001 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005002 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005003 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005004 // read from buffer
5005 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 }
5007}
5008
5009void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5010{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005011 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005012 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005014 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 mSessionId,
5016 mFrameCount,
5017 mState,
5018 mCblk->sampleRate,
5019 mCblk->server,
5020 mCblk->user);
5021}
5022
5023
5024// ----------------------------------------------------------------------------
5025
5026AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005027 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028 DuplicatingThread *sourceThread,
5029 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005030 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005031 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005033 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5034 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 mActive(false), mSourceThread(sourceThread)
5036{
5037
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 if (mCblk != NULL) {
5039 mCblk->flags |= CBLK_DIRECTION_OUT;
5040 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 mOutBuffer.frameCount = 0;
5042 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005043 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005044 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5045 mCblk, mBuffer, mCblk->buffers,
5046 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005048 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 }
5050}
5051
5052AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5053{
5054 clearBufferQueue();
5055}
5056
Glenn Kasten3acbd052012-02-28 10:39:56 -08005057status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005058 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005060 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 if (status != NO_ERROR) {
5062 return status;
5063 }
5064
5065 mActive = true;
5066 mRetryCount = 127;
5067 return status;
5068}
5069
5070void AudioFlinger::PlaybackThread::OutputTrack::stop()
5071{
5072 Track::stop();
5073 clearBufferQueue();
5074 mOutBuffer.frameCount = 0;
5075 mActive = false;
5076}
5077
5078bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5079{
5080 Buffer *pInBuffer;
5081 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005082 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 bool outputBufferFull = false;
5084 inBuffer.frameCount = frames;
5085 inBuffer.i16 = data;
5086
5087 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5088
5089 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005090 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 sp<ThreadBase> thread = mThread.promote();
5092 if (thread != 0) {
5093 MixerThread *mixerThread = (MixerThread *)thread.get();
5094 if (mCblk->frameCount > frames){
5095 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5096 uint32_t startFrames = (mCblk->frameCount - frames);
5097 pInBuffer = new Buffer;
5098 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5099 pInBuffer->frameCount = startFrames;
5100 pInBuffer->i16 = pInBuffer->mBuffer;
5101 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5102 mBufferQueue.add(pInBuffer);
5103 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005104 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 }
5106 }
5107 }
5108 }
5109
5110 while (waitTimeLeftMs) {
5111 // First write pending buffers, then new data
5112 if (mBufferQueue.size()) {
5113 pInBuffer = mBufferQueue.itemAt(0);
5114 } else {
5115 pInBuffer = &inBuffer;
5116 }
5117
5118 if (pInBuffer->frameCount == 0) {
5119 break;
5120 }
5121
5122 if (mOutBuffer.frameCount == 0) {
5123 mOutBuffer.frameCount = pInBuffer->frameCount;
5124 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005125 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005126 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 outputBufferFull = true;
5128 break;
5129 }
5130 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5131 if (waitTimeLeftMs >= waitTimeMs) {
5132 waitTimeLeftMs -= waitTimeMs;
5133 } else {
5134 waitTimeLeftMs = 0;
5135 }
5136 }
5137
5138 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5139 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5140 mCblk->stepUser(outFrames);
5141 pInBuffer->frameCount -= outFrames;
5142 pInBuffer->i16 += outFrames * channelCount;
5143 mOutBuffer.frameCount -= outFrames;
5144 mOutBuffer.i16 += outFrames * channelCount;
5145
5146 if (pInBuffer->frameCount == 0) {
5147 if (mBufferQueue.size()) {
5148 mBufferQueue.removeAt(0);
5149 delete [] pInBuffer->mBuffer;
5150 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005151 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152 } else {
5153 break;
5154 }
5155 }
5156 }
5157
5158 // If we could not write all frames, allocate a buffer and queue it for next time.
5159 if (inBuffer.frameCount) {
5160 sp<ThreadBase> thread = mThread.promote();
5161 if (thread != 0 && !thread->standby()) {
5162 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5163 pInBuffer = new Buffer;
5164 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5165 pInBuffer->frameCount = inBuffer.frameCount;
5166 pInBuffer->i16 = pInBuffer->mBuffer;
5167 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5168 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005169 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005171 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 }
5173 }
5174 }
5175
5176 // Calling write() with a 0 length buffer, means that no more data will be written:
5177 // If no more buffers are pending, fill output track buffer to make sure it is started
5178 // by output mixer.
5179 if (frames == 0 && mBufferQueue.size() == 0) {
5180 if (mCblk->user < mCblk->frameCount) {
5181 frames = mCblk->frameCount - mCblk->user;
5182 pInBuffer = new Buffer;
5183 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5184 pInBuffer->frameCount = frames;
5185 pInBuffer->i16 = pInBuffer->mBuffer;
5186 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5187 mBufferQueue.add(pInBuffer);
5188 } else if (mActive) {
5189 stop();
5190 }
5191 }
5192
5193 return outputBufferFull;
5194}
5195
5196status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5197{
5198 int active;
5199 status_t result;
5200 audio_track_cblk_t* cblk = mCblk;
5201 uint32_t framesReq = buffer->frameCount;
5202
Steve Block3856b092011-10-20 11:56:00 +01005203// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005204 buffer->frameCount = 0;
5205
5206 uint32_t framesAvail = cblk->framesAvailable();
5207
5208
5209 if (framesAvail == 0) {
5210 Mutex::Autolock _l(cblk->lock);
5211 goto start_loop_here;
5212 while (framesAvail == 0) {
5213 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005214 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005215 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005216 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 }
5218 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5219 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005220 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221 }
5222 // read the server count again
5223 start_loop_here:
5224 framesAvail = cblk->framesAvailable_l();
5225 }
5226 }
5227
5228// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005229// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230// }
5231
5232 if (framesReq > framesAvail) {
5233 framesReq = framesAvail;
5234 }
5235
5236 uint32_t u = cblk->user;
5237 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5238
Marco Nelissena1472d92012-03-30 14:36:54 -07005239 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005240 framesReq = bufferEnd - u;
5241 }
5242
5243 buffer->frameCount = framesReq;
5244 buffer->raw = (void *)cblk->buffer(u);
5245 return NO_ERROR;
5246}
5247
5248
5249void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5250{
5251 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252
5253 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005254 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005255 delete [] pBuffer->mBuffer;
5256 delete pBuffer;
5257 }
5258 mBufferQueue.clear();
5259}
5260
5261// ----------------------------------------------------------------------------
5262
5263AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5264 : RefBase(),
5265 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005266 // 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 -07005267 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 mPid(pid),
5269 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005270{
5271 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5272}
5273
5274// Client destructor must be called with AudioFlinger::mLock held
5275AudioFlinger::Client::~Client()
5276{
5277 mAudioFlinger->removeClient_l(mPid);
5278}
5279
Glenn Kasten435dbe62012-01-30 10:15:48 -08005280sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281{
5282 return mMemoryDealer;
5283}
5284
John Grossman4ff14ba2012-02-08 16:37:41 -08005285// Reserve one of the limited slots for a timed audio track associated
5286// with this client
5287bool AudioFlinger::Client::reserveTimedTrack()
5288{
5289 const int kMaxTimedTracksPerClient = 4;
5290
5291 Mutex::Autolock _l(mTimedTrackLock);
5292
5293 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5294 ALOGW("can not create timed track - pid %d has exceeded the limit",
5295 mPid);
5296 return false;
5297 }
5298
5299 mTimedTrackCount++;
5300 return true;
5301}
5302
5303// Release a slot for a timed audio track
5304void AudioFlinger::Client::releaseTimedTrack()
5305{
5306 Mutex::Autolock _l(mTimedTrackLock);
5307 mTimedTrackCount--;
5308}
5309
Mathias Agopian65ab4712010-07-14 17:59:35 -07005310// ----------------------------------------------------------------------------
5311
5312AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5313 const sp<IAudioFlingerClient>& client,
5314 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005315 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316{
5317}
5318
5319AudioFlinger::NotificationClient::~NotificationClient()
5320{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321}
5322
5323void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5324{
5325 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005326 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327}
5328
5329// ----------------------------------------------------------------------------
5330
5331AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5332 : BnAudioTrack(),
5333 mTrack(track)
5334{
5335}
5336
5337AudioFlinger::TrackHandle::~TrackHandle() {
5338 // just stop the track on deletion, associated resources
5339 // will be freed from the main thread once all pending buffers have
5340 // been played. Unless it's not in the active track list, in which
5341 // case we free everything now...
5342 mTrack->destroy();
5343}
5344
Glenn Kasten90716c52012-01-26 13:40:12 -08005345sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5346 return mTrack->getCblk();
5347}
5348
Glenn Kasten3acbd052012-02-28 10:39:56 -08005349status_t AudioFlinger::TrackHandle::start() {
5350 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351}
5352
5353void AudioFlinger::TrackHandle::stop() {
5354 mTrack->stop();
5355}
5356
5357void AudioFlinger::TrackHandle::flush() {
5358 mTrack->flush();
5359}
5360
5361void AudioFlinger::TrackHandle::mute(bool e) {
5362 mTrack->mute(e);
5363}
5364
5365void AudioFlinger::TrackHandle::pause() {
5366 mTrack->pause();
5367}
5368
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5370{
5371 return mTrack->attachAuxEffect(EffectId);
5372}
5373
John Grossman4ff14ba2012-02-08 16:37:41 -08005374status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5375 sp<IMemory>* buffer) {
5376 if (!mTrack->isTimedTrack())
5377 return INVALID_OPERATION;
5378
5379 PlaybackThread::TimedTrack* tt =
5380 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5381 return tt->allocateTimedBuffer(size, buffer);
5382}
5383
5384status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5385 int64_t pts) {
5386 if (!mTrack->isTimedTrack())
5387 return INVALID_OPERATION;
5388
5389 PlaybackThread::TimedTrack* tt =
5390 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5391 return tt->queueTimedBuffer(buffer, pts);
5392}
5393
5394status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5395 const LinearTransform& xform, int target) {
5396
5397 if (!mTrack->isTimedTrack())
5398 return INVALID_OPERATION;
5399
5400 PlaybackThread::TimedTrack* tt =
5401 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5402 return tt->setMediaTimeTransform(
5403 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5404}
5405
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406status_t AudioFlinger::TrackHandle::onTransact(
5407 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5408{
5409 return BnAudioTrack::onTransact(code, data, reply, flags);
5410}
5411
5412// ----------------------------------------------------------------------------
5413
5414sp<IAudioRecord> AudioFlinger::openRecord(
5415 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005416 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005418 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005419 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005421 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 int *sessionId,
5423 status_t *status)
5424{
5425 sp<RecordThread::RecordTrack> recordTrack;
5426 sp<RecordHandle> recordHandle;
5427 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 status_t lStatus;
5429 RecordThread *thread;
5430 size_t inFrameCount;
5431 int lSessionId;
5432
5433 // check calling permissions
5434 if (!recordingAllowed()) {
5435 lStatus = PERMISSION_DENIED;
5436 goto Exit;
5437 }
5438
5439 // add client to list
5440 { // scope for mLock
5441 Mutex::Autolock _l(mLock);
5442 thread = checkRecordThread_l(input);
5443 if (thread == NULL) {
5444 lStatus = BAD_VALUE;
5445 goto Exit;
5446 }
5447
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005448 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449
5450 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005451 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 lSessionId = *sessionId;
5453 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005454 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 if (sessionId != NULL) {
5456 *sessionId = lSessionId;
5457 }
5458 }
5459 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005460 recordTrack = thread->createRecordTrack_l(client,
5461 sampleRate,
5462 format,
5463 channelMask,
5464 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005465 lSessionId,
5466 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005468 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5470 // destructor is called by the TrackBase destructor with mLock held
5471 client.clear();
5472 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 goto Exit;
5474 }
5475
5476 // return to handle to client
5477 recordHandle = new RecordHandle(recordTrack);
5478 lStatus = NO_ERROR;
5479
5480Exit:
5481 if (status) {
5482 *status = lStatus;
5483 }
5484 return recordHandle;
5485}
5486
5487// ----------------------------------------------------------------------------
5488
5489AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5490 : BnAudioRecord(),
5491 mRecordTrack(recordTrack)
5492{
5493}
5494
5495AudioFlinger::RecordHandle::~RecordHandle() {
5496 stop();
5497}
5498
Glenn Kasten90716c52012-01-26 13:40:12 -08005499sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5500 return mRecordTrack->getCblk();
5501}
5502
Glenn Kasten3acbd052012-02-28 10:39:56 -08005503status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005504 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005505 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506}
5507
5508void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005509 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 mRecordTrack->stop();
5511}
5512
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513status_t AudioFlinger::RecordHandle::onTransact(
5514 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5515{
5516 return BnAudioRecord::onTransact(code, data, reply, flags);
5517}
5518
5519// ----------------------------------------------------------------------------
5520
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005521AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5522 AudioStreamIn *input,
5523 uint32_t sampleRate,
5524 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005525 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005526 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005527 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005528 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5529 // mRsmpInIndex and mInputBytes set by readInputParameters()
5530 mReqChannelCount(popcount(channels)),
5531 mReqSampleRate(sampleRate)
5532 // mBytesRead is only meaningful while active, and so is cleared in start()
5533 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534{
Glenn Kasten480b4682012-02-28 12:30:08 -08005535 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005536
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 readInputParameters();
5538}
5539
5540
5541AudioFlinger::RecordThread::~RecordThread()
5542{
5543 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005544 delete mResampler;
5545 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546}
5547
5548void AudioFlinger::RecordThread::onFirstRef()
5549{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005550 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551}
5552
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005553status_t AudioFlinger::RecordThread::readyToRun()
5554{
5555 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005556 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005557 return status;
5558}
5559
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560bool AudioFlinger::RecordThread::threadLoop()
5561{
5562 AudioBufferProvider::Buffer buffer;
5563 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005564 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565
Eric Laurent44d98482010-09-30 16:12:31 -07005566 nsecs_t lastWarning = 0;
5567
Eric Laurentfeb0db62011-07-22 09:04:31 -07005568 acquireWakeLock();
5569
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570 // start recording
5571 while (!exitPending()) {
5572
5573 processConfigEvents();
5574
5575 { // scope for mLock
5576 Mutex::Autolock _l(mLock);
5577 checkForNewParameters_l();
5578 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5579 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005580 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 mStandby = true;
5582 }
5583
5584 if (exitPending()) break;
5585
Eric Laurentfeb0db62011-07-22 09:04:31 -07005586 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005587 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588 // go to sleep
5589 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005590 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005591 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 continue;
5593 }
5594 if (mActiveTrack != 0) {
5595 if (mActiveTrack->mState == TrackBase::PAUSING) {
5596 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005597 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 mStandby = true;
5599 }
5600 mActiveTrack.clear();
5601 mStartStopCond.broadcast();
5602 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5603 if (mReqChannelCount != mActiveTrack->channelCount()) {
5604 mActiveTrack.clear();
5605 mStartStopCond.broadcast();
5606 } else if (mBytesRead != 0) {
5607 // record start succeeds only if first read from audio input
5608 // succeeds
5609 if (mBytesRead > 0) {
5610 mActiveTrack->mState = TrackBase::ACTIVE;
5611 } else {
5612 mActiveTrack.clear();
5613 }
5614 mStartStopCond.broadcast();
5615 }
5616 mStandby = false;
5617 }
5618 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005619 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 }
5621
5622 if (mActiveTrack != 0) {
5623 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5624 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005625 unlockEffectChains(effectChains);
5626 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 continue;
5628 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005629 for (size_t i = 0; i < effectChains.size(); i ++) {
5630 effectChains[i]->process_l();
5631 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005632
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005634 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005636 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637 // no resampling
5638 while (framesOut) {
5639 size_t framesIn = mFrameCount - mRsmpInIndex;
5640 if (framesIn) {
5641 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5642 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5643 if (framesIn > framesOut)
5644 framesIn = framesOut;
5645 mRsmpInIndex += framesIn;
5646 framesOut -= framesIn;
5647 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005648 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 memcpy(dst, src, framesIn * mFrameSize);
5650 } else {
5651 int16_t *src16 = (int16_t *)src;
5652 int16_t *dst16 = (int16_t *)dst;
5653 if (mChannelCount == 1) {
5654 while (framesIn--) {
5655 *dst16++ = *src16;
5656 *dst16++ = *src16++;
5657 }
5658 } else {
5659 while (framesIn--) {
5660 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5661 src16 += 2;
5662 }
5663 }
5664 }
5665 }
5666 if (framesOut && mFrameCount == mRsmpInIndex) {
5667 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005668 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005669 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005670 framesOut = 0;
5671 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005672 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673 mRsmpInIndex = 0;
5674 }
5675 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005676 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5678 // Force input into standby so that it tries to
5679 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005680 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005681 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 }
5683 mRsmpInIndex = mFrameCount;
5684 framesOut = 0;
5685 buffer.frameCount = 0;
5686 }
5687 }
5688 }
5689 } else {
5690 // resampling
5691
5692 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5693 // alter output frame count as if we were expecting stereo samples
5694 if (mChannelCount == 1 && mReqChannelCount == 1) {
5695 framesOut >>= 1;
5696 }
5697 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5698 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5699 // are 32 bit aligned which should be always true.
5700 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005701 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 // the resampler always outputs stereo samples: do post stereo to mono conversion
5703 int16_t *src = (int16_t *)mRsmpOutBuffer;
5704 int16_t *dst = buffer.i16;
5705 while (framesOut--) {
5706 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5707 src += 2;
5708 }
5709 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005710 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 }
5712
5713 }
Eric Laurenta011e352012-03-29 15:51:43 -07005714 if (mFramestoDrop == 0) {
5715 mActiveTrack->releaseBuffer(&buffer);
5716 } else {
5717 if (mFramestoDrop > 0) {
5718 mFramestoDrop -= buffer.frameCount;
5719 if (mFramestoDrop < 0) {
5720 mFramestoDrop = 0;
5721 }
5722 }
5723 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 mActiveTrack->overflow();
5725 }
5726 // client isn't retrieving buffers fast enough
5727 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005728 if (!mActiveTrack->setOverflow()) {
5729 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005730 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005731 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005732 lastWarning = now;
5733 }
5734 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735 // Release the processor for a while before asking for a new buffer.
5736 // This will give the application more chance to read from the buffer and
5737 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005738 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 }
5740 }
Eric Laurentec437d82011-07-26 20:54:46 -07005741 // enable changes in effect chain
5742 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005743 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744 }
5745
5746 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005747 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 }
5749 mActiveTrack.clear();
5750
5751 mStartStopCond.broadcast();
5752
Eric Laurentfeb0db62011-07-22 09:04:31 -07005753 releaseWakeLock();
5754
Steve Block3856b092011-10-20 11:56:00 +01005755 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 return false;
5757}
5758
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005759
5760sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5761 const sp<AudioFlinger::Client>& client,
5762 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005763 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005764 int channelMask,
5765 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005766 int sessionId,
5767 status_t *status)
5768{
5769 sp<RecordTrack> track;
5770 status_t lStatus;
5771
5772 lStatus = initCheck();
5773 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005774 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005775 goto Exit;
5776 }
5777
5778 { // scope for mLock
5779 Mutex::Autolock _l(mLock);
5780
5781 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005782 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005783
Glenn Kasten7378ca52012-01-20 13:44:40 -08005784 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005785 lStatus = NO_MEMORY;
5786 goto Exit;
5787 }
5788
5789 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005790 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5791 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005792 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005793 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5794 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005795 }
5796 lStatus = NO_ERROR;
5797
5798Exit:
5799 if (status) {
5800 *status = lStatus;
5801 }
5802 return track;
5803}
5804
Eric Laurenta011e352012-03-29 15:51:43 -07005805status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005806 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005807 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808{
Glenn Kasten58912562012-04-03 10:45:00 -07005809 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005810 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005812
5813 if (event == AudioSystem::SYNC_EVENT_NONE) {
5814 mSyncStartEvent.clear();
5815 mFramestoDrop = 0;
5816 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5817 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5818 triggerSession,
5819 recordTrack->sessionId(),
5820 syncStartEventCallback,
5821 this);
5822 mFramestoDrop = -1;
5823 }
5824
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005826 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 if (mActiveTrack != 0) {
5828 if (recordTrack != mActiveTrack.get()) {
5829 status = -EBUSY;
5830 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5831 mActiveTrack->mState = TrackBase::ACTIVE;
5832 }
5833 return status;
5834 }
5835
5836 recordTrack->mState = TrackBase::IDLE;
5837 mActiveTrack = recordTrack;
5838 mLock.unlock();
5839 status_t status = AudioSystem::startInput(mId);
5840 mLock.lock();
5841 if (status != NO_ERROR) {
5842 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005843 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844 return status;
5845 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846 mRsmpInIndex = mFrameCount;
5847 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005848 if (mResampler != NULL) {
5849 mResampler->reset();
5850 }
5851 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005853 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854 mWaitWorkCV.signal();
5855 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005856 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 mActiveTrack.clear();
5858 status = INVALID_OPERATION;
5859 goto startError;
5860 }
5861 mStartStopCond.wait(mLock);
5862 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005863 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 status = BAD_VALUE;
5865 goto startError;
5866 }
Steve Block3856b092011-10-20 11:56:00 +01005867 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 return status;
5869 }
5870startError:
5871 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005872 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 return status;
5874}
5875
Eric Laurenta011e352012-03-29 15:51:43 -07005876void AudioFlinger::RecordThread::clearSyncStartEvent()
5877{
5878 if (mSyncStartEvent != 0) {
5879 mSyncStartEvent->cancel();
5880 }
5881 mSyncStartEvent.clear();
5882}
5883
5884void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5885{
5886 sp<SyncEvent> strongEvent = event.promote();
5887
5888 if (strongEvent != 0) {
5889 RecordThread *me = (RecordThread *)strongEvent->cookie();
5890 me->handleSyncStartEvent(strongEvent);
5891 }
5892}
5893
5894void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5895{
5896 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5897 mActiveTrack.get(),
5898 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5899 event->listenerSession());
5900
5901 if (mActiveTrack != 0 &&
5902 event == mSyncStartEvent) {
5903 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5904 // from audio HAL
5905 mFramestoDrop = mFrameCount * 2;
5906 mSyncStartEvent.clear();
5907 }
5908}
5909
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005911 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005912 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005914 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5916 mActiveTrack->mState = TrackBase::PAUSING;
5917 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005918 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919 return;
5920 }
5921 mStartStopCond.wait(mLock);
5922 // if we have been restarted, recordTrack == mActiveTrack.get() here
5923 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5924 mLock.unlock();
5925 AudioSystem::stopInput(mId);
5926 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005927 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 }
5929 }
5930 }
5931}
5932
Eric Laurenta011e352012-03-29 15:51:43 -07005933bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5934{
5935 return false;
5936}
5937
5938status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5939{
5940 if (!isValidSyncEvent(event)) {
5941 return BAD_VALUE;
5942 }
5943
5944 Mutex::Autolock _l(mLock);
5945
5946 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5947 mTrack->setSyncEvent(event);
5948 return NO_ERROR;
5949 }
5950 return NAME_NOT_FOUND;
5951}
5952
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5954{
5955 const size_t SIZE = 256;
5956 char buffer[SIZE];
5957 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958
5959 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5960 result.append(buffer);
5961
5962 if (mActiveTrack != 0) {
5963 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005964 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 mActiveTrack->dump(buffer, SIZE);
5966 result.append(buffer);
5967
5968 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5969 result.append(buffer);
5970 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5971 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005972 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973 result.append(buffer);
5974 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5975 result.append(buffer);
5976 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5977 result.append(buffer);
5978
5979
5980 } else {
5981 result.append("No record client\n");
5982 }
5983 write(fd, result.string(), result.size());
5984
5985 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005986 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987
5988 return NO_ERROR;
5989}
5990
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005991// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005992status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993{
5994 size_t framesReq = buffer->frameCount;
5995 size_t framesReady = mFrameCount - mRsmpInIndex;
5996 int channelCount;
5997
5998 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005999 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006001 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6003 // Force input into standby so that it tries to
6004 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006005 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006006 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006008 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 buffer->frameCount = 0;
6010 return NOT_ENOUGH_DATA;
6011 }
6012 mRsmpInIndex = 0;
6013 framesReady = mFrameCount;
6014 }
6015
6016 if (framesReq > framesReady) {
6017 framesReq = framesReady;
6018 }
6019
6020 if (mChannelCount == 1 && mReqChannelCount == 2) {
6021 channelCount = 1;
6022 } else {
6023 channelCount = 2;
6024 }
6025 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6026 buffer->frameCount = framesReq;
6027 return NO_ERROR;
6028}
6029
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006030// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6032{
6033 mRsmpInIndex += buffer->frameCount;
6034 buffer->frameCount = 0;
6035}
6036
6037bool AudioFlinger::RecordThread::checkForNewParameters_l()
6038{
6039 bool reconfig = false;
6040
6041 while (!mNewParameters.isEmpty()) {
6042 status_t status = NO_ERROR;
6043 String8 keyValuePair = mNewParameters[0];
6044 AudioParameter param = AudioParameter(keyValuePair);
6045 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006046 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 int reqSamplingRate = mReqSampleRate;
6048 int reqChannelCount = mReqChannelCount;
6049
6050 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6051 reqSamplingRate = value;
6052 reconfig = true;
6053 }
6054 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006055 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 reconfig = true;
6057 }
6058 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006059 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 reconfig = true;
6061 }
6062 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6063 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006064 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065 // if frame count is changed after track creation
6066 if (mActiveTrack != 0) {
6067 status = INVALID_OPERATION;
6068 } else {
6069 reconfig = true;
6070 }
6071 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006072 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6073 // forward device change to effects that have requested to be
6074 // aware of attached audio device.
6075 for (size_t i = 0; i < mEffectChains.size(); i++) {
6076 mEffectChains[i]->setDevice_l(value);
6077 }
6078 // store input device and output device but do not forward output device to audio HAL.
6079 // Note that status is ignored by the caller for output device
6080 // (see AudioFlinger::setParameters()
6081 if (value & AUDIO_DEVICE_OUT_ALL) {
6082 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6083 status = BAD_VALUE;
6084 } else {
6085 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006086 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6087 if (mTrack != NULL) {
6088 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006089 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006090 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6091 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6092 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006093 }
6094 mDevice |= (uint32_t)value;
6095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006097 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006099 mInput->stream->common.standby(&mInput->stream->common);
6100 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6101 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 }
6103 if (reconfig) {
6104 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006105 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006106 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006107 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006108 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6109 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110 status = NO_ERROR;
6111 }
6112 if (status == NO_ERROR) {
6113 readInputParameters();
6114 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6115 }
6116 }
6117 }
6118
6119 mNewParameters.removeAt(0);
6120
6121 mParamStatus = status;
6122 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006123 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6124 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006125 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 }
6127 return reconfig;
6128}
6129
6130String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6131{
Dima Zavinfce7a472011-04-19 22:30:36 -07006132 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006133 String8 out_s8 = String8();
6134
6135 Mutex::Autolock _l(mLock);
6136 if (initCheck() != NO_ERROR) {
6137 return out_s8;
6138 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006139
Dima Zavin799a70e2011-04-18 16:57:27 -07006140 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006141 out_s8 = String8(s);
6142 free(s);
6143 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144}
6145
6146void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6147 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006148 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149
6150 switch (event) {
6151 case AudioSystem::INPUT_OPENED:
6152 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006153 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 desc.samplingRate = mSampleRate;
6155 desc.format = mFormat;
6156 desc.frameCount = mFrameCount;
6157 desc.latency = 0;
6158 param2 = &desc;
6159 break;
6160
6161 case AudioSystem::INPUT_CLOSED:
6162 default:
6163 break;
6164 }
6165 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6166}
6167
6168void AudioFlinger::RecordThread::readInputParameters()
6169{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006170 delete mRsmpInBuffer;
6171 // mRsmpInBuffer is always assigned a new[] below
6172 delete mRsmpOutBuffer;
6173 mRsmpOutBuffer = NULL;
6174 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006175 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176
Dima Zavin799a70e2011-04-18 16:57:27 -07006177 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006178 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6179 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006180 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006181 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006182 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006184 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6186
Glenn Kasten53d76db2012-03-08 12:32:47 -08006187 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 {
6189 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006190 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6191 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 if (mChannelCount == 1 && mReqChannelCount == 2) {
6193 channelCount = 1;
6194 } else {
6195 channelCount = 2;
6196 }
6197 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6198 mResampler->setSampleRate(mSampleRate);
6199 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6200 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6201
6202 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6203 if (mChannelCount == 1 && mReqChannelCount == 1) {
6204 mFrameCount >>= 1;
6205 }
6206
6207 }
6208 mRsmpInIndex = mFrameCount;
6209}
6210
6211unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6212{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006213 Mutex::Autolock _l(mLock);
6214 if (initCheck() != NO_ERROR) {
6215 return 0;
6216 }
6217
Dima Zavin799a70e2011-04-18 16:57:27 -07006218 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219}
6220
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6222{
6223 Mutex::Autolock _l(mLock);
6224 uint32_t result = 0;
6225 if (getEffectChain_l(sessionId) != 0) {
6226 result = EFFECT_SESSION;
6227 }
6228
6229 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6230 result |= TRACK_SESSION;
6231 }
6232
6233 return result;
6234}
6235
Eric Laurent59bd0da2011-08-01 09:52:20 -07006236AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6237{
6238 Mutex::Autolock _l(mLock);
6239 return mTrack;
6240}
6241
Glenn Kastenaed850d2012-01-26 09:46:34 -08006242AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006243{
6244 Mutex::Autolock _l(mLock);
6245 return mInput;
6246}
6247
6248AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6249{
6250 Mutex::Autolock _l(mLock);
6251 AudioStreamIn *input = mInput;
6252 mInput = NULL;
6253 return input;
6254}
6255
6256// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006257audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006258{
6259 if (mInput == NULL) {
6260 return NULL;
6261 }
6262 return &mInput->stream->common;
6263}
6264
6265
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266// ----------------------------------------------------------------------------
6267
Eric Laurenta4c5a552012-03-29 10:12:40 -07006268audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6269{
6270 if (!settingsAllowed()) {
6271 return 0;
6272 }
6273 Mutex::Autolock _l(mLock);
6274 return loadHwModule_l(name);
6275}
6276
6277// loadHwModule_l() must be called with AudioFlinger::mLock held
6278audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6279{
6280 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6281 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6282 ALOGW("loadHwModule() module %s already loaded", name);
6283 return mAudioHwDevs.keyAt(i);
6284 }
6285 }
6286
Eric Laurenta4c5a552012-03-29 10:12:40 -07006287 audio_hw_device_t *dev;
6288
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006289 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006290 if (rc) {
6291 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6292 return 0;
6293 }
6294
6295 mHardwareStatus = AUDIO_HW_INIT;
6296 rc = dev->init_check(dev);
6297 mHardwareStatus = AUDIO_HW_IDLE;
6298 if (rc) {
6299 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6300 return 0;
6301 }
6302
6303 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6304 (NULL != dev->set_master_volume)) {
6305 AutoMutex lock(mHardwareLock);
6306 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6307 dev->set_master_volume(dev, mMasterVolume);
6308 mHardwareStatus = AUDIO_HW_IDLE;
6309 }
6310
6311 audio_module_handle_t handle = nextUniqueId();
6312 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6313
6314 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006315 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006316
6317 return handle;
6318
6319}
6320
6321audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6322 audio_devices_t *pDevices,
6323 uint32_t *pSamplingRate,
6324 audio_format_t *pFormat,
6325 audio_channel_mask_t *pChannelMask,
6326 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006327 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328{
6329 status_t status;
6330 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006331 struct audio_config config = {
6332 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6333 channel_mask: pChannelMask ? *pChannelMask : 0,
6334 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6335 };
6336 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006337 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338
Eric Laurenta4c5a552012-03-29 10:12:40 -07006339 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6340 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006341 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006342 config.sample_rate,
6343 config.format,
6344 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006345 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346
6347 if (pDevices == NULL || *pDevices == 0) {
6348 return 0;
6349 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006350
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351 Mutex::Autolock _l(mLock);
6352
Eric Laurenta4c5a552012-03-29 10:12:40 -07006353 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006354 if (outHwDev == NULL)
6355 return 0;
6356
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006357 audio_io_handle_t id = nextUniqueId();
6358
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006359 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006360
6361 status = outHwDev->open_output_stream(outHwDev,
6362 id,
6363 *pDevices,
6364 (audio_output_flags_t)flags,
6365 &config,
6366 &outStream);
6367
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006368 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006369 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006370 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006371 config.sample_rate,
6372 config.format,
6373 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 status);
6375
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006376 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006377 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006378
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006379 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006380 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6381 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006383 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006384 } else {
6385 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006386 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 }
6388 mPlaybackThreads.add(id, thread);
6389
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006390 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6391 if (pFormat != NULL) *pFormat = config.format;
6392 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006393 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394
6395 // notify client processes of the new output creation
6396 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006397
6398 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006399 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006400 ALOGI("Using module %d has the primary audio interface", module);
6401 mPrimaryHardwareDev = outHwDev;
6402
6403 AutoMutex lock(mHardwareLock);
6404 mHardwareStatus = AUDIO_HW_SET_MODE;
6405 outHwDev->set_mode(outHwDev, mMode);
6406
6407 // Determine the level of master volume support the primary audio HAL has,
6408 // and set the initial master volume at the same time.
6409 float initialVolume = 1.0;
6410 mMasterVolumeSupportLvl = MVS_NONE;
6411
6412 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6413 if ((NULL != outHwDev->get_master_volume) &&
6414 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6415 mMasterVolumeSupportLvl = MVS_FULL;
6416 } else {
6417 mMasterVolumeSupportLvl = MVS_SETONLY;
6418 initialVolume = 1.0;
6419 }
6420
6421 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6422 if ((NULL == outHwDev->set_master_volume) ||
6423 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6424 mMasterVolumeSupportLvl = MVS_NONE;
6425 }
6426 // now that we have a primary device, initialize master volume on other devices
6427 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6428 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6429
6430 if ((dev != mPrimaryHardwareDev) &&
6431 (NULL != dev->set_master_volume)) {
6432 dev->set_master_volume(dev, initialVolume);
6433 }
6434 }
6435 mHardwareStatus = AUDIO_HW_IDLE;
6436 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6437 ? initialVolume
6438 : 1.0;
6439 mMasterVolume = initialVolume;
6440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 return id;
6442 }
6443
6444 return 0;
6445}
6446
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006447audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6448 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449{
6450 Mutex::Autolock _l(mLock);
6451 MixerThread *thread1 = checkMixerThread_l(output1);
6452 MixerThread *thread2 = checkMixerThread_l(output2);
6453
6454 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006455 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456 return 0;
6457 }
6458
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006459 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6461 thread->addOutputTrack(thread2);
6462 mPlaybackThreads.add(id, thread);
6463 // notify client processes of the new output creation
6464 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6465 return id;
6466}
6467
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006468status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469{
6470 // keep strong reference on the playback thread so that
6471 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006472 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006473 {
6474 Mutex::Autolock _l(mLock);
6475 thread = checkPlaybackThread_l(output);
6476 if (thread == NULL) {
6477 return BAD_VALUE;
6478 }
6479
Steve Block3856b092011-10-20 11:56:00 +01006480 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006482 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006484 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6486 dupThread->removeOutputTrack((MixerThread *)thread.get());
6487 }
6488 }
6489 }
Glenn Kastena1117922012-01-26 10:53:32 -08006490 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 mPlaybackThreads.removeItem(output);
6492 }
6493 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006494 // The thread entity (active unit of execution) is no longer running here,
6495 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006497 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006498 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006499 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006500 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006501 out->hwDev->close_output_stream(out->hwDev, out->stream);
6502 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 }
6504 return NO_ERROR;
6505}
6506
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006507status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508{
6509 Mutex::Autolock _l(mLock);
6510 PlaybackThread *thread = checkPlaybackThread_l(output);
6511
6512 if (thread == NULL) {
6513 return BAD_VALUE;
6514 }
6515
Steve Block3856b092011-10-20 11:56:00 +01006516 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 thread->suspend();
6518
6519 return NO_ERROR;
6520}
6521
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006522status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523{
6524 Mutex::Autolock _l(mLock);
6525 PlaybackThread *thread = checkPlaybackThread_l(output);
6526
6527 if (thread == NULL) {
6528 return BAD_VALUE;
6529 }
6530
Steve Block3856b092011-10-20 11:56:00 +01006531 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532
6533 thread->restore();
6534
6535 return NO_ERROR;
6536}
6537
Eric Laurenta4c5a552012-03-29 10:12:40 -07006538audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6539 audio_devices_t *pDevices,
6540 uint32_t *pSamplingRate,
6541 audio_format_t *pFormat,
6542 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543{
6544 status_t status;
6545 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006546 struct audio_config config = {
6547 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6548 channel_mask: pChannelMask ? *pChannelMask : 0,
6549 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6550 };
6551 uint32_t reqSamplingRate = config.sample_rate;
6552 audio_format_t reqFormat = config.format;
6553 audio_channel_mask_t reqChannels = config.channel_mask;
6554 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006555 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556
6557 if (pDevices == NULL || *pDevices == 0) {
6558 return 0;
6559 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006560
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561 Mutex::Autolock _l(mLock);
6562
Eric Laurenta4c5a552012-03-29 10:12:40 -07006563 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006564 if (inHwDev == NULL)
6565 return 0;
6566
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006567 audio_io_handle_t id = nextUniqueId();
6568
6569 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006570 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006571 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006572 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006573 config.sample_rate,
6574 config.format,
6575 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 status);
6577
6578 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6579 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6580 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006581 if (status == BAD_VALUE &&
6582 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6583 (config.sample_rate <= 2 * reqSamplingRate) &&
6584 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006585 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006586 inStream = NULL;
6587 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588 }
6589
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006590 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006591 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6592
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006593 // Start record thread
6594 // RecorThread require both input and output device indication to forward to audio
6595 // pre processing modules
6596 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6597 thread = new RecordThread(this,
6598 input,
6599 reqSamplingRate,
6600 reqChannels,
6601 id,
6602 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006604 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006605 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006606 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006607 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608
Dima Zavin799a70e2011-04-18 16:57:27 -07006609 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610
6611 // notify client processes of the new input creation
6612 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6613 return id;
6614 }
6615
6616 return 0;
6617}
6618
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006619status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620{
6621 // keep strong reference on the record thread so that
6622 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006623 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 {
6625 Mutex::Autolock _l(mLock);
6626 thread = checkRecordThread_l(input);
6627 if (thread == NULL) {
6628 return BAD_VALUE;
6629 }
6630
Steve Block3856b092011-10-20 11:56:00 +01006631 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006632 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633 mRecordThreads.removeItem(input);
6634 }
6635 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006636 // The thread entity (active unit of execution) is no longer running here,
6637 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006639 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006640 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006641 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006642 in->hwDev->close_input_stream(in->hwDev, in->stream);
6643 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644
6645 return NO_ERROR;
6646}
6647
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006648status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649{
6650 Mutex::Autolock _l(mLock);
6651 MixerThread *dstThread = checkMixerThread_l(output);
6652 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006653 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 return BAD_VALUE;
6655 }
6656
Steve Block3856b092011-10-20 11:56:00 +01006657 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6659
6660 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6661 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006662 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663 MixerThread *srcThread = (MixerThread *)thread;
6664 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 }
Eric Laurentde070132010-07-13 04:45:46 -07006666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667
6668 return NO_ERROR;
6669}
6670
6671
6672int AudioFlinger::newAudioSessionId()
6673{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006674 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675}
6676
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006677void AudioFlinger::acquireAudioSessionId(int audioSession)
6678{
6679 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006680 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006681 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006682 size_t num = mAudioSessionRefs.size();
6683 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006684 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006685 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6686 ref->mCnt++;
6687 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006688 return;
6689 }
6690 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006691 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6692 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006693}
6694
6695void AudioFlinger::releaseAudioSessionId(int audioSession)
6696{
6697 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006698 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006699 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006700 size_t num = mAudioSessionRefs.size();
6701 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006702 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006703 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6704 ref->mCnt--;
6705 ALOGV(" decremented refcount to %d", ref->mCnt);
6706 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006707 mAudioSessionRefs.removeAt(i);
6708 delete ref;
6709 purgeStaleEffects_l();
6710 }
6711 return;
6712 }
6713 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006714 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006715}
6716
6717void AudioFlinger::purgeStaleEffects_l() {
6718
Steve Block3856b092011-10-20 11:56:00 +01006719 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006720
6721 Vector< sp<EffectChain> > chains;
6722
6723 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6724 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6725 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6726 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006727 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6728 chains.push(ec);
6729 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006730 }
6731 }
6732 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6733 sp<RecordThread> t = mRecordThreads.valueAt(i);
6734 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6735 sp<EffectChain> ec = t->mEffectChains[j];
6736 chains.push(ec);
6737 }
6738 }
6739
6740 for (size_t i = 0; i < chains.size(); i++) {
6741 sp<EffectChain> ec = chains[i];
6742 int sessionid = ec->sessionId();
6743 sp<ThreadBase> t = ec->mThread.promote();
6744 if (t == 0) {
6745 continue;
6746 }
6747 size_t numsessionrefs = mAudioSessionRefs.size();
6748 bool found = false;
6749 for (size_t k = 0; k < numsessionrefs; k++) {
6750 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006751 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006752 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006753 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006754 found = true;
6755 break;
6756 }
6757 }
6758 if (!found) {
6759 // remove all effects from the chain
6760 while (ec->mEffects.size()) {
6761 sp<EffectModule> effect = ec->mEffects[0];
6762 effect->unPin();
6763 Mutex::Autolock _l (t->mLock);
6764 t->removeEffect_l(effect);
6765 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6766 sp<EffectHandle> handle = effect->mHandles[j].promote();
6767 if (handle != 0) {
6768 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006769 if (handle->mHasControl && handle->mEnabled) {
6770 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6771 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006772 }
6773 }
6774 AudioSystem::unregisterEffect(effect->id());
6775 }
6776 }
6777 }
6778 return;
6779}
6780
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006782AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783{
Glenn Kastena1117922012-01-26 10:53:32 -08006784 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785}
6786
6787// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006788AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789{
6790 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006791 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792}
6793
6794// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006795AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796{
Glenn Kastena1117922012-01-26 10:53:32 -08006797 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798}
6799
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006800uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006802 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803}
6804
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006805AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006806{
6807 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6808 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006809 AudioStreamOut *output = thread->getOutput();
6810 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006811 return thread;
6812 }
6813 }
6814 return NULL;
6815}
6816
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006817uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006818{
6819 PlaybackThread *thread = primaryPlaybackThread_l();
6820
6821 if (thread == NULL) {
6822 return 0;
6823 }
6824
6825 return thread->device();
6826}
6827
Eric Laurenta011e352012-03-29 15:51:43 -07006828sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6829 int triggerSession,
6830 int listenerSession,
6831 sync_event_callback_t callBack,
6832 void *cookie)
6833{
6834 Mutex::Autolock _l(mLock);
6835
6836 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6837 status_t playStatus = NAME_NOT_FOUND;
6838 status_t recStatus = NAME_NOT_FOUND;
6839 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6840 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6841 if (playStatus == NO_ERROR) {
6842 return event;
6843 }
6844 }
6845 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6846 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6847 if (recStatus == NO_ERROR) {
6848 return event;
6849 }
6850 }
6851 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6852 mPendingSyncEvents.add(event);
6853 } else {
6854 ALOGV("createSyncEvent() invalid event %d", event->type());
6855 event.clear();
6856 }
6857 return event;
6858}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006859
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860// ----------------------------------------------------------------------------
6861// Effect management
6862// ----------------------------------------------------------------------------
6863
6864
Glenn Kastenf587ba52012-01-26 16:25:10 -08006865status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866{
6867 Mutex::Autolock _l(mLock);
6868 return EffectQueryNumberEffects(numEffects);
6869}
6870
Glenn Kastenf587ba52012-01-26 16:25:10 -08006871status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872{
6873 Mutex::Autolock _l(mLock);
6874 return EffectQueryEffect(index, descriptor);
6875}
6876
Glenn Kasten5e92a782012-01-30 07:40:52 -08006877status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006878 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879{
6880 Mutex::Autolock _l(mLock);
6881 return EffectGetDescriptor(pUuid, descriptor);
6882}
6883
6884
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6886 effect_descriptor_t *pDesc,
6887 const sp<IEffectClient>& effectClient,
6888 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006889 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 int sessionId,
6891 status_t *status,
6892 int *id,
6893 int *enabled)
6894{
6895 status_t lStatus = NO_ERROR;
6896 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006899 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006900 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901
6902 if (pDesc == NULL) {
6903 lStatus = BAD_VALUE;
6904 goto Exit;
6905 }
6906
Eric Laurent84e9a102010-09-23 16:10:16 -07006907 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006908 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006909 lStatus = PERMISSION_DENIED;
6910 goto Exit;
6911 }
6912
Dima Zavinfce7a472011-04-19 22:30:36 -07006913 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006914 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006915 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006916 lStatus = PERMISSION_DENIED;
6917 goto Exit;
6918 }
6919
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006920 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006921 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006922 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006923 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006924 lStatus = BAD_VALUE;
6925 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006926 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006927 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006928 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006929 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006931 }
6932 }
6933
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 {
6935 Mutex::Autolock _l(mLock);
6936
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937
6938 if (!EffectIsNullUuid(&pDesc->uuid)) {
6939 // if uuid is specified, request effect descriptor
6940 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6941 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006942 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 goto Exit;
6944 }
6945 } else {
6946 // if uuid is not specified, look for an available implementation
6947 // of the required type in effect factory
6948 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006949 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 lStatus = BAD_VALUE;
6951 goto Exit;
6952 }
6953 uint32_t numEffects = 0;
6954 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006955 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 bool found = false;
6957
6958 lStatus = EffectQueryNumberEffects(&numEffects);
6959 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006960 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 goto Exit;
6962 }
6963 for (uint32_t i = 0; i < numEffects; i++) {
6964 lStatus = EffectQueryEffect(i, &desc);
6965 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006966 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 continue;
6968 }
6969 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6970 // If matching type found save effect descriptor. If the session is
6971 // 0 and the effect is not auxiliary, continue enumeration in case
6972 // an auxiliary version of this effect type is available
6973 found = true;
6974 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006975 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6977 break;
6978 }
6979 }
6980 }
6981 if (!found) {
6982 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006983 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 goto Exit;
6985 }
6986 // For same effect type, chose auxiliary version over insert version if
6987 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006988 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6990 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6991 }
6992 }
6993
6994 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006995 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6997 lStatus = INVALID_OPERATION;
6998 goto Exit;
6999 }
7000
Eric Laurent59255e42011-07-27 19:49:51 -07007001 // check recording permission for visualizer
7002 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7003 !recordingAllowed()) {
7004 lStatus = PERMISSION_DENIED;
7005 goto Exit;
7006 }
7007
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008 // return effect descriptor
7009 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7010
7011 // If output is not specified try to find a matching audio session ID in one of the
7012 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007013 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7014 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007015 // Note: io is never 0 when creating an effect on an input
7016 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007017 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7019 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007020 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007021 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007024 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007025 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7026 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7027 io = mRecordThreads.keyAt(i);
7028 break;
7029 }
7030 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007031 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007032 // If no output thread contains the requested session ID, default to
7033 // first output. The effect chain will be moved to the correct output
7034 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007035 if (io == 0 && mPlaybackThreads.size()) {
7036 io = mPlaybackThreads.keyAt(0);
7037 }
Steve Block3856b092011-10-20 11:56:00 +01007038 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007039 }
7040 ThreadBase *thread = checkRecordThread_l(io);
7041 if (thread == NULL) {
7042 thread = checkPlaybackThread_l(io);
7043 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007044 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007045 lStatus = BAD_VALUE;
7046 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007049
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007050 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007052 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007053 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7054 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 if (handle != 0 && id != NULL) {
7056 *id = handle->id();
7057 }
7058 }
7059
7060Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007061 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 *status = lStatus;
7063 }
7064 return handle;
7065}
7066
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007067status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7068 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007069{
Steve Block3856b092011-10-20 11:56:00 +01007070 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007071 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007072 Mutex::Autolock _l(mLock);
7073 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007074 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007075 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076 }
Eric Laurentde070132010-07-13 04:45:46 -07007077 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7078 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007079 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007080 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 }
Eric Laurentde070132010-07-13 04:45:46 -07007082 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7083 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007084 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007085 return BAD_VALUE;
7086 }
7087
7088 Mutex::Autolock _dl(dstThread->mLock);
7089 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007090 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007091
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092 return NO_ERROR;
7093}
7094
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007095// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007096status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007097 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007098 AudioFlinger::PlaybackThread *dstThread,
7099 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007100{
Steve Block3856b092011-10-20 11:56:00 +01007101 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007102 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007103
Eric Laurent59255e42011-07-27 19:49:51 -07007104 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007105 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007106 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007107 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007108 return INVALID_OPERATION;
7109 }
7110
Eric Laurent39e94f82010-07-28 01:32:47 -07007111 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007112 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007113 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007114 // removed.
7115 srcThread->removeEffectChain_l(chain);
7116
7117 // transfer all effects one by one so that new effect chain is created on new thread with
7118 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007119 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007120 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007121 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007122 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7123 while (effect != 0) {
7124 srcThread->removeEffect_l(effect);
7125 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007126 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7127 if (effect->state() == EffectModule::ACTIVE ||
7128 effect->state() == EffectModule::STOPPING) {
7129 effect->start();
7130 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007131 // if the move request is not received from audio policy manager, the effect must be
7132 // re-registered with the new strategy and output
7133 if (dstChain == 0) {
7134 dstChain = effect->chain().promote();
7135 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007136 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007137 srcThread->addEffect_l(effect);
7138 return NO_INIT;
7139 }
7140 strategy = dstChain->strategy();
7141 }
7142 if (reRegister) {
7143 AudioSystem::unregisterEffect(effect->id());
7144 AudioSystem::registerEffect(&effect->desc(),
7145 dstOutput,
7146 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007147 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007148 effect->id());
7149 }
Eric Laurentde070132010-07-13 04:45:46 -07007150 effect = chain->getEffectFromId_l(0);
7151 }
7152
7153 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154}
7155
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007158sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159 const sp<AudioFlinger::Client>& client,
7160 const sp<IEffectClient>& effectClient,
7161 int32_t priority,
7162 int sessionId,
7163 effect_descriptor_t *desc,
7164 int *enabled,
7165 status_t *status
7166 )
7167{
7168 sp<EffectModule> effect;
7169 sp<EffectHandle> handle;
7170 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007172 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173 bool effectCreated = false;
7174 bool effectRegistered = false;
7175
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007176 lStatus = initCheck();
7177 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007178 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179 goto Exit;
7180 }
7181
7182 // Do not allow effects with session ID 0 on direct output or duplicating threads
7183 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007184 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007185 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007186 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 lStatus = BAD_VALUE;
7188 goto Exit;
7189 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007190 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007191 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007192 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007193 desc->name, desc->flags, mType);
7194 lStatus = BAD_VALUE;
7195 goto Exit;
7196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197
Steve Block3856b092011-10-20 11:56:00 +01007198 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199
7200 { // scope for mLock
7201 Mutex::Autolock _l(mLock);
7202
7203 // check for existing effect chain with the requested audio session
7204 chain = getEffectChain_l(sessionId);
7205 if (chain == 0) {
7206 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007207 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 chain = new EffectChain(this, sessionId);
7209 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007210 chain->setStrategy(getStrategyForSession_l(sessionId));
7211 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007213 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214 }
7215
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007216 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217
7218 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007219 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007220 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007221 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222 if (lStatus != NO_ERROR) {
7223 goto Exit;
7224 }
7225 effectRegistered = true;
7226 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007227 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 lStatus = effect->status();
7229 if (lStatus != NO_ERROR) {
7230 goto Exit;
7231 }
Eric Laurentcab11242010-07-15 12:50:15 -07007232 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007233 if (lStatus != NO_ERROR) {
7234 goto Exit;
7235 }
7236 effectCreated = true;
7237
7238 effect->setDevice(mDevice);
7239 effect->setMode(mAudioFlinger->getMode());
7240 }
7241 // create effect handle and connect it to effect module
7242 handle = new EffectHandle(effect, client, effectClient, priority);
7243 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007244 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245 *enabled = (int)effect->isEnabled();
7246 }
7247 }
7248
7249Exit:
7250 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007251 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007253 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 }
7255 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007256 AudioSystem::unregisterEffect(effect->id());
7257 }
7258 if (chainCreated) {
7259 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 }
7261 handle.clear();
7262 }
7263
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007264 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265 *status = lStatus;
7266 }
7267 return handle;
7268}
7269
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007270sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7271{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007272 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007273 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007274}
7275
Eric Laurentde070132010-07-13 04:45:46 -07007276// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7277// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007278status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007279{
7280 // check for existing effect chain with the requested audio session
7281 int sessionId = effect->sessionId();
7282 sp<EffectChain> chain = getEffectChain_l(sessionId);
7283 bool chainCreated = false;
7284
7285 if (chain == 0) {
7286 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007287 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007288 chain = new EffectChain(this, sessionId);
7289 addEffectChain_l(chain);
7290 chain->setStrategy(getStrategyForSession_l(sessionId));
7291 chainCreated = true;
7292 }
Steve Block3856b092011-10-20 11:56:00 +01007293 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007294
7295 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007296 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007297 this, effect->desc().name, chain.get());
7298 return BAD_VALUE;
7299 }
7300
7301 status_t status = chain->addEffect_l(effect);
7302 if (status != NO_ERROR) {
7303 if (chainCreated) {
7304 removeEffectChain_l(chain);
7305 }
7306 return status;
7307 }
7308
7309 effect->setDevice(mDevice);
7310 effect->setMode(mAudioFlinger->getMode());
7311 return NO_ERROR;
7312}
7313
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007314void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007315
Steve Block3856b092011-10-20 11:56:00 +01007316 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007318 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7319 detachAuxEffect_l(effect->id());
7320 }
7321
7322 sp<EffectChain> chain = effect->chain().promote();
7323 if (chain != 0) {
7324 // remove effect chain if removing last effect
7325 if (chain->removeEffect_l(effect) == 0) {
7326 removeEffectChain_l(chain);
7327 }
7328 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007329 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007330 }
7331}
7332
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007333void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007334 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007335{
7336 effectChains = mEffectChains;
7337 for (size_t i = 0; i < mEffectChains.size(); i++) {
7338 mEffectChains[i]->lock();
7339 }
7340}
7341
7342void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007343 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007344{
7345 for (size_t i = 0; i < effectChains.size(); i++) {
7346 effectChains[i]->unlock();
7347 }
7348}
7349
7350sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7351{
7352 Mutex::Autolock _l(mLock);
7353 return getEffectChain_l(sessionId);
7354}
7355
7356sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7357{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007358 size_t size = mEffectChains.size();
7359 for (size_t i = 0; i < size; i++) {
7360 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007361 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007362 }
7363 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007364 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007365}
7366
Glenn Kastenf78aee72012-01-04 11:00:47 -08007367void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007368{
7369 Mutex::Autolock _l(mLock);
7370 size_t size = mEffectChains.size();
7371 for (size_t i = 0; i < size; i++) {
7372 mEffectChains[i]->setMode_l(mode);
7373 }
7374}
7375
7376void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007377 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007378 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007379
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007381 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 // delete the effect module if removing last handle on it
7383 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007384 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007385 removeEffect_l(effect);
7386 AudioSystem::unregisterEffect(effect->id());
7387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 }
7389}
7390
7391status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7392{
7393 int session = chain->sessionId();
7394 int16_t *buffer = mMixBuffer;
7395 bool ownsBuffer = false;
7396
Steve Block3856b092011-10-20 11:56:00 +01007397 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398 if (session > 0) {
7399 // Only one effect chain can be present in direct output thread and it uses
7400 // the mix buffer as input
7401 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007402 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403 buffer = new int16_t[numSamples];
7404 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007405 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406 ownsBuffer = true;
7407 }
7408
7409 // Attach all tracks with same session ID to this chain.
7410 for (size_t i = 0; i < mTracks.size(); ++i) {
7411 sp<Track> track = mTracks[i];
7412 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007413 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007415 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416 }
7417 }
7418
7419 // indicate all active tracks in the chain
7420 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7421 sp<Track> track = mActiveTracks[i].promote();
7422 if (track == 0) continue;
7423 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007424 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007425 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 }
7427 }
7428 }
7429
7430 chain->setInBuffer(buffer, ownsBuffer);
7431 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007432 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007433 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007434 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7435 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007437 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7438 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007439 // Effect chain for other sessions are inserted at beginning of effect
7440 // chains list to be processed before output mix effects. Relative order between other
7441 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 size_t size = mEffectChains.size();
7443 size_t i = 0;
7444 for (i = 0; i < size; i++) {
7445 if (mEffectChains[i]->sessionId() < session) break;
7446 }
7447 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007448 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449
7450 return NO_ERROR;
7451}
7452
7453size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7454{
7455 int session = chain->sessionId();
7456
Steve Block3856b092011-10-20 11:56:00 +01007457 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007458
7459 for (size_t i = 0; i < mEffectChains.size(); i++) {
7460 if (chain == mEffectChains[i]) {
7461 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007462 // detach all active tracks from the chain
7463 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7464 sp<Track> track = mActiveTracks[i].promote();
7465 if (track == 0) continue;
7466 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007467 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007468 chain.get(), session);
7469 chain->decActiveTrackCnt();
7470 }
7471 }
7472
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 // detach all tracks with same session ID from this chain
7474 for (size_t i = 0; i < mTracks.size(); ++i) {
7475 sp<Track> track = mTracks[i];
7476 if (session == track->sessionId()) {
7477 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007478 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 }
7480 }
Eric Laurentde070132010-07-13 04:45:46 -07007481 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007482 }
7483 }
7484 return mEffectChains.size();
7485}
7486
Eric Laurentde070132010-07-13 04:45:46 -07007487status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7488 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489{
7490 Mutex::Autolock _l(mLock);
7491 return attachAuxEffect_l(track, EffectId);
7492}
7493
Eric Laurentde070132010-07-13 04:45:46 -07007494status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7495 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496{
7497 status_t status = NO_ERROR;
7498
7499 if (EffectId == 0) {
7500 track->setAuxBuffer(0, NULL);
7501 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007502 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7503 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007504 if (effect != 0) {
7505 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7506 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7507 } else {
7508 status = INVALID_OPERATION;
7509 }
7510 } else {
7511 status = BAD_VALUE;
7512 }
7513 }
7514 return status;
7515}
7516
7517void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7518{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007519 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520 sp<Track> track = mTracks[i];
7521 if (track->auxEffectId() == effectId) {
7522 attachAuxEffect_l(track, 0);
7523 }
7524 }
7525}
7526
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007527status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7528{
7529 // only one chain per input thread
7530 if (mEffectChains.size() != 0) {
7531 return INVALID_OPERATION;
7532 }
Steve Block3856b092011-10-20 11:56:00 +01007533 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007534
7535 chain->setInBuffer(NULL);
7536 chain->setOutBuffer(NULL);
7537
Eric Laurent59255e42011-07-27 19:49:51 -07007538 checkSuspendOnAddEffectChain_l(chain);
7539
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007540 mEffectChains.add(chain);
7541
7542 return NO_ERROR;
7543}
7544
7545size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7546{
Steve Block3856b092011-10-20 11:56:00 +01007547 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007548 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007549 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7550 chain.get(), mEffectChains.size(), this);
7551 if (mEffectChains.size() == 1) {
7552 mEffectChains.removeAt(0);
7553 }
7554 return 0;
7555}
7556
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557// ----------------------------------------------------------------------------
7558// EffectModule implementation
7559// ----------------------------------------------------------------------------
7560
7561#undef LOG_TAG
7562#define LOG_TAG "AudioFlinger::EffectModule"
7563
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007564AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565 const wp<AudioFlinger::EffectChain>& chain,
7566 effect_descriptor_t *desc,
7567 int id,
7568 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007569 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007570 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571{
Steve Block3856b092011-10-20 11:56:00 +01007572 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007573 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007574 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575 return;
7576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577
7578 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7579
7580 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007581 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582
7583 if (mStatus != NO_ERROR) {
7584 return;
7585 }
7586 lStatus = init();
7587 if (lStatus < 0) {
7588 mStatus = lStatus;
7589 goto Error;
7590 }
7591
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007592 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7593 mPinned = true;
7594 }
Steve Block3856b092011-10-20 11:56:00 +01007595 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 return;
7597Error:
7598 EffectRelease(mEffectInterface);
7599 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007600 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601}
7602
7603AudioFlinger::EffectModule::~EffectModule()
7604{
Steve Block3856b092011-10-20 11:56:00 +01007605 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007607 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7608 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7609 sp<ThreadBase> thread = mThread.promote();
7610 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007611 audio_stream_t *stream = thread->stream();
7612 if (stream != NULL) {
7613 stream->remove_audio_effect(stream, mEffectInterface);
7614 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007615 }
7616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617 // release effect engine
7618 EffectRelease(mEffectInterface);
7619 }
7620}
7621
Glenn Kasten435dbe62012-01-30 10:15:48 -08007622status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623{
7624 status_t status;
7625
7626 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 int priority = handle->priority();
7628 size_t size = mHandles.size();
7629 sp<EffectHandle> h;
7630 size_t i;
7631 for (i = 0; i < size; i++) {
7632 h = mHandles[i].promote();
7633 if (h == 0) continue;
7634 if (h->priority() <= priority) break;
7635 }
7636 // if inserted in first place, move effect control from previous owner to this handle
7637 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007638 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007640 enabled = h->enabled();
7641 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007642 }
Eric Laurent59255e42011-07-27 19:49:51 -07007643 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644 status = NO_ERROR;
7645 } else {
7646 status = ALREADY_EXISTS;
7647 }
Steve Block3856b092011-10-20 11:56:00 +01007648 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649 mHandles.insertAt(handle, i);
7650 return status;
7651}
7652
7653size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7654{
7655 Mutex::Autolock _l(mLock);
7656 size_t size = mHandles.size();
7657 size_t i;
7658 for (i = 0; i < size; i++) {
7659 if (mHandles[i] == handle) break;
7660 }
7661 if (i == size) {
7662 return size;
7663 }
Steve Block3856b092011-10-20 11:56:00 +01007664 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007665
7666 bool enabled = false;
7667 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007668 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007669 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007670 enabled = hdl->enabled();
7671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 mHandles.removeAt(i);
7673 size = mHandles.size();
7674 // if removed from first place, move effect control from this handle to next in line
7675 if (i == 0 && size != 0) {
7676 sp<EffectHandle> h = mHandles[0].promote();
7677 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007678 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 }
7680 }
7681
Eric Laurentec437d82011-07-26 20:54:46 -07007682 // Prevent calls to process() and other functions on effect interface from now on.
7683 // The effect engine will be released by the destructor when the last strong reference on
7684 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007685 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007686 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007687 }
7688
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 return size;
7690}
7691
Eric Laurent59255e42011-07-27 19:49:51 -07007692sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7693{
7694 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007695 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007696}
7697
Glenn Kasten58123c32012-02-03 10:32:24 -08007698void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007700 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 // keep a strong reference on this EffectModule to avoid calling the
7702 // destructor before we exit
7703 sp<EffectModule> keep(this);
7704 {
7705 sp<ThreadBase> thread = mThread.promote();
7706 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007707 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 }
7709 }
7710}
7711
7712void AudioFlinger::EffectModule::updateState() {
7713 Mutex::Autolock _l(mLock);
7714
7715 switch (mState) {
7716 case RESTART:
7717 reset_l();
7718 // FALL THROUGH
7719
7720 case STARTING:
7721 // clear auxiliary effect input buffer for next accumulation
7722 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7723 memset(mConfig.inputCfg.buffer.raw,
7724 0,
7725 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7726 }
7727 start_l();
7728 mState = ACTIVE;
7729 break;
7730 case STOPPING:
7731 stop_l();
7732 mDisableWaitCnt = mMaxDisableWaitCnt;
7733 mState = STOPPED;
7734 break;
7735 case STOPPED:
7736 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7737 // turn off sequence.
7738 if (--mDisableWaitCnt == 0) {
7739 reset_l();
7740 mState = IDLE;
7741 }
7742 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007743 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 break;
7745 }
7746}
7747
7748void AudioFlinger::EffectModule::process()
7749{
7750 Mutex::Autolock _l(mLock);
7751
Eric Laurentec437d82011-07-26 20:54:46 -07007752 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 mConfig.inputCfg.buffer.raw == NULL ||
7754 mConfig.outputCfg.buffer.raw == NULL) {
7755 return;
7756 }
7757
Eric Laurent8f45bd72010-08-31 13:50:07 -07007758 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7760 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007761 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007763 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 }
7765
7766 // do the actual processing in the effect engine
7767 int ret = (*mEffectInterface)->process(mEffectInterface,
7768 &mConfig.inputCfg.buffer,
7769 &mConfig.outputCfg.buffer);
7770
7771 // force transition to IDLE state when engine is ready
7772 if (mState == STOPPED && ret == -ENODATA) {
7773 mDisableWaitCnt = 1;
7774 }
7775
7776 // clear auxiliary effect input buffer for next accumulation
7777 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007778 memset(mConfig.inputCfg.buffer.raw, 0,
7779 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 }
7781 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007782 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7783 // If an insert effect is idle and input buffer is different from output buffer,
7784 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007786 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007787 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7788 int16_t *in = mConfig.inputCfg.buffer.s16;
7789 int16_t *out = mConfig.outputCfg.buffer.s16;
7790 for (size_t i = 0; i < frameCnt; i++) {
7791 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 }
7794 }
7795}
7796
7797void AudioFlinger::EffectModule::reset_l()
7798{
7799 if (mEffectInterface == NULL) {
7800 return;
7801 }
7802 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7803}
7804
7805status_t AudioFlinger::EffectModule::configure()
7806{
7807 uint32_t channels;
7808 if (mEffectInterface == NULL) {
7809 return NO_INIT;
7810 }
7811
7812 sp<ThreadBase> thread = mThread.promote();
7813 if (thread == 0) {
7814 return DEAD_OBJECT;
7815 }
7816
7817 // TODO: handle configuration of effects replacing track process
7818 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007819 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007821 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 }
7823
7824 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007825 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 } else {
7827 mConfig.inputCfg.channels = channels;
7828 }
7829 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007830 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7831 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832 mConfig.inputCfg.samplingRate = thread->sampleRate();
7833 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7834 mConfig.inputCfg.bufferProvider.cookie = NULL;
7835 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7836 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7837 mConfig.outputCfg.bufferProvider.cookie = NULL;
7838 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7839 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7840 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7841 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007842 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007843 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 // - in other sessions:
7845 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7846 // other effect: overwrites output buffer: input buffer == output buffer
7847 // Auxiliary effect:
7848 // accumulates in output buffer: input buffer != output buffer
7849 // Therefore: accumulate <=> input buffer != output buffer
7850 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7851 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7852 } else {
7853 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7854 }
7855 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7856 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7857 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7858 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7859
Steve Block3856b092011-10-20 11:56:00 +01007860 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007861 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7862
Mathias Agopian65ab4712010-07-14 17:59:35 -07007863 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007864 uint32_t size = sizeof(int);
7865 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007866 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007867 sizeof(effect_config_t),
7868 &mConfig,
7869 &size,
7870 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 if (status == 0) {
7872 status = cmdStatus;
7873 }
7874
7875 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7876 (1000 * mConfig.outputCfg.buffer.frameCount);
7877
7878 return status;
7879}
7880
7881status_t AudioFlinger::EffectModule::init()
7882{
7883 Mutex::Autolock _l(mLock);
7884 if (mEffectInterface == NULL) {
7885 return NO_INIT;
7886 }
7887 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007888 uint32_t size = sizeof(status_t);
7889 status_t status = (*mEffectInterface)->command(mEffectInterface,
7890 EFFECT_CMD_INIT,
7891 0,
7892 NULL,
7893 &size,
7894 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895 if (status == 0) {
7896 status = cmdStatus;
7897 }
7898 return status;
7899}
7900
Eric Laurentec35a142011-10-05 17:42:25 -07007901status_t AudioFlinger::EffectModule::start()
7902{
7903 Mutex::Autolock _l(mLock);
7904 return start_l();
7905}
7906
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907status_t AudioFlinger::EffectModule::start_l()
7908{
7909 if (mEffectInterface == NULL) {
7910 return NO_INIT;
7911 }
7912 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007913 uint32_t size = sizeof(status_t);
7914 status_t status = (*mEffectInterface)->command(mEffectInterface,
7915 EFFECT_CMD_ENABLE,
7916 0,
7917 NULL,
7918 &size,
7919 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007920 if (status == 0) {
7921 status = cmdStatus;
7922 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007923 if (status == 0 &&
7924 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7925 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7926 sp<ThreadBase> thread = mThread.promote();
7927 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007928 audio_stream_t *stream = thread->stream();
7929 if (stream != NULL) {
7930 stream->add_audio_effect(stream, mEffectInterface);
7931 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007932 }
7933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007934 return status;
7935}
7936
Eric Laurentec437d82011-07-26 20:54:46 -07007937status_t AudioFlinger::EffectModule::stop()
7938{
7939 Mutex::Autolock _l(mLock);
7940 return stop_l();
7941}
7942
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943status_t AudioFlinger::EffectModule::stop_l()
7944{
7945 if (mEffectInterface == NULL) {
7946 return NO_INIT;
7947 }
7948 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007949 uint32_t size = sizeof(status_t);
7950 status_t status = (*mEffectInterface)->command(mEffectInterface,
7951 EFFECT_CMD_DISABLE,
7952 0,
7953 NULL,
7954 &size,
7955 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 if (status == 0) {
7957 status = cmdStatus;
7958 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007959 if (status == 0 &&
7960 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7961 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7962 sp<ThreadBase> thread = mThread.promote();
7963 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007964 audio_stream_t *stream = thread->stream();
7965 if (stream != NULL) {
7966 stream->remove_audio_effect(stream, mEffectInterface);
7967 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007968 }
7969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 return status;
7971}
7972
Eric Laurent25f43952010-07-28 05:40:18 -07007973status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7974 uint32_t cmdSize,
7975 void *pCmdData,
7976 uint32_t *replySize,
7977 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978{
7979 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007980// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981
Eric Laurentec437d82011-07-26 20:54:46 -07007982 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 return NO_INIT;
7984 }
Eric Laurent25f43952010-07-28 05:40:18 -07007985 status_t status = (*mEffectInterface)->command(mEffectInterface,
7986 cmdCode,
7987 cmdSize,
7988 pCmdData,
7989 replySize,
7990 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007992 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993 for (size_t i = 1; i < mHandles.size(); i++) {
7994 sp<EffectHandle> h = mHandles[i].promote();
7995 if (h != 0) {
7996 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7997 }
7998 }
7999 }
8000 return status;
8001}
8002
8003status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8004{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008005
Mathias Agopian65ab4712010-07-14 17:59:35 -07008006 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008007 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008008
8009 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008010 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8011 if (enabled && status != NO_ERROR) {
8012 return status;
8013 }
8014
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 switch (mState) {
8016 // going from disabled to enabled
8017 case IDLE:
8018 mState = STARTING;
8019 break;
8020 case STOPPED:
8021 mState = RESTART;
8022 break;
8023 case STOPPING:
8024 mState = ACTIVE;
8025 break;
8026
8027 // going from enabled to disabled
8028 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008029 mState = STOPPED;
8030 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008031 case STARTING:
8032 mState = IDLE;
8033 break;
8034 case ACTIVE:
8035 mState = STOPPING;
8036 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008037 case DESTROYED:
8038 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039 }
8040 for (size_t i = 1; i < mHandles.size(); i++) {
8041 sp<EffectHandle> h = mHandles[i].promote();
8042 if (h != 0) {
8043 h->setEnabled(enabled);
8044 }
8045 }
8046 }
8047 return NO_ERROR;
8048}
8049
Glenn Kastenc59c0042012-02-02 14:06:11 -08008050bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051{
8052 switch (mState) {
8053 case RESTART:
8054 case STARTING:
8055 case ACTIVE:
8056 return true;
8057 case IDLE:
8058 case STOPPING:
8059 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008060 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 default:
8062 return false;
8063 }
8064}
8065
Glenn Kastenc59c0042012-02-02 14:06:11 -08008066bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008067{
8068 switch (mState) {
8069 case RESTART:
8070 case ACTIVE:
8071 case STOPPING:
8072 case STOPPED:
8073 return true;
8074 case IDLE:
8075 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008076 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008077 default:
8078 return false;
8079 }
8080}
8081
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8083{
8084 Mutex::Autolock _l(mLock);
8085 status_t status = NO_ERROR;
8086
8087 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8088 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008089 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008090 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8091 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092 status_t cmdStatus;
8093 uint32_t volume[2];
8094 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008095 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096 volume[0] = *left;
8097 volume[1] = *right;
8098 if (controller) {
8099 pVolume = volume;
8100 }
Eric Laurent25f43952010-07-28 05:40:18 -07008101 status = (*mEffectInterface)->command(mEffectInterface,
8102 EFFECT_CMD_SET_VOLUME,
8103 size,
8104 volume,
8105 &size,
8106 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008107 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8108 *left = volume[0];
8109 *right = volume[1];
8110 }
8111 }
8112 return status;
8113}
8114
8115status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8116{
8117 Mutex::Autolock _l(mLock);
8118 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008119 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8120 // audio pre processing modules on RecordThread can receive both output and
8121 // input device indication in the same call
8122 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8123 if (dev) {
8124 status_t cmdStatus;
8125 uint32_t size = sizeof(status_t);
8126
8127 status = (*mEffectInterface)->command(mEffectInterface,
8128 EFFECT_CMD_SET_DEVICE,
8129 sizeof(uint32_t),
8130 &dev,
8131 &size,
8132 &cmdStatus);
8133 if (status == NO_ERROR) {
8134 status = cmdStatus;
8135 }
8136 }
8137 dev = device & AUDIO_DEVICE_IN_ALL;
8138 if (dev) {
8139 status_t cmdStatus;
8140 uint32_t size = sizeof(status_t);
8141
8142 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8143 EFFECT_CMD_SET_INPUT_DEVICE,
8144 sizeof(uint32_t),
8145 &dev,
8146 &size,
8147 &cmdStatus);
8148 if (status2 == NO_ERROR) {
8149 status2 = cmdStatus;
8150 }
8151 if (status == NO_ERROR) {
8152 status = status2;
8153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 }
8155 }
8156 return status;
8157}
8158
Glenn Kastenf78aee72012-01-04 11:00:47 -08008159status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008160{
8161 Mutex::Autolock _l(mLock);
8162 status_t status = NO_ERROR;
8163 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008165 uint32_t size = sizeof(status_t);
8166 status = (*mEffectInterface)->command(mEffectInterface,
8167 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008168 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008169 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008170 &size,
8171 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 if (status == NO_ERROR) {
8173 status = cmdStatus;
8174 }
8175 }
8176 return status;
8177}
8178
Eric Laurent59255e42011-07-27 19:49:51 -07008179void AudioFlinger::EffectModule::setSuspended(bool suspended)
8180{
8181 Mutex::Autolock _l(mLock);
8182 mSuspended = suspended;
8183}
Glenn Kastena3a85482012-01-04 11:01:11 -08008184
8185bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008186{
8187 Mutex::Autolock _l(mLock);
8188 return mSuspended;
8189}
8190
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8192{
8193 const size_t SIZE = 256;
8194 char buffer[SIZE];
8195 String8 result;
8196
8197 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8198 result.append(buffer);
8199
8200 bool locked = tryLock(mLock);
8201 // failed to lock - AudioFlinger is probably deadlocked
8202 if (!locked) {
8203 result.append("\t\tCould not lock Fx mutex:\n");
8204 }
8205
8206 result.append("\t\tSession Status State Engine:\n");
8207 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8208 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8209 result.append(buffer);
8210
8211 result.append("\t\tDescriptor:\n");
8212 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8213 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8214 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8215 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8216 result.append(buffer);
8217 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8218 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8219 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8220 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8221 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008222 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008223 mDescriptor.apiVersion,
8224 mDescriptor.flags);
8225 result.append(buffer);
8226 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8227 mDescriptor.name);
8228 result.append(buffer);
8229 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8230 mDescriptor.implementor);
8231 result.append(buffer);
8232
8233 result.append("\t\t- Input configuration:\n");
8234 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8235 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8236 (uint32_t)mConfig.inputCfg.buffer.raw,
8237 mConfig.inputCfg.buffer.frameCount,
8238 mConfig.inputCfg.samplingRate,
8239 mConfig.inputCfg.channels,
8240 mConfig.inputCfg.format);
8241 result.append(buffer);
8242
8243 result.append("\t\t- Output configuration:\n");
8244 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8245 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8246 (uint32_t)mConfig.outputCfg.buffer.raw,
8247 mConfig.outputCfg.buffer.frameCount,
8248 mConfig.outputCfg.samplingRate,
8249 mConfig.outputCfg.channels,
8250 mConfig.outputCfg.format);
8251 result.append(buffer);
8252
8253 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8254 result.append(buffer);
8255 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8256 for (size_t i = 0; i < mHandles.size(); ++i) {
8257 sp<EffectHandle> handle = mHandles[i].promote();
8258 if (handle != 0) {
8259 handle->dump(buffer, SIZE);
8260 result.append(buffer);
8261 }
8262 }
8263
8264 result.append("\n");
8265
8266 write(fd, result.string(), result.length());
8267
8268 if (locked) {
8269 mLock.unlock();
8270 }
8271
8272 return NO_ERROR;
8273}
8274
8275// ----------------------------------------------------------------------------
8276// EffectHandle implementation
8277// ----------------------------------------------------------------------------
8278
8279#undef LOG_TAG
8280#define LOG_TAG "AudioFlinger::EffectHandle"
8281
8282AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8283 const sp<AudioFlinger::Client>& client,
8284 const sp<IEffectClient>& effectClient,
8285 int32_t priority)
8286 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008287 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008288 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008289{
Steve Block3856b092011-10-20 11:56:00 +01008290 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008292 if (client == 0) {
8293 return;
8294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8296 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8297 if (mCblkMemory != 0) {
8298 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8299
Glenn Kastena0d68332012-01-27 16:47:15 -08008300 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008301 new(mCblk) effect_param_cblk_t();
8302 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008305 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008306 return;
8307 }
8308}
8309
8310AudioFlinger::EffectHandle::~EffectHandle()
8311{
Steve Block3856b092011-10-20 11:56:00 +01008312 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008313 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008314 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315}
8316
8317status_t AudioFlinger::EffectHandle::enable()
8318{
Steve Block3856b092011-10-20 11:56:00 +01008319 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008320 if (!mHasControl) return INVALID_OPERATION;
8321 if (mEffect == 0) return DEAD_OBJECT;
8322
Eric Laurentdb7c0792011-08-10 10:37:50 -07008323 if (mEnabled) {
8324 return NO_ERROR;
8325 }
8326
Eric Laurent59255e42011-07-27 19:49:51 -07008327 mEnabled = true;
8328
8329 sp<ThreadBase> thread = mEffect->thread().promote();
8330 if (thread != 0) {
8331 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8332 }
8333
8334 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8335 if (mEffect->suspended()) {
8336 return NO_ERROR;
8337 }
8338
Eric Laurentdb7c0792011-08-10 10:37:50 -07008339 status_t status = mEffect->setEnabled(true);
8340 if (status != NO_ERROR) {
8341 if (thread != 0) {
8342 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8343 }
8344 mEnabled = false;
8345 }
8346 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008347}
8348
8349status_t AudioFlinger::EffectHandle::disable()
8350{
Steve Block3856b092011-10-20 11:56:00 +01008351 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008352 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008353 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008354
Eric Laurentdb7c0792011-08-10 10:37:50 -07008355 if (!mEnabled) {
8356 return NO_ERROR;
8357 }
Eric Laurent59255e42011-07-27 19:49:51 -07008358 mEnabled = false;
8359
8360 if (mEffect->suspended()) {
8361 return NO_ERROR;
8362 }
8363
8364 status_t status = mEffect->setEnabled(false);
8365
8366 sp<ThreadBase> thread = mEffect->thread().promote();
8367 if (thread != 0) {
8368 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8369 }
8370
8371 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372}
8373
8374void AudioFlinger::EffectHandle::disconnect()
8375{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008376 disconnect(true);
8377}
8378
Glenn Kasten58123c32012-02-03 10:32:24 -08008379void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008380{
Glenn Kasten58123c32012-02-03 10:32:24 -08008381 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 if (mEffect == 0) {
8383 return;
8384 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008385 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008386
Eric Laurenta85a74a2011-10-19 11:44:54 -07008387 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008388 sp<ThreadBase> thread = mEffect->thread().promote();
8389 if (thread != 0) {
8390 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8391 }
Eric Laurent59255e42011-07-27 19:49:51 -07008392 }
8393
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394 // release sp on module => module destructor can be called now
8395 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008397 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008398 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008399 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8400 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008401 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008402 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8404 mClient.clear();
8405 }
8406}
8407
Eric Laurent25f43952010-07-28 05:40:18 -07008408status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8409 uint32_t cmdSize,
8410 void *pCmdData,
8411 uint32_t *replySize,
8412 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413{
Steve Block3856b092011-10-20 11:56:00 +01008414// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008415// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416
8417 // only get parameter command is permitted for applications not controlling the effect
8418 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8419 return INVALID_OPERATION;
8420 }
8421 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008422 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008423
8424 // handle commands that are not forwarded transparently to effect engine
8425 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8426 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8427 // no risk to block the whole media server process or mixer threads is we are stuck here
8428 Mutex::Autolock _l(mCblk->lock);
8429 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8430 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8431 mCblk->serverIndex = 0;
8432 mCblk->clientIndex = 0;
8433 return BAD_VALUE;
8434 }
8435 status_t status = NO_ERROR;
8436 while (mCblk->serverIndex < mCblk->clientIndex) {
8437 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008438 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 int *p = (int *)(mBuffer + mCblk->serverIndex);
8440 int size = *p++;
8441 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008442 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008443 break;
8444 }
8445 effect_param_t *param = (effect_param_t *)p;
8446 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008447 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008448 mCblk->serverIndex += size;
8449 continue;
8450 }
Eric Laurent25f43952010-07-28 05:40:18 -07008451 uint32_t psize = sizeof(effect_param_t) +
8452 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8453 param->vsize;
8454 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8455 psize,
8456 p,
8457 &rsize,
8458 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008459 // stop at first error encountered
8460 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008462 *(int *)pReplyData = reply;
8463 break;
8464 } else if (reply != NO_ERROR) {
8465 *(int *)pReplyData = reply;
8466 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008467 }
8468 mCblk->serverIndex += size;
8469 }
8470 mCblk->serverIndex = 0;
8471 mCblk->clientIndex = 0;
8472 return status;
8473 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008474 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008475 return enable();
8476 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008477 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008478 return disable();
8479 }
8480
8481 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8482}
8483
Eric Laurent59255e42011-07-27 19:49:51 -07008484void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008485{
Steve Block3856b092011-10-20 11:56:00 +01008486 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487
8488 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008489 mEnabled = enabled;
8490
Mathias Agopian65ab4712010-07-14 17:59:35 -07008491 if (signal && mEffectClient != 0) {
8492 mEffectClient->controlStatusChanged(hasControl);
8493 }
8494}
8495
Eric Laurent25f43952010-07-28 05:40:18 -07008496void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8497 uint32_t cmdSize,
8498 void *pCmdData,
8499 uint32_t replySize,
8500 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501{
8502 if (mEffectClient != 0) {
8503 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8504 }
8505}
8506
8507
8508
8509void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8510{
8511 if (mEffectClient != 0) {
8512 mEffectClient->enableStatusChanged(enabled);
8513 }
8514}
8515
8516status_t AudioFlinger::EffectHandle::onTransact(
8517 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8518{
8519 return BnEffect::onTransact(code, data, reply, flags);
8520}
8521
8522
8523void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8524{
Glenn Kastena0d68332012-01-27 16:47:15 -08008525 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526
8527 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008528 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008529 mPriority,
8530 mHasControl,
8531 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008532 mCblk ? mCblk->clientIndex : 0,
8533 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534 );
8535
8536 if (locked) {
8537 mCblk->lock.unlock();
8538 }
8539}
8540
8541#undef LOG_TAG
8542#define LOG_TAG "AudioFlinger::EffectChain"
8543
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008544AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008545 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008546 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008547 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8548 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008549{
Dima Zavinfce7a472011-04-19 22:30:36 -07008550 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008551 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008552 return;
8553 }
8554 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8555 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556}
8557
8558AudioFlinger::EffectChain::~EffectChain()
8559{
8560 if (mOwnInBuffer) {
8561 delete mInBuffer;
8562 }
8563
8564}
8565
Eric Laurent59255e42011-07-27 19:49:51 -07008566// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008567sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 size_t size = mEffects.size();
8570
8571 for (size_t i = 0; i < size; i++) {
8572 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008573 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008574 }
8575 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008576 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577}
8578
Eric Laurent59255e42011-07-27 19:49:51 -07008579// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008580sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582 size_t size = mEffects.size();
8583
8584 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008585 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8586 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008587 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008588 }
8589 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008590 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008591}
8592
Eric Laurent59255e42011-07-27 19:49:51 -07008593// getEffectFromType_l() must be called with ThreadBase::mLock held
8594sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8595 const effect_uuid_t *type)
8596{
Eric Laurent59255e42011-07-27 19:49:51 -07008597 size_t size = mEffects.size();
8598
8599 for (size_t i = 0; i < size; i++) {
8600 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008601 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008602 }
8603 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008604 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008605}
8606
Mathias Agopian65ab4712010-07-14 17:59:35 -07008607// Must be called with EffectChain::mLock locked
8608void AudioFlinger::EffectChain::process_l()
8609{
Eric Laurentdac69112010-09-28 14:09:57 -07008610 sp<ThreadBase> thread = mThread.promote();
8611 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008612 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008613 return;
8614 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008615 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8616 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008617 // always process effects unless no more tracks are on the session and the effect tail
8618 // has been rendered
8619 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008620 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008621 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008622
Eric Laurent544fe9b2011-11-11 15:42:52 -08008623 if (!tracksOnSession && mTailBufferCount == 0) {
8624 doProcess = false;
8625 }
8626
8627 if (activeTrackCnt() == 0) {
8628 // if no track is active and the effect tail has not been rendered,
8629 // the input buffer must be cleared here as the mixer process will not do it
8630 if (tracksOnSession || mTailBufferCount > 0) {
8631 size_t numSamples = thread->frameCount() * thread->channelCount();
8632 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8633 if (mTailBufferCount > 0) {
8634 mTailBufferCount--;
8635 }
8636 }
8637 }
Eric Laurentdac69112010-09-28 14:09:57 -07008638 }
8639
Mathias Agopian65ab4712010-07-14 17:59:35 -07008640 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008641 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008642 for (size_t i = 0; i < size; i++) {
8643 mEffects[i]->process();
8644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008645 }
8646 for (size_t i = 0; i < size; i++) {
8647 mEffects[i]->updateState();
8648 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649}
8650
Eric Laurentcab11242010-07-15 12:50:15 -07008651// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008652status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008653{
8654 effect_descriptor_t desc = effect->desc();
8655 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8656
8657 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008658 effect->setChain(this);
8659 sp<ThreadBase> thread = mThread.promote();
8660 if (thread == 0) {
8661 return NO_INIT;
8662 }
8663 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008664
8665 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8666 // Auxiliary effects are inserted at the beginning of mEffects vector as
8667 // they are processed first and accumulated in chain input buffer
8668 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008669
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 // the input buffer for auxiliary effect contains mono samples in
8671 // 32 bit format. This is to avoid saturation in AudoMixer
8672 // accumulation stage. Saturation is done in EffectModule::process() before
8673 // calling the process in effect engine
8674 size_t numSamples = thread->frameCount();
8675 int32_t *buffer = new int32_t[numSamples];
8676 memset(buffer, 0, numSamples * sizeof(int32_t));
8677 effect->setInBuffer((int16_t *)buffer);
8678 // auxiliary effects output samples to chain input buffer for further processing
8679 // by insert effects
8680 effect->setOutBuffer(mInBuffer);
8681 } else {
8682 // Insert effects are inserted at the end of mEffects vector as they are processed
8683 // after track and auxiliary effects.
8684 // Insert effect order as a function of indicated preference:
8685 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8686 // another effect is present
8687 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8688 // last effect claiming first position
8689 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8690 // first effect claiming last position
8691 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8692 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8693 // already present
8694
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008695 size_t size = mEffects.size();
8696 size_t idx_insert = size;
8697 ssize_t idx_insert_first = -1;
8698 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008700 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008701 effect_descriptor_t d = mEffects[i]->desc();
8702 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8703 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8704 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8705 // check invalid effect chaining combinations
8706 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8707 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008708 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008709 return INVALID_OPERATION;
8710 }
8711 // remember position of first insert effect and by default
8712 // select this as insert position for new effect
8713 if (idx_insert == size) {
8714 idx_insert = i;
8715 }
8716 // remember position of last insert effect claiming
8717 // first position
8718 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8719 idx_insert_first = i;
8720 }
8721 // remember position of first insert effect claiming
8722 // last position
8723 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8724 idx_insert_last == -1) {
8725 idx_insert_last = i;
8726 }
8727 }
8728 }
8729
8730 // modify idx_insert from first position if needed
8731 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8732 if (idx_insert_last != -1) {
8733 idx_insert = idx_insert_last;
8734 } else {
8735 idx_insert = size;
8736 }
8737 } else {
8738 if (idx_insert_first != -1) {
8739 idx_insert = idx_insert_first + 1;
8740 }
8741 }
8742
8743 // always read samples from chain input buffer
8744 effect->setInBuffer(mInBuffer);
8745
8746 // if last effect in the chain, output samples to chain
8747 // output buffer, otherwise to chain input buffer
8748 if (idx_insert == size) {
8749 if (idx_insert != 0) {
8750 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8751 mEffects[idx_insert-1]->configure();
8752 }
8753 effect->setOutBuffer(mOutBuffer);
8754 } else {
8755 effect->setOutBuffer(mInBuffer);
8756 }
8757 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758
Steve Block3856b092011-10-20 11:56:00 +01008759 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760 }
8761 effect->configure();
8762 return NO_ERROR;
8763}
8764
Eric Laurentcab11242010-07-15 12:50:15 -07008765// removeEffect_l() must be called with PlaybackThread::mLock held
8766size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008767{
8768 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008769 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8771
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008772 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008773 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008774 // calling stop here will remove pre-processing effect from the audio HAL.
8775 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8776 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008777 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8778 mEffects[i]->state() == EffectModule::STOPPING) {
8779 mEffects[i]->stop();
8780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008781 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8782 delete[] effect->inBuffer();
8783 } else {
8784 if (i == size - 1 && i != 0) {
8785 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8786 mEffects[i - 1]->configure();
8787 }
8788 }
8789 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008790 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008791 break;
8792 }
8793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008794
8795 return mEffects.size();
8796}
8797
Eric Laurentcab11242010-07-15 12:50:15 -07008798// setDevice_l() must be called with PlaybackThread::mLock held
8799void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008800{
8801 size_t size = mEffects.size();
8802 for (size_t i = 0; i < size; i++) {
8803 mEffects[i]->setDevice(device);
8804 }
8805}
8806
Eric Laurentcab11242010-07-15 12:50:15 -07008807// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008808void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008809{
8810 size_t size = mEffects.size();
8811 for (size_t i = 0; i < size; i++) {
8812 mEffects[i]->setMode(mode);
8813 }
8814}
8815
Eric Laurentcab11242010-07-15 12:50:15 -07008816// setVolume_l() must be called with PlaybackThread::mLock held
8817bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818{
8819 uint32_t newLeft = *left;
8820 uint32_t newRight = *right;
8821 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008822 int ctrlIdx = -1;
8823 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824
Eric Laurentcab11242010-07-15 12:50:15 -07008825 // first update volume controller
8826 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008827 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008828 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8829 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008830 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008831 break;
8832 }
8833 }
8834
8835 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008836 if (hasControl) {
8837 *left = mNewLeftVolume;
8838 *right = mNewRightVolume;
8839 }
8840 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008841 }
8842
8843 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008844 mLeftVolume = newLeft;
8845 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008846
8847 // second get volume update from volume controller
8848 if (ctrlIdx >= 0) {
8849 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008850 mNewLeftVolume = newLeft;
8851 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852 }
8853 // then indicate volume to all other effects in chain.
8854 // Pass altered volume to effects before volume controller
8855 // and requested volume to effects after controller
8856 uint32_t lVol = newLeft;
8857 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008858
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008860 if ((int)i == ctrlIdx) continue;
8861 // this also works for ctrlIdx == -1 when there is no volume controller
8862 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863 lVol = *left;
8864 rVol = *right;
8865 }
8866 mEffects[i]->setVolume(&lVol, &rVol, false);
8867 }
8868 *left = newLeft;
8869 *right = newRight;
8870
8871 return hasControl;
8872}
8873
Mathias Agopian65ab4712010-07-14 17:59:35 -07008874status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8875{
8876 const size_t SIZE = 256;
8877 char buffer[SIZE];
8878 String8 result;
8879
8880 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8881 result.append(buffer);
8882
8883 bool locked = tryLock(mLock);
8884 // failed to lock - AudioFlinger is probably deadlocked
8885 if (!locked) {
8886 result.append("\tCould not lock mutex:\n");
8887 }
8888
Eric Laurentcab11242010-07-15 12:50:15 -07008889 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8890 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008891 mEffects.size(),
8892 (uint32_t)mInBuffer,
8893 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 mActiveTrackCnt);
8895 result.append(buffer);
8896 write(fd, result.string(), result.size());
8897
8898 for (size_t i = 0; i < mEffects.size(); ++i) {
8899 sp<EffectModule> effect = mEffects[i];
8900 if (effect != 0) {
8901 effect->dump(fd, args);
8902 }
8903 }
8904
8905 if (locked) {
8906 mLock.unlock();
8907 }
8908
8909 return NO_ERROR;
8910}
8911
Eric Laurent59255e42011-07-27 19:49:51 -07008912// must be called with ThreadBase::mLock held
8913void AudioFlinger::EffectChain::setEffectSuspended_l(
8914 const effect_uuid_t *type, bool suspend)
8915{
8916 sp<SuspendedEffectDesc> desc;
8917 // use effect type UUID timelow as key as there is no real risk of identical
8918 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008919 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008920 if (suspend) {
8921 if (index >= 0) {
8922 desc = mSuspendedEffects.valueAt(index);
8923 } else {
8924 desc = new SuspendedEffectDesc();
8925 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8926 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008927 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008928 }
8929 if (desc->mRefCount++ == 0) {
8930 sp<EffectModule> effect = getEffectIfEnabled(type);
8931 if (effect != 0) {
8932 desc->mEffect = effect;
8933 effect->setSuspended(true);
8934 effect->setEnabled(false);
8935 }
8936 }
8937 } else {
8938 if (index < 0) {
8939 return;
8940 }
8941 desc = mSuspendedEffects.valueAt(index);
8942 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008943 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008944 desc->mRefCount = 1;
8945 }
8946 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008947 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008948 if (desc->mEffect != 0) {
8949 sp<EffectModule> effect = desc->mEffect.promote();
8950 if (effect != 0) {
8951 effect->setSuspended(false);
8952 sp<EffectHandle> handle = effect->controlHandle();
8953 if (handle != 0) {
8954 effect->setEnabled(handle->enabled());
8955 }
8956 }
8957 desc->mEffect.clear();
8958 }
8959 mSuspendedEffects.removeItemsAt(index);
8960 }
8961 }
8962}
8963
8964// must be called with ThreadBase::mLock held
8965void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8966{
8967 sp<SuspendedEffectDesc> desc;
8968
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008969 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008970 if (suspend) {
8971 if (index >= 0) {
8972 desc = mSuspendedEffects.valueAt(index);
8973 } else {
8974 desc = new SuspendedEffectDesc();
8975 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008976 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008977 }
8978 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008979 Vector< sp<EffectModule> > effects;
8980 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008981 for (size_t i = 0; i < effects.size(); i++) {
8982 setEffectSuspended_l(&effects[i]->desc().type, true);
8983 }
8984 }
8985 } else {
8986 if (index < 0) {
8987 return;
8988 }
8989 desc = mSuspendedEffects.valueAt(index);
8990 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008991 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008992 desc->mRefCount = 1;
8993 }
8994 if (--desc->mRefCount == 0) {
8995 Vector<const effect_uuid_t *> types;
8996 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8997 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8998 continue;
8999 }
9000 types.add(&mSuspendedEffects.valueAt(i)->mType);
9001 }
9002 for (size_t i = 0; i < types.size(); i++) {
9003 setEffectSuspended_l(types[i], false);
9004 }
Steve Block3856b092011-10-20 11:56:00 +01009005 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009006 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9007 }
9008 }
9009}
9010
Eric Laurent6bffdb82011-09-23 08:40:41 -07009011
9012// The volume effect is used for automated tests only
9013#ifndef OPENSL_ES_H_
9014static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9015 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9016const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9017#endif //OPENSL_ES_H_
9018
Eric Laurentdb7c0792011-08-10 10:37:50 -07009019bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9020{
9021 // auxiliary effects and visualizer are never suspended on output mix
9022 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9023 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009024 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9025 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009026 return false;
9027 }
9028 return true;
9029}
9030
Glenn Kastend0539712012-01-30 12:56:03 -08009031void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009032{
Glenn Kastend0539712012-01-30 12:56:03 -08009033 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009034 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009035 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9036 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009037 }
Eric Laurent59255e42011-07-27 19:49:51 -07009038 }
Eric Laurent59255e42011-07-27 19:49:51 -07009039}
9040
9041sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9042 const effect_uuid_t *type)
9043{
Glenn Kasten090f0192012-01-30 13:00:02 -08009044 sp<EffectModule> effect = getEffectFromType_l(type);
9045 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009046}
9047
9048void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9049 bool enabled)
9050{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009051 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009052 if (enabled) {
9053 if (index < 0) {
9054 // if the effect is not suspend check if all effects are suspended
9055 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9056 if (index < 0) {
9057 return;
9058 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009059 if (!isEffectEligibleForSuspend(effect->desc())) {
9060 return;
9061 }
Eric Laurent59255e42011-07-27 19:49:51 -07009062 setEffectSuspended_l(&effect->desc().type, enabled);
9063 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009064 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009065 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009066 return;
9067 }
Eric Laurent59255e42011-07-27 19:49:51 -07009068 }
Steve Block3856b092011-10-20 11:56:00 +01009069 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009070 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009071 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9072 // if effect is requested to suspended but was not yet enabled, supend it now.
9073 if (desc->mEffect == 0) {
9074 desc->mEffect = effect;
9075 effect->setEnabled(false);
9076 effect->setSuspended(true);
9077 }
9078 } else {
9079 if (index < 0) {
9080 return;
9081 }
Steve Block3856b092011-10-20 11:56:00 +01009082 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009083 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009084 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9085 desc->mEffect.clear();
9086 effect->setSuspended(false);
9087 }
9088}
9089
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090#undef LOG_TAG
9091#define LOG_TAG "AudioFlinger"
9092
9093// ----------------------------------------------------------------------------
9094
9095status_t AudioFlinger::onTransact(
9096 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9097{
9098 return BnAudioFlinger::onTransact(code, data, reply, flags);
9099}
9100
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101}; // namespace android