blob: 21137f215f711392db4b1efabd8da17dd4e333de [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),
Glenn Kasten288ed212012-04-25 17:52:27 -07001496 // index 0 is reserved for normal mixer's submix
1497 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498{
Glenn Kasten480b4682012-02-28 12:30:08 -08001499 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001500
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 readOutputParameters();
1502
Glenn Kasten263709e2012-01-06 08:40:01 -08001503 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001504 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1505 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1506 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001507 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1508 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001510 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1511 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512}
1513
1514AudioFlinger::PlaybackThread::~PlaybackThread()
1515{
1516 delete [] mMixBuffer;
1517}
1518
1519status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1520{
1521 dumpInternals(fd, args);
1522 dumpTracks(fd, args);
1523 dumpEffectChains(fd, args);
1524 return NO_ERROR;
1525}
1526
1527status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1528{
1529 const size_t SIZE = 256;
1530 char buffer[SIZE];
1531 String8 result;
1532
Glenn Kasten58912562012-04-03 10:45:00 -07001533 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1534 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1535 const stream_type_t *st = &mStreamTypes[i];
1536 if (i > 0) {
1537 result.appendFormat(", ");
1538 }
1539 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1540 if (st->mute) {
1541 result.append("M");
1542 }
1543 }
1544 result.append("\n");
1545 write(fd, result.string(), result.length());
1546 result.clear();
1547
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1549 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001550 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 for (size_t i = 0; i < mTracks.size(); ++i) {
1552 sp<Track> track = mTracks[i];
1553 if (track != 0) {
1554 track->dump(buffer, SIZE);
1555 result.append(buffer);
1556 }
1557 }
1558
1559 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1560 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001561 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001563 sp<Track> track = mActiveTracks[i].promote();
1564 if (track != 0) {
1565 track->dump(buffer, SIZE);
1566 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 }
1568 }
1569 write(fd, result.string(), result.size());
1570 return NO_ERROR;
1571}
1572
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1574{
1575 const size_t SIZE = 256;
1576 char buffer[SIZE];
1577 String8 result;
1578
1579 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1580 result.append(buffer);
1581 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1582 result.append(buffer);
1583 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1584 result.append(buffer);
1585 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1586 result.append(buffer);
1587 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1588 result.append(buffer);
1589 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1590 result.append(buffer);
1591 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1592 result.append(buffer);
1593 write(fd, result.string(), result.size());
1594
1595 dumpBase(fd, args);
1596
1597 return NO_ERROR;
1598}
1599
1600// Thread virtuals
1601status_t AudioFlinger::PlaybackThread::readyToRun()
1602{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001603 status_t status = initCheck();
1604 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001605 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001606 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001607 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001609 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610}
1611
1612void AudioFlinger::PlaybackThread::onFirstRef()
1613{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001614 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615}
1616
1617// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001618sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001620 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001622 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001623 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 int frameCount,
1625 const sp<IMemory>& sharedBuffer,
1626 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001627 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001628 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 status_t *status)
1630{
1631 sp<Track> track;
1632 status_t lStatus;
1633
Glenn Kasten73d22752012-03-19 13:38:30 -07001634 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1635
1636 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001637 if (flags & IAudioFlinger::TRACK_FAST) {
1638 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001639 // not timed
1640 (!isTimed) &&
1641 // either of these use cases:
1642 (
1643 // use case 1: shared buffer with any frame count
1644 (
1645 (sharedBuffer != 0)
1646 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001647 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001648 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001649 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001650 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001651 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001652 )
1653 ) &&
1654 // PCM data
1655 audio_is_linear_pcm(format) &&
1656 // mono or stereo
1657 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1658 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001659#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001660 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001661 (sampleRate == mSampleRate) &&
1662#endif
1663 // normal mixer has an associated fast mixer
1664 hasFastMixer() &&
1665 // there are sufficient fast track slots available
1666 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001667 // FIXME test that MixerThread for this fast track has a capable output HAL
1668 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001669 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001670 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1671 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001672 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001673 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001674 ALOGI("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1675 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001676 } else {
1677 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001678 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1679 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1680 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1681 audio_is_linear_pcm(format),
1682 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001683 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001684 // For compatibility with AudioTrack calculation, buffer depth is forced
1685 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1686 // This is probably too conservative, but legacy application code may depend on it.
1687 // If you change this calculation, also review the start threshold which is related.
1688 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1689 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1690 if (minBufCount < 2) {
1691 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001692 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001693 int minFrameCount = mNormalFrameCount * minBufCount;
1694 if (frameCount < minFrameCount) {
1695 frameCount = minFrameCount;
1696 }
1697 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001698 }
1699
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001701 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1702 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001703 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001704 "for output %p with format %d",
1705 sampleRate, format, channelMask, mOutput, mFormat);
1706 lStatus = BAD_VALUE;
1707 goto Exit;
1708 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 }
1710 } else {
1711 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1712 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001713 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 lStatus = BAD_VALUE;
1715 goto Exit;
1716 }
1717 }
1718
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001719 lStatus = initCheck();
1720 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001721 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 goto Exit;
1723 }
1724
1725 { // scope for mLock
1726 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001727
1728 // all tracks in same audio session must share the same routing strategy otherwise
1729 // conflicts will happen when tracks are moved from one output to another by audio policy
1730 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001731 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001732 for (size_t i = 0; i < mTracks.size(); ++i) {
1733 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001734 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001735 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001736 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001737 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001738 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001739 lStatus = BAD_VALUE;
1740 goto Exit;
1741 }
1742 }
1743 }
1744
John Grossman4ff14ba2012-02-08 16:37:41 -08001745 if (!isTimed) {
1746 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001747 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001748 } else {
1749 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1750 channelMask, frameCount, sharedBuffer, sessionId);
1751 }
1752 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 lStatus = NO_MEMORY;
1754 goto Exit;
1755 }
1756 mTracks.add(track);
1757
1758 sp<EffectChain> chain = getEffectChain_l(sessionId);
1759 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001760 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001762 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001763 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001766
1767#ifdef HAVE_REQUEST_PRIORITY
1768 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1769 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1770 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1771 // so ask activity manager to do this on our behalf
1772 int err = requestPriority(callingPid, tid, 1);
1773 if (err != 0) {
1774 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1775 1, callingPid, tid, err);
1776 }
1777 }
1778#endif
1779
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 lStatus = NO_ERROR;
1781
1782Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001783 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 *status = lStatus;
1785 }
1786 return track;
1787}
1788
1789uint32_t AudioFlinger::PlaybackThread::latency() const
1790{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001791 Mutex::Autolock _l(mLock);
1792 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001793 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001794 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 return 0;
1796 }
1797}
1798
Glenn Kasten6637baa2012-01-09 09:40:36 -08001799void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001801 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803}
1804
Glenn Kasten6637baa2012-01-09 09:40:36 -08001805void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001807 Mutex::Autolock _l(mLock);
1808 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809}
1810
Glenn Kasten6637baa2012-01-09 09:40:36 -08001811void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815}
1816
Glenn Kasten6637baa2012-01-09 09:40:36 -08001817void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001819 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821}
1822
Glenn Kastenfff6d712012-01-12 16:38:12 -08001823float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001825 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 return mStreamTypes[stream].volume;
1827}
1828
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829// addTrack_l() must be called with ThreadBase::mLock held
1830status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1831{
1832 status_t status = ALREADY_EXISTS;
1833
1834 // set retry count for buffer fill
1835 track->mRetryCount = kMaxTrackStartupRetries;
1836 if (mActiveTracks.indexOf(track) < 0) {
1837 // the track is newly added, make sure it fills up all its
1838 // buffers before playing. This is to ensure the client will
1839 // effectively get the latency it requested.
1840 track->mFillingUpStatus = Track::FS_FILLING;
1841 track->mResetDone = false;
1842 mActiveTracks.add(track);
1843 if (track->mainBuffer() != mMixBuffer) {
1844 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1845 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001846 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001847 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 }
1849 }
1850
1851 status = NO_ERROR;
1852 }
1853
Steve Block3856b092011-10-20 11:56:00 +01001854 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 mWaitWorkCV.broadcast();
1856
1857 return status;
1858}
1859
1860// destroyTrack_l() must be called with ThreadBase::mLock held
1861void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1862{
1863 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001864 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001866 removeTrack_l(track);
1867 }
1868}
1869
1870void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1871{
1872 mTracks.remove(track);
1873 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001874 // redundant as track is about to be destroyed, for dumpsys only
1875 track->mName = -1;
1876 if (track->isFastTrack()) {
1877 int index = track->mFastIndex;
1878 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1879 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1880 mFastTrackAvailMask |= 1 << index;
1881 // redundant as track is about to be destroyed, for dumpsys only
1882 track->mFastIndex = -1;
1883 }
Eric Laurentb469b942011-05-09 12:09:06 -07001884 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1885 if (chain != 0) {
1886 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 }
1888}
1889
1890String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1891{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001892 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001893 char *s;
1894
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001895 Mutex::Autolock _l(mLock);
1896 if (initCheck() != NO_ERROR) {
1897 return out_s8;
1898 }
1899
Dima Zavin799a70e2011-04-18 16:57:27 -07001900 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001901 out_s8 = String8(s);
1902 free(s);
1903 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904}
1905
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001906// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1908 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001909 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910
Steve Block3856b092011-10-20 11:56:00 +01001911 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912
1913 switch (event) {
1914 case AudioSystem::OUTPUT_OPENED:
1915 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001916 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 desc.samplingRate = mSampleRate;
1918 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001919 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920 desc.latency = latency();
1921 param2 = &desc;
1922 break;
1923
1924 case AudioSystem::STREAM_CONFIG_CHANGED:
1925 param2 = &param;
1926 case AudioSystem::OUTPUT_CLOSED:
1927 default:
1928 break;
1929 }
1930 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1931}
1932
1933void AudioFlinger::PlaybackThread::readOutputParameters()
1934{
Dima Zavin799a70e2011-04-18 16:57:27 -07001935 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001936 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1937 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001938 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001939 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001940 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001941 if (mFrameCount & 15) {
1942 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1943 mFrameCount);
1944 }
1945
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001946 // Calculate size of normal mix buffer relative to the HAL output buffer size
1947 uint32_t multiple = 1;
1948 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001949 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001950 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1951 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1952 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1953 // FIXME this rounding up should not be done if no HAL SRC
1954 if ((multiple > 2) && (multiple & 1)) {
1955 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001956 }
Glenn Kasten58912562012-04-03 10:45:00 -07001957 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001958 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001959 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
1961 // FIXME - Current mixer implementation only supports stereo output: Always
1962 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001963 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001964 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1965 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966
Eric Laurentde070132010-07-13 04:45:46 -07001967 // force reconfiguration of effect chains and engines to take new buffer size and audio
1968 // parameters into account
1969 // Note that mLock is not held when readOutputParameters() is called from the constructor
1970 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1971 // matter.
1972 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1973 Vector< sp<EffectChain> > effectChains = mEffectChains;
1974 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001975 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977}
1978
1979status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1980{
Glenn Kastena0d68332012-01-27 16:47:15 -08001981 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 return BAD_VALUE;
1983 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001984 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001985 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 return INVALID_OPERATION;
1987 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001988 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989
Dima Zavin799a70e2011-04-18 16:57:27 -07001990 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991}
1992
Eric Laurent39e94f82010-07-28 01:32:47 -07001993uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994{
1995 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001996 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001998 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 }
2000
2001 for (size_t i = 0; i < mTracks.size(); ++i) {
2002 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002003 if (sessionId == track->sessionId() &&
2004 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002005 result |= TRACK_SESSION;
2006 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 }
2008 }
2009
Eric Laurent39e94f82010-07-28 01:32:47 -07002010 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011}
2012
Eric Laurentde070132010-07-13 04:45:46 -07002013uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2014{
Dima Zavinfce7a472011-04-19 22:30:36 -07002015 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002016 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002017 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2018 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002019 }
2020 for (size_t i = 0; i < mTracks.size(); i++) {
2021 sp<Track> track = mTracks[i];
2022 if (sessionId == track->sessionId() &&
2023 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002024 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002025 }
2026 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002027 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002028}
2029
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030
Glenn Kastenaed850d2012-01-26 09:46:34 -08002031AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002032{
2033 Mutex::Autolock _l(mLock);
2034 return mOutput;
2035}
2036
2037AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2038{
2039 Mutex::Autolock _l(mLock);
2040 AudioStreamOut *output = mOutput;
2041 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002042 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2043 // must push a NULL and wait for ack
2044 mOutputSink.clear();
2045 mPipeSink.clear();
2046 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002047 return output;
2048}
2049
2050// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002051audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002052{
2053 if (mOutput == NULL) {
2054 return NULL;
2055 }
2056 return &mOutput->stream->common;
2057}
2058
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002059uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002060{
2061 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2062 // decoding and transfer time. So sleeping for half of the latency would likely cause
2063 // underruns
2064 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002065 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002066 } else {
2067 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2068 }
2069}
2070
Eric Laurenta011e352012-03-29 15:51:43 -07002071status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2072{
2073 if (!isValidSyncEvent(event)) {
2074 return BAD_VALUE;
2075 }
2076
2077 Mutex::Autolock _l(mLock);
2078
2079 for (size_t i = 0; i < mTracks.size(); ++i) {
2080 sp<Track> track = mTracks[i];
2081 if (event->triggerSession() == track->sessionId()) {
2082 track->setSyncEvent(event);
2083 return NO_ERROR;
2084 }
2085 }
2086
2087 return NAME_NOT_FOUND;
2088}
2089
2090bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2091{
2092 switch (event->type()) {
2093 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2094 return true;
2095 default:
2096 break;
2097 }
2098 return false;
2099}
2100
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101// ----------------------------------------------------------------------------
2102
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002103AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002104 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002105 : PlaybackThread(audioFlinger, output, id, device, type),
2106 // mAudioMixer below
2107#ifdef SOAKER
2108 mSoaker(NULL),
2109#endif
2110 // mFastMixer below
2111 mFastMixerFutex(0)
2112 // mOutputSink below
2113 // mPipeSink below
2114 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115{
Glenn Kasten58912562012-04-03 10:45:00 -07002116 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2117 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2118 "mFrameCount=%d, mNormalFrameCount=%d",
2119 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2120 mNormalFrameCount);
2121 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2122
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 // FIXME - Current mixer implementation only supports stereo output
2124 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002125 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 }
Glenn Kasten58912562012-04-03 10:45:00 -07002127
2128 // create an NBAIO sink for the HAL output stream, and negotiate
2129 mOutputSink = new AudioStreamOutSink(output->stream);
2130 size_t numCounterOffers = 0;
2131 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2132 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2133 ALOG_ASSERT(index == 0);
2134
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002135 // initialize fast mixer depending on configuration
2136 bool initFastMixer;
2137 switch (kUseFastMixer) {
2138 case FastMixer_Never:
2139 initFastMixer = false;
2140 break;
2141 case FastMixer_Always:
2142 initFastMixer = true;
2143 break;
2144 case FastMixer_Static:
2145 case FastMixer_Dynamic:
2146 initFastMixer = mFrameCount < mNormalFrameCount;
2147 break;
2148 }
2149 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002150
2151 // create a MonoPipe to connect our submix to FastMixer
2152 NBAIO_Format format = mOutputSink->format();
2153 // frame count will be rounded up to a power of 2, so this formula should work well
2154 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2155 true /*writeCanBlock*/);
2156 const NBAIO_Format offers[1] = {format};
2157 size_t numCounterOffers = 0;
2158 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2159 ALOG_ASSERT(index == 0);
2160 mPipeSink = monoPipe;
2161
2162#ifdef SOAKER
2163 // create a soaker as workaround for governor issues
2164 mSoaker = new Soaker();
2165 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2166 mSoaker->run("Soaker", PRIORITY_LOWEST);
2167#endif
2168
2169 // create fast mixer and configure it initially with just one fast track for our submix
2170 mFastMixer = new FastMixer();
2171 FastMixerStateQueue *sq = mFastMixer->sq();
2172 FastMixerState *state = sq->begin();
2173 FastTrack *fastTrack = &state->mFastTracks[0];
2174 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2175 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2176 fastTrack->mVolumeProvider = NULL;
2177 fastTrack->mGeneration++;
2178 state->mFastTracksGen++;
2179 state->mTrackMask = 1;
2180 // fast mixer will use the HAL output sink
2181 state->mOutputSink = mOutputSink.get();
2182 state->mOutputSinkGen++;
2183 state->mFrameCount = mFrameCount;
2184 state->mCommand = FastMixerState::COLD_IDLE;
2185 // already done in constructor initialization list
2186 //mFastMixerFutex = 0;
2187 state->mColdFutexAddr = &mFastMixerFutex;
2188 state->mColdGen++;
2189 state->mDumpState = &mFastMixerDumpState;
2190 sq->end();
2191 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2192
2193 // start the fast mixer
2194 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2195#ifdef HAVE_REQUEST_PRIORITY
2196 pid_t tid = mFastMixer->getTid();
2197 int err = requestPriority(getpid_cached, tid, 2);
2198 if (err != 0) {
2199 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2200 2, getpid_cached, tid, err);
2201 }
2202#endif
2203
2204 } else {
2205 mFastMixer = NULL;
2206 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002207
2208 switch (kUseFastMixer) {
2209 case FastMixer_Never:
2210 case FastMixer_Dynamic:
2211 mNormalSink = mOutputSink;
2212 break;
2213 case FastMixer_Always:
2214 mNormalSink = mPipeSink;
2215 break;
2216 case FastMixer_Static:
2217 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2218 break;
2219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220}
2221
2222AudioFlinger::MixerThread::~MixerThread()
2223{
Glenn Kasten58912562012-04-03 10:45:00 -07002224 if (mFastMixer != NULL) {
2225 FastMixerStateQueue *sq = mFastMixer->sq();
2226 FastMixerState *state = sq->begin();
2227 if (state->mCommand == FastMixerState::COLD_IDLE) {
2228 int32_t old = android_atomic_inc(&mFastMixerFutex);
2229 if (old == -1) {
2230 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2231 }
2232 }
2233 state->mCommand = FastMixerState::EXIT;
2234 sq->end();
2235 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2236 mFastMixer->join();
2237 // Though the fast mixer thread has exited, it's state queue is still valid.
2238 // We'll use that extract the final state which contains one remaining fast track
2239 // corresponding to our sub-mix.
2240 state = sq->begin();
2241 ALOG_ASSERT(state->mTrackMask == 1);
2242 FastTrack *fastTrack = &state->mFastTracks[0];
2243 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2244 delete fastTrack->mBufferProvider;
2245 sq->end(false /*didModify*/);
2246 delete mFastMixer;
2247#ifdef SOAKER
2248 if (mSoaker != NULL) {
2249 mSoaker->requestExitAndWait();
2250 }
2251 delete mSoaker;
2252#endif
2253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 delete mAudioMixer;
2255}
2256
Glenn Kasten83efdd02012-02-24 07:21:32 -08002257class CpuStats {
2258public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002259 CpuStats();
2260 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002261#ifdef DEBUG_CPU_USAGE
2262private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002263 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2264 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2265
2266 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2267
2268 int mCpuNum; // thread's current CPU number
2269 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002270#endif
2271};
2272
Glenn Kasten190a46f2012-03-06 11:27:10 -08002273CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002274#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002275 : mCpuNum(-1), mCpukHz(-1)
2276#endif
2277{
2278}
2279
2280void CpuStats::sample(const String8 &title) {
2281#ifdef DEBUG_CPU_USAGE
2282 // get current thread's delta CPU time in wall clock ns
2283 double wcNs;
2284 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2285
2286 // record sample for wall clock statistics
2287 if (valid) {
2288 mWcStats.sample(wcNs);
2289 }
2290
2291 // get the current CPU number
2292 int cpuNum = sched_getcpu();
2293
2294 // get the current CPU frequency in kHz
2295 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2296
2297 // check if either CPU number or frequency changed
2298 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2299 mCpuNum = cpuNum;
2300 mCpukHz = cpukHz;
2301 // ignore sample for purposes of cycles
2302 valid = false;
2303 }
2304
2305 // if no change in CPU number or frequency, then record sample for cycle statistics
2306 if (valid && mCpukHz > 0) {
2307 double cycles = wcNs * cpukHz * 0.000001;
2308 mHzStats.sample(cycles);
2309 }
2310
2311 unsigned n = mWcStats.n();
2312 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002313 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002314 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002315 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2316 double perLoop = elapsed / (double) n;
2317 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002318 double perLoop1k = perLoop * 0.001;
2319 double mean = mWcStats.mean();
2320 double stddev = mWcStats.stddev();
2321 double minimum = mWcStats.minimum();
2322 double maximum = mWcStats.maximum();
2323 double meanCycles = mHzStats.mean();
2324 double stddevCycles = mHzStats.stddev();
2325 double minCycles = mHzStats.minimum();
2326 double maxCycles = mHzStats.maximum();
2327 mCpuUsage.resetElapsed();
2328 mWcStats.reset();
2329 mHzStats.reset();
2330 ALOGD("CPU usage for %s over past %.1f secs\n"
2331 " (%u mixer loops at %.1f mean ms per loop):\n"
2332 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2333 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2334 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2335 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002336 elapsed * .000000001, n, perLoop * .000001,
2337 mean * .001,
2338 stddev * .001,
2339 minimum * .001,
2340 maximum * .001,
2341 mean / perLoop100,
2342 stddev / perLoop100,
2343 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002344 maximum / perLoop100,
2345 meanCycles / perLoop1k,
2346 stddevCycles / perLoop1k,
2347 minCycles / perLoop1k,
2348 maxCycles / perLoop1k);
2349
Glenn Kasten83efdd02012-02-24 07:21:32 -08002350 }
2351 }
2352#endif
2353};
2354
Glenn Kasten37d825e2012-02-24 07:21:48 -08002355void AudioFlinger::PlaybackThread::checkSilentMode_l()
2356{
2357 if (!mMasterMute) {
2358 char value[PROPERTY_VALUE_MAX];
2359 if (property_get("ro.audio.silent", value, "0") > 0) {
2360 char *endptr;
2361 unsigned long ul = strtoul(value, &endptr, 0);
2362 if (*endptr == '\0' && ul != 0) {
2363 ALOGD("Silence is golden");
2364 // The setprop command will not allow a property to be changed after
2365 // the first time it is set, so we don't have to worry about un-muting.
2366 setMasterMute_l(true);
2367 }
2368 }
2369 }
2370}
2371
Glenn Kasten000f0e32012-03-01 17:10:56 -08002372bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373{
2374 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002375
Glenn Kasten000f0e32012-03-01 17:10:56 -08002376 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002377
2378 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002380if (mType == MIXER) {
2381 longStandbyExit = false;
2382}
Glenn Kasten688a6402012-02-29 07:57:06 -08002383
Glenn Kasten000f0e32012-03-01 17:10:56 -08002384 // DUPLICATING
2385 // FIXME could this be made local to while loop?
2386 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002387
Glenn Kasten66fcab92012-02-24 14:59:21 -08002388 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002389 sleepTime = idleSleepTime;
2390
2391if (mType == MIXER) {
2392 sleepTimeShift = 0;
2393}
2394
Glenn Kasten83efdd02012-02-24 07:21:32 -08002395 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002396 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397
Eric Laurentfeb0db62011-07-22 09:04:31 -07002398 acquireWakeLock();
2399
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 while (!exitPending())
2401 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002402 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002403
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002404 Vector< sp<EffectChain> > effectChains;
2405
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 processConfigEvents();
2407
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 { // scope for mLock
2409
2410 Mutex::Autolock _l(mLock);
2411
2412 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002413 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 }
2415
Glenn Kastenfa26a852012-03-06 11:28:04 -08002416 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002417
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002419 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002420 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002422
2423 threadLoop_standby();
2424
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 mStandby = true;
2426 mBytesWritten = 0;
2427 }
2428
Glenn Kasten3e074702012-02-28 18:40:35 -08002429 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 // we're about to wait, flush the binder command buffer
2431 IPCThreadState::self()->flushCommands();
2432
Glenn Kastenfa26a852012-03-06 11:28:04 -08002433 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002434
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 if (exitPending()) break;
2436
Eric Laurentfeb0db62011-07-22 09:04:31 -07002437 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002439 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002441 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002442 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443
Eric Laurentda747442012-04-25 18:53:13 -07002444 mMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002445
Glenn Kasten37d825e2012-02-24 07:21:48 -08002446 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447
Glenn Kasten000f0e32012-03-01 17:10:56 -08002448 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002450 if (mType == MIXER) {
2451 sleepTimeShift = 0;
2452 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002453
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 continue;
2455 }
2456 }
2457
Eric Laurentda747442012-04-25 18:53:13 -07002458 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459
2460 // prevent any changes in effect chain list and in each effect chain
2461 // during mixing and effect process as the audio buffers could be deleted
2462 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002463 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465
Glenn Kastenfec279f2012-03-08 07:47:15 -08002466 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002467 threadLoop_mix();
2468 } else {
2469 threadLoop_sleepTime();
2470 }
2471
2472 if (mSuspended > 0) {
2473 sleepTime = suspendSleepTimeUs();
2474 }
2475
2476 // only process effects if we're going to write
2477 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002478 for (size_t i = 0; i < effectChains.size(); i ++) {
2479 effectChains[i]->process_l();
2480 }
2481 }
2482
2483 // enable changes in effect chain
2484 unlockEffectChains(effectChains);
2485
2486 // sleepTime == 0 means we must write to audio hardware
2487 if (sleepTime == 0) {
2488
2489 threadLoop_write();
2490
2491if (mType == MIXER) {
2492 // write blocked detection
2493 nsecs_t now = systemTime();
2494 nsecs_t delta = now - mLastWriteTime;
2495 if (!mStandby && delta > maxPeriod) {
2496 mNumDelayedWrites++;
2497 if ((now - lastWarning) > kWarningThrottleNs) {
2498 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2499 ns2ms(delta), mNumDelayedWrites, this);
2500 lastWarning = now;
2501 }
2502 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2503 // a different threshold. Or completely removed for what it is worth anyway...
2504 if (mStandby) {
2505 longStandbyExit = true;
2506 }
2507 }
2508}
2509
2510 mStandby = false;
2511 } else {
2512 usleep(sleepTime);
2513 }
2514
Glenn Kasten58912562012-04-03 10:45:00 -07002515 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002516 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002517 // same lock. This will also mutate and push a new fast mixer state.
2518 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002519 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520
Glenn Kastenfa26a852012-03-06 11:28:04 -08002521 // FIXME I don't understand the need for this here;
2522 // it was in the original code but maybe the
2523 // assignment in saveOutputTracks() makes this unnecessary?
2524 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525
2526 // Effect chains will be actually deleted here if they were removed from
2527 // mEffectChains list during mixing or effects processing
2528 effectChains.clear();
2529
2530 // FIXME Note that the above .clear() is no longer necessary since effectChains
2531 // is now local to this block, but will keep it for now (at least until merge done).
2532 }
2533
2534if (mType == MIXER || mType == DIRECT) {
2535 // put output stream into standby mode
2536 if (!mStandby) {
2537 mOutput->stream->common.standby(&mOutput->stream->common);
2538 }
2539}
2540if (mType == DUPLICATING) {
2541 // for DuplicatingThread, standby mode is handled by the outputTracks
2542}
2543
2544 releaseWakeLock();
2545
2546 ALOGV("Thread %p type %d exiting", this, mType);
2547 return false;
2548}
2549
Glenn Kasten288ed212012-04-25 17:52:27 -07002550// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002551void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2552{
Glenn Kasten58912562012-04-03 10:45:00 -07002553 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2554}
2555
2556void AudioFlinger::MixerThread::threadLoop_write()
2557{
2558 // FIXME we should only do one push per cycle; confirm this is true
2559 // Start the fast mixer if it's not already running
2560 if (mFastMixer != NULL) {
2561 FastMixerStateQueue *sq = mFastMixer->sq();
2562 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002563 if (state->mCommand != FastMixerState::MIX_WRITE &&
2564 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002565 if (state->mCommand == FastMixerState::COLD_IDLE) {
2566 int32_t old = android_atomic_inc(&mFastMixerFutex);
2567 if (old == -1) {
2568 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2569 }
2570 }
2571 state->mCommand = FastMixerState::MIX_WRITE;
2572 sq->end();
2573 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002574 if (kUseFastMixer == FastMixer_Dynamic) {
2575 mNormalSink = mPipeSink;
2576 }
Glenn Kasten58912562012-04-03 10:45:00 -07002577 } else {
2578 sq->end(false /*didModify*/);
2579 }
2580 }
2581 PlaybackThread::threadLoop_write();
2582}
2583
Glenn Kasten000f0e32012-03-01 17:10:56 -08002584// shared by MIXER and DIRECT, overridden by DUPLICATING
2585void AudioFlinger::PlaybackThread::threadLoop_write()
2586{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002587 // FIXME rewrite to reduce number of system calls
2588 mLastWriteTime = systemTime();
2589 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002590
Glenn Kasten58912562012-04-03 10:45:00 -07002591#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002592 size_t count = mixBufferSize >> mBitShift;
2593 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2594 if (framesWritten > 0) {
2595 size_t bytesWritten = framesWritten << mBitShift;
2596 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002597 }
2598
Glenn Kasten952eeb22012-03-06 11:30:57 -08002599 mNumWrites++;
2600 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002601}
2602
Glenn Kasten58912562012-04-03 10:45:00 -07002603void AudioFlinger::MixerThread::threadLoop_standby()
2604{
2605 // Idle the fast mixer if it's currently running
2606 if (mFastMixer != NULL) {
2607 FastMixerStateQueue *sq = mFastMixer->sq();
2608 FastMixerState *state = sq->begin();
2609 if (!(state->mCommand & FastMixerState::IDLE)) {
2610 state->mCommand = FastMixerState::COLD_IDLE;
2611 state->mColdFutexAddr = &mFastMixerFutex;
2612 state->mColdGen++;
2613 mFastMixerFutex = 0;
2614 sq->end();
2615 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2616 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002617 if (kUseFastMixer == FastMixer_Dynamic) {
2618 mNormalSink = mOutputSink;
2619 }
Glenn Kasten58912562012-04-03 10:45:00 -07002620 } else {
2621 sq->end(false /*didModify*/);
2622 }
2623 }
2624 PlaybackThread::threadLoop_standby();
2625}
2626
Glenn Kasten000f0e32012-03-01 17:10:56 -08002627// shared by MIXER and DIRECT, overridden by DUPLICATING
2628void AudioFlinger::PlaybackThread::threadLoop_standby()
2629{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002630 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2631 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002632}
2633
2634void AudioFlinger::MixerThread::threadLoop_mix()
2635{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002636 // obtain the presentation timestamp of the next output buffer
2637 int64_t pts;
2638 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002639
Glenn Kasten952eeb22012-03-06 11:30:57 -08002640 if (NULL != mOutput->stream->get_next_write_timestamp) {
2641 status = mOutput->stream->get_next_write_timestamp(
2642 mOutput->stream, &pts);
2643 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002644
Glenn Kasten952eeb22012-03-06 11:30:57 -08002645 if (status != NO_ERROR) {
2646 pts = AudioBufferProvider::kInvalidPTS;
2647 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002648
Glenn Kasten952eeb22012-03-06 11:30:57 -08002649 // mix buffers...
2650 mAudioMixer->process(pts);
2651 // increase sleep time progressively when application underrun condition clears.
2652 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2653 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2654 // such that we would underrun the audio HAL.
2655 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2656 sleepTimeShift--;
2657 }
2658 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002659 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002660 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002661}
2662
2663void AudioFlinger::MixerThread::threadLoop_sleepTime()
2664{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002665 // If no tracks are ready, sleep once for the duration of an output
2666 // buffer size, then write 0s to the output
2667 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002668 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002669 sleepTime = activeSleepTime >> sleepTimeShift;
2670 if (sleepTime < kMinThreadSleepTimeUs) {
2671 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002673 // reduce sleep time in case of consecutive application underruns to avoid
2674 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2675 // duration we would end up writing less data than needed by the audio HAL if
2676 // the condition persists.
2677 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2678 sleepTimeShift++;
2679 }
2680 } else {
2681 sleepTime = idleSleepTime;
2682 }
2683 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002684 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002685 memset (mMixBuffer, 0, mixBufferSize);
2686 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002687 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002688 }
2689 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690}
2691
2692// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002693AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002694 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695{
2696
Glenn Kasten29c23c32012-01-26 13:37:52 -08002697 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002699 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 size_t mixedTracks = 0;
2701 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002702 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002703 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002704 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705
2706 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002707 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708
Eric Laurent571d49c2010-08-11 05:20:11 -07002709 if (masterMute) {
2710 masterVolume = 0;
2711 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002713 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002715 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002716 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 masterVolume = (float)((v + (1 << 23)) >> 24);
2718 chain.clear();
2719 }
2720
Glenn Kasten288ed212012-04-25 17:52:27 -07002721 // prepare a new state to push
2722 FastMixerStateQueue *sq = NULL;
2723 FastMixerState *state = NULL;
2724 bool didModify = false;
2725 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2726 if (mFastMixer != NULL) {
2727 sq = mFastMixer->sq();
2728 state = sq->begin();
2729 }
2730
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002732 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 if (t == 0) continue;
2734
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002735 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002737
Glenn Kasten288ed212012-04-25 17:52:27 -07002738 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002739 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002740
2741 // It's theoretically possible (though unlikely) for a fast track to be created
2742 // and then removed within the same normal mix cycle. This is not a problem, as
2743 // the track never becomes active so it's fast mixer slot is never touched.
2744 // The converse, of removing an (active) track and then creating a new track
2745 // at the identical fast mixer slot within the same normal mix cycle,
2746 // is impossible because the slot isn't marked available until the end of each cycle.
2747 int j = track->mFastIndex;
2748 FastTrack *fastTrack = &state->mFastTracks[j];
2749
2750 // Determine whether the track is currently in underrun condition,
2751 // and whether it had a recent underrun.
2752 uint32_t underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2753 uint32_t recentUnderruns = (underruns - (track->mObservedUnderruns & ~1)) >> 1;
2754 // don't count underruns that occur while stopping or pausing
2755 if (!(track->isStopped() || track->isPausing())) {
2756 track->mUnderrunCount += recentUnderruns;
2757 }
2758 track->mObservedUnderruns = underruns;
2759
2760 // This is similar to the formula for normal tracks,
2761 // with a few modifications for fast tracks.
2762 bool isActive;
2763 if (track->isStopped()) {
2764 // track stays active after stop() until first underrun
2765 isActive = recentUnderruns == 0;
2766 } else if (track->isPaused() || track->isTerminated()) {
2767 isActive = false;
2768 } else if (track->isPausing()) {
2769 // ramp down is not yet implemented
2770 isActive = true;
2771 track->setPaused();
2772 } else if (track->isResuming()) {
2773 // ramp up is not yet implemented
2774 isActive = true;
2775 track->mState = TrackBase::ACTIVE;
2776 } else {
2777 // no minimum frame count for fast tracks; continual underrun is allowed,
2778 // but later could implement automatic pause after several consecutive underruns,
2779 // or auto-mute yet still consider the track active and continue to service it
2780 isActive = true;
2781 }
2782
2783 if (isActive) {
2784 // was it previously inactive?
2785 if (!(state->mTrackMask & (1 << j))) {
2786 ExtendedAudioBufferProvider *eabp = track;
2787 VolumeProvider *vp = track;
2788 fastTrack->mBufferProvider = eabp;
2789 fastTrack->mVolumeProvider = vp;
2790 fastTrack->mSampleRate = track->mSampleRate;
2791 fastTrack->mChannelMask = track->mChannelMask;
2792 fastTrack->mGeneration++;
2793 state->mTrackMask |= 1 << j;
2794 didModify = true;
2795 // no acknowledgement required for newly active tracks
2796 }
2797 // cache the combined master volume and stream type volume for fast mixer; this
2798 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2799 track->mCachedVolume = track->isMuted() ?
2800 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2801 ++fastTracks;
2802 } else {
2803 // was it previously active?
2804 if (state->mTrackMask & (1 << j)) {
2805 fastTrack->mBufferProvider = NULL;
2806 fastTrack->mGeneration++;
2807 state->mTrackMask &= ~(1 << j);
2808 didModify = true;
2809 // If any fast tracks were removed, we must wait for acknowledgement
2810 // because we're about to decrement the last sp<> on those tracks.
2811 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2812 }
2813 // Remainder of this block is copied from similar code for normal tracks
2814 if (track->isStopped()) {
2815 // Can't reset directly, as fast mixer is still polling this track
2816 // track->reset();
2817 // So instead mark this track as needing to be reset after push with ack
2818 resetMask |= 1 << i;
2819 }
2820 // This would be incomplete if we auto-paused on underrun
2821 size_t audioHALFrames =
2822 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2823 size_t framesWritten =
2824 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2825 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2826 tracksToRemove->add(track);
2827 }
2828 // Avoids a misleading display in dumpsys
2829 track->mObservedUnderruns &= ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07002830 }
2831 continue;
2832 }
2833
2834 { // local variable scope to avoid goto warning
2835
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 audio_track_cblk_t* cblk = track->cblk();
2837
2838 // The first time a track is added we wait
2839 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002840 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002841 // make sure that we have enough frames to mix one full buffer.
2842 // enforce this condition only once to enable draining the buffer in case the client
2843 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002844 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002845 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002846 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002847 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Eric Laurentda747442012-04-25 18:53:13 -07002848 (mMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002849 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002850 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002851 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002852 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002853 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002854 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002855 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002856 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2857 // the minimum track buffer size is normally twice the number of frames necessary
2858 // to fill one buffer and the resampler should not leave more than one buffer worth
2859 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002860 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002861 }
2862 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002863 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 !track->isPaused() && !track->isTerminated())
2865 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002866 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867
2868 mixedTracks++;
2869
2870 // track->mainBuffer() != mMixBuffer means there is an effect chain
2871 // connected to the track
2872 chain.clear();
2873 if (track->mainBuffer() != mMixBuffer) {
2874 chain = getEffectChain_l(track->sessionId());
2875 // Delegate volume control to effect in track effect chain if needed
2876 if (chain != 0) {
2877 tracksWithEffect++;
2878 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002879 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002880 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 }
2882 }
2883
2884
2885 int param = AudioMixer::VOLUME;
2886 if (track->mFillingUpStatus == Track::FS_FILLED) {
2887 // no ramp for the first volume setting
2888 track->mFillingUpStatus = Track::FS_ACTIVE;
2889 if (track->mState == TrackBase::RESUMING) {
2890 track->mState = TrackBase::ACTIVE;
2891 param = AudioMixer::RAMP_VOLUME;
2892 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002893 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 } else if (cblk->server != 0) {
2895 // If the track is stopped before the first frame was mixed,
2896 // do not apply ramp
2897 param = AudioMixer::RAMP_VOLUME;
2898 }
2899
2900 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002901 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002902 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002903 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002904 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 if (track->isPausing()) {
2906 track->setPaused();
2907 }
2908 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002909
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002911 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002913 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002914 vl = vlr & 0xFFFF;
2915 vr = vlr >> 16;
2916 // track volumes come from shared memory, so can't be trusted and must be clamped
2917 if (vl > MAX_GAIN_INT) {
2918 ALOGV("Track left volume out of range: %04X", vl);
2919 vl = MAX_GAIN_INT;
2920 }
2921 if (vr > MAX_GAIN_INT) {
2922 ALOGV("Track right volume out of range: %04X", vr);
2923 vr = MAX_GAIN_INT;
2924 }
2925 // now apply the master volume and stream type volume
2926 vl = (uint32_t)(v * vl) << 12;
2927 vr = (uint32_t)(v * vr) << 12;
2928 // assuming master volume and stream type volume each go up to 1.0,
2929 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930
Glenn Kasten05632a52012-01-03 14:22:33 -08002931 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2932 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002933 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002934 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002935 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002936 }
2937 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002939 // Delegate volume control to effect in track effect chain if needed
2940 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2941 // Do not ramp volume if volume is controlled by effect
2942 param = AudioMixer::VOLUME;
2943 track->mHasVolumeController = true;
2944 } else {
2945 // force no volume ramp when volume controller was just disabled or removed
2946 // from effect chain to avoid volume spike
2947 if (track->mHasVolumeController) {
2948 param = AudioMixer::VOLUME;
2949 }
2950 track->mHasVolumeController = false;
2951 }
2952
2953 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002954 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002955 vl = (vl + (1 << 11)) >> 12;
2956 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2957 vr = (vr + (1 << 11)) >> 12;
2958 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002959
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002960 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 -07002961
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002963 mAudioMixer->setBufferProvider(name, track);
2964 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002966 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2967 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2968 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002970 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 AudioMixer::TRACK,
2972 AudioMixer::FORMAT, (void *)track->format());
2973 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002974 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002976 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002978 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 AudioMixer::RESAMPLE,
2980 AudioMixer::SAMPLE_RATE,
2981 (void *)(cblk->sampleRate));
2982 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002983 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 AudioMixer::TRACK,
2985 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2986 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002987 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 AudioMixer::TRACK,
2989 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2990
2991 // reset retry count
2992 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002993
Eric Laurent27741442012-01-17 19:20:12 -08002994 // If one track is ready, set the mixer ready if:
2995 // - the mixer was not ready during previous round OR
2996 // - no other track is not ready
Eric Laurentda747442012-04-25 18:53:13 -07002997 if (mMixerStatus != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08002998 mixerStatus != MIXER_TRACKS_ENABLED) {
2999 mixerStatus = MIXER_TRACKS_READY;
3000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003002 //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 -07003003 if (track->isStopped()) {
3004 track->reset();
3005 }
Eric Laurent83faee02012-04-27 18:24:29 -07003006 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3007 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 // We have consumed all the buffers of this track.
3009 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003010 // TODO: use actual buffer filling status instead of latency when available from
3011 // audio HAL
3012 size_t audioHALFrames =
3013 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3014 size_t framesWritten =
3015 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3016 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3017 tracksToRemove->add(track);
3018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 } else {
3020 // No buffers for this track. Give it a few chances to
3021 // fill a buffer, then remove it from active list.
3022 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003023 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003025 // indicate to client process that the track was disabled because of underrun;
3026 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003027 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003028 // If one track is not ready, mark the mixer also not ready if:
3029 // - the mixer was ready during previous round OR
3030 // - no other track is ready
Eric Laurentda747442012-04-25 18:53:13 -07003031 } else if (mMixerStatus == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003032 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 mixerStatus = MIXER_TRACKS_ENABLED;
3034 }
3035 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003036 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
Glenn Kasten58912562012-04-03 10:45:00 -07003038
3039 } // local variable scope to avoid goto warning
3040track_is_ready: ;
3041
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 }
3043
Glenn Kasten288ed212012-04-25 17:52:27 -07003044 // Push the new FastMixer state if necessary
3045 if (didModify) {
3046 state->mFastTracksGen++;
3047 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3048 if (kUseFastMixer == FastMixer_Dynamic &&
3049 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3050 state->mCommand = FastMixerState::COLD_IDLE;
3051 state->mColdFutexAddr = &mFastMixerFutex;
3052 state->mColdGen++;
3053 mFastMixerFutex = 0;
3054 if (kUseFastMixer == FastMixer_Dynamic) {
3055 mNormalSink = mOutputSink;
3056 }
3057 // If we go into cold idle, need to wait for acknowledgement
3058 // so that fast mixer stops doing I/O.
3059 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3060 }
3061 sq->end();
3062 }
3063 if (sq != NULL) {
3064 sq->end(didModify);
3065 sq->push(block);
3066 }
3067
3068 // Now perform the deferred reset on fast tracks that have stopped
3069 while (resetMask != 0) {
3070 size_t i = __builtin_ctz(resetMask);
3071 ALOG_ASSERT(i < count);
3072 resetMask &= ~(1 << i);
3073 sp<Track> t = mActiveTracks[i].promote();
3074 if (t == 0) continue;
3075 Track* track = t.get();
3076 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3077 track->reset();
3078 }
Glenn Kasten58912562012-04-03 10:45:00 -07003079
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080 // remove all the tracks that need to be...
3081 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003082 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 for (size_t i=0 ; i<count ; i++) {
3084 const sp<Track>& track = tracksToRemove->itemAt(i);
3085 mActiveTracks.remove(track);
3086 if (track->mainBuffer() != mMixBuffer) {
3087 chain = getEffectChain_l(track->sessionId());
3088 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003089 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003090 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 }
3092 }
3093 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003094 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 }
3096 }
3097 }
3098
3099 // mix buffer must be cleared if all tracks are connected to an
3100 // effect chain as in this case the mixer will not write to
3101 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003102 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3103 // FIXME as a performance optimization, should remember previous zero status
3104 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
3106
Glenn Kasten58912562012-04-03 10:45:00 -07003107 // if any fast tracks, then status is ready
3108 if (fastTracks > 0) {
3109 mixerStatus = MIXER_TRACKS_READY;
3110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111 return mixerStatus;
3112}
3113
Glenn Kasten66fcab92012-02-24 14:59:21 -08003114/*
3115The derived values that are cached:
3116 - mixBufferSize from frame count * frame size
3117 - activeSleepTime from activeSleepTimeUs()
3118 - idleSleepTime from idleSleepTimeUs()
3119 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3120 - maxPeriod from frame count and sample rate (MIXER only)
3121
3122The parameters that affect these derived values are:
3123 - frame count
3124 - frame size
3125 - sample rate
3126 - device type: A2DP or not
3127 - device latency
3128 - format: PCM or not
3129 - active sleep time
3130 - idle sleep time
3131*/
3132
3133void AudioFlinger::PlaybackThread::cacheParameters_l()
3134{
Glenn Kasten58912562012-04-03 10:45:00 -07003135 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003136 activeSleepTime = activeSleepTimeUs();
3137 idleSleepTime = idleSleepTimeUs();
3138}
3139
Glenn Kastenfff6d712012-01-12 16:38:12 -08003140void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141{
Steve Block3856b092011-10-20 11:56:00 +01003142 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003143 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003145
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 size_t size = mTracks.size();
3147 for (size_t i = 0; i < size; i++) {
3148 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003149 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003150 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 }
3153 }
3154}
3155
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003157int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003159 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160}
3161
3162// deleteTrackName_l() must be called with ThreadBase::mLock held
3163void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3164{
Steve Block3856b092011-10-20 11:56:00 +01003165 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 mAudioMixer->deleteTrackName(name);
3167}
3168
3169// checkForNewParameters_l() must be called with ThreadBase::mLock held
3170bool AudioFlinger::MixerThread::checkForNewParameters_l()
3171{
Glenn Kasten58912562012-04-03 10:45:00 -07003172 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3173 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 bool reconfig = false;
3175
3176 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003177
3178 if (mFastMixer != NULL) {
3179 FastMixerStateQueue *sq = mFastMixer->sq();
3180 FastMixerState *state = sq->begin();
3181 if (!(state->mCommand & FastMixerState::IDLE)) {
3182 previousCommand = state->mCommand;
3183 state->mCommand = FastMixerState::HOT_IDLE;
3184 sq->end();
3185 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3186 } else {
3187 sq->end(false /*didModify*/);
3188 }
3189 }
3190
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 status_t status = NO_ERROR;
3192 String8 keyValuePair = mNewParameters[0];
3193 AudioParameter param = AudioParameter(keyValuePair);
3194 int value;
3195
3196 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3197 reconfig = true;
3198 }
3199 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003200 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 status = BAD_VALUE;
3202 } else {
3203 reconfig = true;
3204 }
3205 }
3206 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003207 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 status = BAD_VALUE;
3209 } else {
3210 reconfig = true;
3211 }
3212 }
3213 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3214 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003215 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 // if frame count is changed after track creation
3217 if (!mTracks.isEmpty()) {
3218 status = INVALID_OPERATION;
3219 } else {
3220 reconfig = true;
3221 }
3222 }
3223 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003224#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003225 // when changing the audio output device, call addBatteryData to notify
3226 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003227 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003228 uint32_t params = 0;
3229 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003230 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003231 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3232 }
3233
3234 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003235 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003236 // check if any other device (except speaker) is on
3237 if (value & deviceWithoutSpeaker ) {
3238 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3239 }
3240
3241 if (params != 0) {
3242 addBatteryData(params);
3243 }
3244 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003245#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003246
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 // forward device change to effects that have requested to be
3248 // aware of attached audio device.
3249 mDevice = (uint32_t)value;
3250 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003251 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 }
3253 }
3254
3255 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003256 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003257 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003259 mOutput->stream->common.standby(&mOutput->stream->common);
3260 mStandby = true;
3261 mBytesWritten = 0;
3262 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003263 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 }
3265 if (status == NO_ERROR && reconfig) {
3266 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003267 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3268 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003270 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003272 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 if (name < 0) break;
3274 mTracks[i]->mName = name;
3275 // limit track sample rate to 2 x new output sample rate
3276 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3277 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3278 }
3279 }
3280 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3281 }
3282 }
3283
3284 mNewParameters.removeAt(0);
3285
3286 mParamStatus = status;
3287 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003288 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3289 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003290 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 }
Glenn Kasten58912562012-04-03 10:45:00 -07003292
3293 if (!(previousCommand & FastMixerState::IDLE)) {
3294 ALOG_ASSERT(mFastMixer != NULL);
3295 FastMixerStateQueue *sq = mFastMixer->sq();
3296 FastMixerState *state = sq->begin();
3297 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3298 state->mCommand = previousCommand;
3299 sq->end();
3300 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3301 }
3302
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 return reconfig;
3304}
3305
3306status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3307{
3308 const size_t SIZE = 256;
3309 char buffer[SIZE];
3310 String8 result;
3311
3312 PlaybackThread::dumpInternals(fd, args);
3313
3314 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3315 result.append(buffer);
3316 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003317
3318 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3319 FastMixerDumpState copy = mFastMixerDumpState;
3320 copy.dump(fd);
3321
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322 return NO_ERROR;
3323}
3324
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003325uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326{
Glenn Kasten58912562012-04-03 10:45:00 -07003327 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328}
3329
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003330uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003331{
Glenn Kasten58912562012-04-03 10:45:00 -07003332 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003333}
3334
Glenn Kasten66fcab92012-02-24 14:59:21 -08003335void AudioFlinger::MixerThread::cacheParameters_l()
3336{
3337 PlaybackThread::cacheParameters_l();
3338
3339 // FIXME: Relaxed timing because of a certain device that can't meet latency
3340 // Should be reduced to 2x after the vendor fixes the driver issue
3341 // increase threshold again due to low power audio mode. The way this warning
3342 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003343 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003344}
3345
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003347AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3348 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003349 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003350 // mLeftVolFloat, mRightVolFloat
3351 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353}
3354
3355AudioFlinger::DirectOutputThread::~DirectOutputThread()
3356{
3357}
3358
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003359AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3360 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003361)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003363 sp<Track> trackToRemove;
3364
Glenn Kastenfec279f2012-03-08 07:47:15 -08003365 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366
Glenn Kasten952eeb22012-03-06 11:30:57 -08003367 // find out which tracks need to be processed
3368 if (mActiveTracks.size() != 0) {
3369 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003370 // The track died recently
3371 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372
Glenn Kasten952eeb22012-03-06 11:30:57 -08003373 Track* const track = t.get();
3374 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375
Glenn Kasten952eeb22012-03-06 11:30:57 -08003376 // The first time a track is added we wait
3377 // for all its buffers to be filled before processing it
3378 if (cblk->framesReady() && track->isReady() &&
3379 !track->isPaused() && !track->isTerminated())
3380 {
3381 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382
Glenn Kasten952eeb22012-03-06 11:30:57 -08003383 if (track->mFillingUpStatus == Track::FS_FILLED) {
3384 track->mFillingUpStatus = Track::FS_ACTIVE;
3385 mLeftVolFloat = mRightVolFloat = 0;
3386 mLeftVolShort = mRightVolShort = 0;
3387 if (track->mState == TrackBase::RESUMING) {
3388 track->mState = TrackBase::ACTIVE;
3389 rampVolume = true;
3390 }
3391 } else if (cblk->server != 0) {
3392 // If the track is stopped before the first frame was mixed,
3393 // do not apply ramp
3394 rampVolume = true;
3395 }
3396 // compute volume for this track
3397 float left, right;
3398 if (track->isMuted() || mMasterMute || track->isPausing() ||
3399 mStreamTypes[track->streamType()].mute) {
3400 left = right = 0;
3401 if (track->isPausing()) {
3402 track->setPaused();
3403 }
3404 } else {
3405 float typeVolume = mStreamTypes[track->streamType()].volume;
3406 float v = mMasterVolume * typeVolume;
3407 uint32_t vlr = cblk->getVolumeLR();
3408 float v_clamped = v * (vlr & 0xFFFF);
3409 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3410 left = v_clamped/MAX_GAIN;
3411 v_clamped = v * (vlr >> 16);
3412 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3413 right = v_clamped/MAX_GAIN;
3414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415
Glenn Kasten952eeb22012-03-06 11:30:57 -08003416 if (left != mLeftVolFloat || right != mRightVolFloat) {
3417 mLeftVolFloat = left;
3418 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419
Glenn Kasten952eeb22012-03-06 11:30:57 -08003420 // If audio HAL implements volume control,
3421 // force software volume to nominal value
3422 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3423 left = 1.0f;
3424 right = 1.0f;
3425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426
Glenn Kasten952eeb22012-03-06 11:30:57 -08003427 // Convert volumes from float to 8.24
3428 uint32_t vl = (uint32_t)(left * (1 << 24));
3429 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430
Glenn Kasten952eeb22012-03-06 11:30:57 -08003431 // Delegate volume control to effect in track effect chain if needed
3432 // only one effect chain can be present on DirectOutputThread, so if
3433 // there is one, the track is connected to it
3434 if (!mEffectChains.isEmpty()) {
3435 // Do not ramp volume if volume is controlled by effect
3436 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 rampVolume = false;
3438 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440
Glenn Kasten952eeb22012-03-06 11:30:57 -08003441 // Convert volumes from 8.24 to 4.12 format
3442 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3443 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3444 leftVol = (uint16_t)v_clamped;
3445 v_clamped = (vr + (1 << 11)) >> 12;
3446 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3447 rightVol = (uint16_t)v_clamped;
3448 } else {
3449 leftVol = mLeftVolShort;
3450 rightVol = mRightVolShort;
3451 rampVolume = false;
3452 }
3453
3454 // reset retry count
3455 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003456 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003457 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003458 } else {
3459 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3460 if (track->isStopped()) {
3461 track->reset();
3462 }
3463 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3464 // We have consumed all the buffers of this track.
3465 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003466 // TODO: implement behavior for compressed audio
3467 size_t audioHALFrames =
3468 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3469 size_t framesWritten =
3470 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3471 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3472 trackToRemove = track;
3473 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003474 } else {
3475 // No buffers for this track. Give it a few chances to
3476 // fill a buffer, then remove it from active list.
3477 if (--(track->mRetryCount) <= 0) {
3478 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3479 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003481 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 }
3483 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003484 }
3485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003487 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003488 // remove all the tracks that need to be...
3489 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003490 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003491 mActiveTracks.remove(trackToRemove);
3492 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003493 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003494 trackToRemove->sessionId());
3495 mEffectChains[0]->decActiveTrackCnt();
3496 }
3497 if (trackToRemove->isTerminated()) {
3498 removeTrack_l(trackToRemove);
3499 }
3500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501
Glenn Kastenfec279f2012-03-08 07:47:15 -08003502 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003503}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504
Glenn Kasten000f0e32012-03-01 17:10:56 -08003505void AudioFlinger::DirectOutputThread::threadLoop_mix()
3506{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003507 AudioBufferProvider::Buffer buffer;
3508 size_t frameCount = mFrameCount;
3509 int8_t *curBuf = (int8_t *)mMixBuffer;
3510 // output audio to hardware
3511 while (frameCount) {
3512 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003513 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003514 if (CC_UNLIKELY(buffer.raw == NULL)) {
3515 memset(curBuf, 0, frameCount * mFrameSize);
3516 break;
3517 }
3518 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3519 frameCount -= buffer.frameCount;
3520 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003521 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003522 }
3523 sleepTime = 0;
3524 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003525 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003526
3527 // apply volume
3528
3529 // Do not apply volume on compressed audio
3530 if (!audio_is_linear_pcm(mFormat)) {
3531 return;
3532 }
3533
3534 // convert to signed 16 bit before volume calculation
3535 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3536 size_t count = mFrameCount * mChannelCount;
3537 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3538 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003539 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003540 *dst-- = (int16_t)(*src--^0x80) << 8;
3541 }
3542 }
3543
3544 frameCount = mFrameCount;
3545 int16_t *out = mMixBuffer;
3546 if (rampVolume) {
3547 if (mChannelCount == 1) {
3548 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3549 int32_t vlInc = d / (int32_t)frameCount;
3550 int32_t vl = ((int32_t)mLeftVolShort << 16);
3551 do {
3552 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3553 out++;
3554 vl += vlInc;
3555 } while (--frameCount);
3556
3557 } else {
3558 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3559 int32_t vlInc = d / (int32_t)frameCount;
3560 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3561 int32_t vrInc = d / (int32_t)frameCount;
3562 int32_t vl = ((int32_t)mLeftVolShort << 16);
3563 int32_t vr = ((int32_t)mRightVolShort << 16);
3564 do {
3565 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3566 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3567 out += 2;
3568 vl += vlInc;
3569 vr += vrInc;
3570 } while (--frameCount);
3571 }
3572 } else {
3573 if (mChannelCount == 1) {
3574 do {
3575 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3576 out++;
3577 } while (--frameCount);
3578 } else {
3579 do {
3580 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3581 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3582 out += 2;
3583 } while (--frameCount);
3584 }
3585 }
3586
3587 // convert back to unsigned 8 bit after volume calculation
3588 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3589 size_t count = mFrameCount * mChannelCount;
3590 int16_t *src = mMixBuffer;
3591 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003592 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003593 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3594 }
3595 }
3596
3597 mLeftVolShort = leftVol;
3598 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003599}
3600
3601void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3602{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003603 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003604 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003605 sleepTime = activeSleepTime;
3606 } else {
3607 sleepTime = idleSleepTime;
3608 }
3609 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003610 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003611 sleepTime = 0;
3612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613}
3614
3615// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003616int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617{
3618 return 0;
3619}
3620
3621// deleteTrackName_l() must be called with ThreadBase::mLock held
3622void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3623{
3624}
3625
3626// checkForNewParameters_l() must be called with ThreadBase::mLock held
3627bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3628{
3629 bool reconfig = false;
3630
3631 while (!mNewParameters.isEmpty()) {
3632 status_t status = NO_ERROR;
3633 String8 keyValuePair = mNewParameters[0];
3634 AudioParameter param = AudioParameter(keyValuePair);
3635 int value;
3636
3637 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3638 // do not accept frame count changes if tracks are open as the track buffer
3639 // size depends on frame count and correct behavior would not be garantied
3640 // if frame count is changed after track creation
3641 if (!mTracks.isEmpty()) {
3642 status = INVALID_OPERATION;
3643 } else {
3644 reconfig = true;
3645 }
3646 }
3647 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003648 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003649 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003651 mOutput->stream->common.standby(&mOutput->stream->common);
3652 mStandby = true;
3653 mBytesWritten = 0;
3654 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003655 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 }
3657 if (status == NO_ERROR && reconfig) {
3658 readOutputParameters();
3659 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3660 }
3661 }
3662
3663 mNewParameters.removeAt(0);
3664
3665 mParamStatus = status;
3666 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003667 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3668 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003669 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670 }
3671 return reconfig;
3672}
3673
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003674uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675{
3676 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003677 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003678 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679 } else {
3680 time = 10000;
3681 }
3682 return time;
3683}
3684
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003685uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686{
3687 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003688 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003689 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 } else {
3691 time = 10000;
3692 }
3693 return time;
3694}
3695
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003696uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003697{
3698 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003699 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003700 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3701 } else {
3702 time = 10000;
3703 }
3704 return time;
3705}
3706
Glenn Kasten66fcab92012-02-24 14:59:21 -08003707void AudioFlinger::DirectOutputThread::cacheParameters_l()
3708{
3709 PlaybackThread::cacheParameters_l();
3710
3711 // use shorter standby delay as on normal output to release
3712 // hardware resources as soon as possible
3713 standbyDelay = microseconds(activeSleepTime*2);
3714}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003715
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716// ----------------------------------------------------------------------------
3717
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003718AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003719 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003720 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3721 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 addOutputTrack(mainThread);
3724}
3725
3726AudioFlinger::DuplicatingThread::~DuplicatingThread()
3727{
3728 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3729 mOutputTracks[i]->destroy();
3730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003731}
3732
Glenn Kasten000f0e32012-03-01 17:10:56 -08003733void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003735 // mix buffers...
3736 if (outputsReady(outputTracks)) {
3737 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3738 } else {
3739 memset(mMixBuffer, 0, mixBufferSize);
3740 }
3741 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003742 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003743}
3744
3745void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3746{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003747 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003748 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 sleepTime = activeSleepTime;
3750 } else {
3751 sleepTime = idleSleepTime;
3752 }
3753 } else if (mBytesWritten != 0) {
3754 // flush remaining overflow buffers in output tracks
3755 for (size_t i = 0; i < outputTracks.size(); i++) {
3756 if (outputTracks[i]->isActive()) {
3757 sleepTime = 0;
3758 writeFrames = 0;
3759 memset(mMixBuffer, 0, mixBufferSize);
3760 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003762 }
3763 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003764}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765
Glenn Kasten000f0e32012-03-01 17:10:56 -08003766void AudioFlinger::DuplicatingThread::threadLoop_write()
3767{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003768 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 for (size_t i = 0; i < outputTracks.size(); i++) {
3770 outputTracks[i]->write(mMixBuffer, writeFrames);
3771 }
3772 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003773}
Glenn Kasten688a6402012-02-29 07:57:06 -08003774
Glenn Kasten000f0e32012-03-01 17:10:56 -08003775void AudioFlinger::DuplicatingThread::threadLoop_standby()
3776{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003777 // DuplicatingThread implements standby by stopping all tracks
3778 for (size_t i = 0; i < outputTracks.size(); i++) {
3779 outputTracks[i]->stop();
3780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781}
3782
Glenn Kastenfa26a852012-03-06 11:28:04 -08003783void AudioFlinger::DuplicatingThread::saveOutputTracks()
3784{
3785 outputTracks = mOutputTracks;
3786}
3787
3788void AudioFlinger::DuplicatingThread::clearOutputTracks()
3789{
3790 outputTracks.clear();
3791}
3792
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3794{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003795 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003796 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003797 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003798 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 this,
3800 mSampleRate,
3801 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003802 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803 frameCount);
3804 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003805 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003806 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003807 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003808 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 }
3810}
3811
3812void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3813{
3814 Mutex::Autolock _l(mLock);
3815 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003816 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817 mOutputTracks[i]->destroy();
3818 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003819 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 return;
3821 }
3822 }
Steve Block3856b092011-10-20 11:56:00 +01003823 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824}
3825
Glenn Kasten438b0362012-03-06 11:24:48 -08003826// caller must hold mLock
3827void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828{
3829 mWaitTimeMs = UINT_MAX;
3830 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3831 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003832 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3834 if (waitTimeMs < mWaitTimeMs) {
3835 mWaitTimeMs = waitTimeMs;
3836 }
3837 }
3838 }
3839}
3840
3841
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003842bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843{
3844 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003845 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003847 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003848 return false;
3849 }
3850 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3851 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003852 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 return false;
3854 }
3855 }
3856 return true;
3857}
3858
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003859uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860{
3861 return (mWaitTimeMs * 1000) / 2;
3862}
3863
Glenn Kasten66fcab92012-02-24 14:59:21 -08003864void AudioFlinger::DuplicatingThread::cacheParameters_l()
3865{
3866 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3867 updateWaitTime_l();
3868
3869 MixerThread::cacheParameters_l();
3870}
3871
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872// ----------------------------------------------------------------------------
3873
3874// TrackBase constructor must be called with AudioFlinger::mLock held
3875AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003876 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 const sp<Client>& client,
3878 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003879 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003880 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882 const sp<IMemory>& sharedBuffer,
3883 int sessionId)
3884 : RefBase(),
3885 mThread(thread),
3886 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003887 mCblk(NULL),
3888 // mBuffer
3889 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890 mFrameCount(0),
3891 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003892 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003894 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003896 // mChannelCount
3897 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898{
Steve Block3856b092011-10-20 11:56:00 +01003899 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900
Steve Blockb8a80522011-12-20 16:23:08 +00003901 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003902 size_t size = sizeof(audio_track_cblk_t);
3903 uint8_t channelCount = popcount(channelMask);
3904 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3905 if (sharedBuffer == 0) {
3906 size += bufferSize;
3907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003909 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910 mCblkMemory = client->heap()->allocate(size);
3911 if (mCblkMemory != 0) {
3912 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003913 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 new(mCblk) audio_track_cblk_t();
3915 // clear all buffers
3916 mCblk->frameCount = frameCount;
3917 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003918// uncomment the following lines to quickly test 32-bit wraparound
3919// mCblk->user = 0xffff0000;
3920// mCblk->server = 0xffff0000;
3921// mCblk->userBase = 0xffff0000;
3922// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003923 mChannelCount = channelCount;
3924 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 if (sharedBuffer == 0) {
3926 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3927 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3928 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003929 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 mCblk->flags = CBLK_UNDERRUN_ON;
3931 } else {
3932 mBuffer = sharedBuffer->pointer();
3933 }
3934 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3935 }
3936 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003937 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 client->heap()->dump("AudioTrack");
3939 return;
3940 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003941 } else {
3942 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003943 // construct the shared structure in-place.
3944 new(mCblk) audio_track_cblk_t();
3945 // clear all buffers
3946 mCblk->frameCount = frameCount;
3947 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003948// uncomment the following lines to quickly test 32-bit wraparound
3949// mCblk->user = 0xffff0000;
3950// mCblk->server = 0xffff0000;
3951// mCblk->userBase = 0xffff0000;
3952// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003953 mChannelCount = channelCount;
3954 mChannelMask = channelMask;
3955 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3956 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3957 // Force underrun condition to avoid false underrun callback until first data is
3958 // written to buffer (other flags are cleared)
3959 mCblk->flags = CBLK_UNDERRUN_ON;
3960 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962}
3963
3964AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3965{
Glenn Kastena0d68332012-01-27 16:47:15 -08003966 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003967 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003969 } else {
3970 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971 }
3972 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003973 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003974 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003975 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003977 // If the client's reference count drops to zero, the associated destructor
3978 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3979 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 mClient.clear();
3981 }
3982}
3983
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003984// AudioBufferProvider interface
3985// getNextBuffer() = 0;
3986// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3988{
Glenn Kastene0feee32011-12-13 11:53:26 -08003989 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07003991 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003992 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993 buffer->frameCount = 0;
3994}
3995
3996bool AudioFlinger::ThreadBase::TrackBase::step() {
3997 bool result;
3998 audio_track_cblk_t* cblk = this->cblk();
3999
4000 result = cblk->stepServer(mFrameCount);
4001 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004002 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004003 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 }
4005 return result;
4006}
4007
4008void AudioFlinger::ThreadBase::TrackBase::reset() {
4009 audio_track_cblk_t* cblk = this->cblk();
4010
4011 cblk->user = 0;
4012 cblk->server = 0;
4013 cblk->userBase = 0;
4014 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004015 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004016 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017}
4018
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4020 return (int)mCblk->sampleRate;
4021}
4022
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4024 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004025 size_t frameSize = cblk->frameSize;
4026 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4027 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028
4029 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004030 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4031 "TrackBase::getBuffer buffer out of range:\n"
4032 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4033 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004035 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036
4037 return bufferStart;
4038}
4039
Eric Laurenta011e352012-03-29 15:51:43 -07004040status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4041{
4042 mSyncEvents.add(event);
4043 return NO_ERROR;
4044}
4045
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046// ----------------------------------------------------------------------------
4047
4048// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4049AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004050 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004052 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004054 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004055 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056 int frameCount,
4057 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004058 int sessionId,
4059 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004060 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004061 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004062 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004063 // mRetryCount initialized later when needed
4064 mSharedBuffer(sharedBuffer),
4065 mStreamType(streamType),
4066 mName(-1), // see note below
4067 mMainBuffer(thread->mixBuffer()),
4068 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004069 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004070 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004071 mFlags(flags),
4072 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004073 mObservedUnderruns(0),
4074 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004075 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076{
4077 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4079 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004080 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004081 if (flags & IAudioFlinger::TRACK_FAST) {
4082 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4083 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4084 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4085 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004086 // FIXME This is too eager. We allocate a fast track index before the
4087 // fast track becomes active. Since fast tracks are a scarce resource,
4088 // this means we are potentially denying other more important fast tracks from
4089 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004090 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004091 // Read the initial underruns because this field is never cleared by the fast mixer
4092 mObservedUnderruns = thread->getFastTrackUnderruns(i) & ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07004093 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004094 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004095 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004096 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004097 if (mName < 0) {
4098 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004099 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4100 // then we leak a fast track index. Should swap these two sections, or better yet
4101 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004104 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105}
4106
4107AudioFlinger::PlaybackThread::Track::~Track()
4108{
Steve Block3856b092011-10-20 11:56:00 +01004109 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 sp<ThreadBase> thread = mThread.promote();
4111 if (thread != 0) {
4112 Mutex::Autolock _l(thread->mLock);
4113 mState = TERMINATED;
4114 }
4115}
4116
4117void AudioFlinger::PlaybackThread::Track::destroy()
4118{
4119 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4120 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004121 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 // we must acquire a strong reference on this Track before locking mLock
4123 // here so that the destructor is called only when exiting this function.
4124 // On the other hand, as long as Track::destroy() is only called by
4125 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4126 // this Track with its member mTrack.
4127 sp<Track> keep(this);
4128 { // scope for mLock
4129 sp<ThreadBase> thread = mThread.promote();
4130 if (thread != 0) {
4131 if (!isOutputTrack()) {
4132 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004133 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004134
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004135#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004136 // to track the speaker usage
4137 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004138#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 }
4140 AudioSystem::releaseOutput(thread->id());
4141 }
4142 Mutex::Autolock _l(thread->mLock);
4143 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4144 playbackThread->destroyTrack_l(this);
4145 }
4146 }
4147}
4148
Glenn Kasten288ed212012-04-25 17:52:27 -07004149/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4150{
4151 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
4152 " Server User Main buf Aux Buf FastUnder\n");
4153
4154}
4155
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4157{
Glenn Kasten83d86532012-01-17 14:39:34 -08004158 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004159 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004160 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004161 } else {
4162 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4163 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004164 track_state state = mState;
4165 char stateChar;
4166 switch (state) {
4167 case IDLE:
4168 stateChar = 'I';
4169 break;
4170 case TERMINATED:
4171 stateChar = 'T';
4172 break;
4173 case STOPPED:
4174 stateChar = 'S';
4175 break;
4176 case RESUMING:
4177 stateChar = 'R';
4178 break;
4179 case ACTIVE:
4180 stateChar = 'A';
4181 break;
4182 case PAUSING:
4183 stateChar = 'p';
4184 break;
4185 case PAUSED:
4186 stateChar = 'P';
4187 break;
4188 default:
4189 stateChar = '?';
4190 break;
4191 }
4192 bool nowInUnderrun = mObservedUnderruns & 1;
4193 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %1c %1d %1d %5u %5.2g %5.2g "
4194 "0x%08x 0x%08x 0x%08x 0x%08x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004195 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 mStreamType,
4197 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004198 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199 mSessionId,
4200 mFrameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004201 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mMute,
4203 mFillingUpStatus,
4204 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004205 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4206 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 mCblk->server,
4208 mCblk->user,
4209 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004210 (int)mAuxBuffer,
4211 mUnderrunCount,
4212 nowInUnderrun ? '*' : ' ');
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213}
4214
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004215// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004216status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004217 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004219 audio_track_cblk_t* cblk = this->cblk();
4220 uint32_t framesReady;
4221 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004223 // Check if last stepServer failed, try to step now
4224 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004225 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4226 // Since the fast mixer is higher priority than client callback thread,
4227 // it does not result in priority inversion for client.
4228 // But a non-blocking solution would be preferable to avoid
4229 // fast mixer being unable to tryLock(), and
4230 // to avoid the extra context switches if the client wakes up,
4231 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004232 if (!step()) goto getNextBuffer_exit;
4233 ALOGV("stepServer recovered");
4234 mStepServerFailed = false;
4235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236
Glenn Kasten288ed212012-04-25 17:52:27 -07004237 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004238 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004240 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 uint32_t s = cblk->server;
4242 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4243
4244 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4245 if (framesReq > framesReady) {
4246 framesReq = framesReady;
4247 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004248 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 framesReq = bufferEnd - s;
4250 }
4251
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004252 buffer->raw = getBuffer(s, framesReq);
4253 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004255 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258
4259getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004260 buffer->raw = NULL;
4261 buffer->frameCount = 0;
4262 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4263 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264}
4265
Glenn Kasten288ed212012-04-25 17:52:27 -07004266// Note that framesReady() takes a mutex on the control block using tryLock().
4267// This could result in priority inversion if framesReady() is called by the normal mixer,
4268// as the normal mixer thread runs at lower
4269// priority than the client's callback thread: there is a short window within framesReady()
4270// during which the normal mixer could be preempted, and the client callback would block.
4271// Another problem can occur if framesReady() is called by the fast mixer:
4272// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4273// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4274size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004275 return mCblk->framesReady();
4276}
4277
Glenn Kasten288ed212012-04-25 17:52:27 -07004278// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004280 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281
John Grossman4ff14ba2012-02-08 16:37:41 -08004282 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4284 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004285 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 return true;
4287 }
4288 return false;
4289}
4290
Glenn Kasten3acbd052012-02-28 10:39:56 -08004291status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004292 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293{
4294 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004295 ALOGV("start(%d), calling pid %d session %d",
4296 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004297
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 sp<ThreadBase> thread = mThread.promote();
4299 if (thread != 0) {
4300 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004301 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 // here the track could be either new, or restarted
4303 // in both cases "unstop" the track
4304 if (mState == PAUSED) {
4305 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004306 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 } else {
4308 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004309 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 }
4311
4312 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4313 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004314 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004316
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004317#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004318 // to track the speaker usage
4319 if (status == NO_ERROR) {
4320 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4321 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004322#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 }
4324 if (status == NO_ERROR) {
4325 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4326 playbackThread->addTrack_l(this);
4327 } else {
4328 mState = state;
4329 }
4330 } else {
4331 status = BAD_VALUE;
4332 }
4333 return status;
4334}
4335
4336void AudioFlinger::PlaybackThread::Track::stop()
4337{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004338 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339 sp<ThreadBase> thread = mThread.promote();
4340 if (thread != 0) {
4341 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004342 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 if (mState > STOPPED) {
4344 mState = STOPPED;
4345 // If the track is not active (PAUSED and buffers full), flush buffers
4346 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4347 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4348 reset();
4349 }
Steve Block3856b092011-10-20 11:56:00 +01004350 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 }
4352 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4353 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004354 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004356
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004357#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004358 // to track the speaker usage
4359 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004360#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 }
4362 }
4363}
4364
4365void AudioFlinger::PlaybackThread::Track::pause()
4366{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004367 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 sp<ThreadBase> thread = mThread.promote();
4369 if (thread != 0) {
4370 Mutex::Autolock _l(thread->mLock);
4371 if (mState == ACTIVE || mState == RESUMING) {
4372 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004373 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374 if (!isOutputTrack()) {
4375 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004376 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004378
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004379#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004380 // to track the speaker usage
4381 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004382#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 }
4384 }
4385 }
4386}
4387
4388void AudioFlinger::PlaybackThread::Track::flush()
4389{
Steve Block3856b092011-10-20 11:56:00 +01004390 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 sp<ThreadBase> thread = mThread.promote();
4392 if (thread != 0) {
4393 Mutex::Autolock _l(thread->mLock);
4394 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4395 return;
4396 }
4397 // No point remaining in PAUSED state after a flush => go to
4398 // STOPPED state
4399 mState = STOPPED;
4400
Eric Laurent38ccae22011-03-28 18:37:07 -07004401 // do not reset the track if it is still in the process of being stopped or paused.
4402 // this will be done by prepareTracks_l() when the track is stopped.
4403 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4404 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4405 reset();
4406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407 }
4408}
4409
4410void AudioFlinger::PlaybackThread::Track::reset()
4411{
4412 // Do not reset twice to avoid discarding data written just after a flush and before
4413 // the audioflinger thread detects the track is stopped.
4414 if (!mResetDone) {
4415 TrackBase::reset();
4416 // Force underrun condition to avoid false underrun callback until first data is
4417 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004418 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4419 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 mFillingUpStatus = FS_FILLING;
4421 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004422 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424}
4425
4426void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4427{
4428 mMute = muted;
4429}
4430
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4432{
4433 status_t status = DEAD_OBJECT;
4434 sp<ThreadBase> thread = mThread.promote();
4435 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004436 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4437 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 }
4439 return status;
4440}
4441
4442void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4443{
4444 mAuxEffectId = EffectId;
4445 mAuxBuffer = buffer;
4446}
4447
Eric Laurenta011e352012-03-29 15:51:43 -07004448bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4449 size_t audioHalFrames)
4450{
4451 // a track is considered presented when the total number of frames written to audio HAL
4452 // corresponds to the number of frames written when presentationComplete() is called for the
4453 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4454 if (mPresentationCompleteFrames == 0) {
4455 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4456 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4457 mPresentationCompleteFrames, audioHalFrames);
4458 }
4459 if (framesWritten >= mPresentationCompleteFrames) {
4460 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4461 mSessionId, framesWritten);
4462 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4463 mPresentationCompleteFrames = 0;
4464 return true;
4465 }
4466 return false;
4467}
4468
4469void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4470{
4471 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4472 if (mSyncEvents[i]->type() == type) {
4473 mSyncEvents[i]->trigger();
4474 mSyncEvents.removeAt(i);
4475 i--;
4476 }
4477 }
4478}
4479
Glenn Kasten58912562012-04-03 10:45:00 -07004480// implement VolumeBufferProvider interface
4481
4482uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4483{
4484 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4485 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4486 uint32_t vlr = mCblk->getVolumeLR();
4487 uint32_t vl = vlr & 0xFFFF;
4488 uint32_t vr = vlr >> 16;
4489 // track volumes come from shared memory, so can't be trusted and must be clamped
4490 if (vl > MAX_GAIN_INT) {
4491 vl = MAX_GAIN_INT;
4492 }
4493 if (vr > MAX_GAIN_INT) {
4494 vr = MAX_GAIN_INT;
4495 }
4496 // now apply the cached master volume and stream type volume;
4497 // this is trusted but lacks any synchronization or barrier so may be stale
4498 float v = mCachedVolume;
4499 vl *= v;
4500 vr *= v;
4501 // re-combine into U4.16
4502 vlr = (vr << 16) | (vl & 0xFFFF);
4503 // FIXME look at mute, pause, and stop flags
4504 return vlr;
4505}
Eric Laurenta011e352012-03-29 15:51:43 -07004506
John Grossman4ff14ba2012-02-08 16:37:41 -08004507// timed audio tracks
4508
4509sp<AudioFlinger::PlaybackThread::TimedTrack>
4510AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004511 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004512 const sp<Client>& client,
4513 audio_stream_type_t streamType,
4514 uint32_t sampleRate,
4515 audio_format_t format,
4516 uint32_t channelMask,
4517 int frameCount,
4518 const sp<IMemory>& sharedBuffer,
4519 int sessionId) {
4520 if (!client->reserveTimedTrack())
4521 return NULL;
4522
Glenn Kastena0356762012-03-19 10:38:51 -07004523 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004524 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4525 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004526}
4527
4528AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004529 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004530 const sp<Client>& client,
4531 audio_stream_type_t streamType,
4532 uint32_t sampleRate,
4533 audio_format_t format,
4534 uint32_t channelMask,
4535 int frameCount,
4536 const sp<IMemory>& sharedBuffer,
4537 int sessionId)
4538 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004539 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004540 mQueueHeadInFlight(false),
4541 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004542 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004543 mTimedSilenceBuffer(NULL),
4544 mTimedSilenceBufferSize(0),
4545 mTimedAudioOutputOnTime(false),
4546 mMediaTimeTransformValid(false)
4547{
4548 LocalClock lc;
4549 mLocalTimeFreq = lc.getLocalFreq();
4550
4551 mLocalTimeToSampleTransform.a_zero = 0;
4552 mLocalTimeToSampleTransform.b_zero = 0;
4553 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4554 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4555 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4556 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004557
4558 mMediaTimeToSampleTransform.a_zero = 0;
4559 mMediaTimeToSampleTransform.b_zero = 0;
4560 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4561 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4562 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4563 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004564}
4565
4566AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4567 mClient->releaseTimedTrack();
4568 delete [] mTimedSilenceBuffer;
4569}
4570
4571status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4572 size_t size, sp<IMemory>* buffer) {
4573
4574 Mutex::Autolock _l(mTimedBufferQueueLock);
4575
4576 trimTimedBufferQueue_l();
4577
4578 // lazily initialize the shared memory heap for timed buffers
4579 if (mTimedMemoryDealer == NULL) {
4580 const int kTimedBufferHeapSize = 512 << 10;
4581
4582 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4583 "AudioFlingerTimed");
4584 if (mTimedMemoryDealer == NULL)
4585 return NO_MEMORY;
4586 }
4587
4588 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4589 if (newBuffer == NULL) {
4590 newBuffer = mTimedMemoryDealer->allocate(size);
4591 if (newBuffer == NULL)
4592 return NO_MEMORY;
4593 }
4594
4595 *buffer = newBuffer;
4596 return NO_ERROR;
4597}
4598
4599// caller must hold mTimedBufferQueueLock
4600void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4601 int64_t mediaTimeNow;
4602 {
4603 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4604 if (!mMediaTimeTransformValid)
4605 return;
4606
4607 int64_t targetTimeNow;
4608 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4609 ? mCCHelper.getCommonTime(&targetTimeNow)
4610 : mCCHelper.getLocalTime(&targetTimeNow);
4611
4612 if (OK != res)
4613 return;
4614
4615 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4616 &mediaTimeNow)) {
4617 return;
4618 }
4619 }
4620
John Grossman1c345192012-03-27 14:00:17 -07004621 size_t trimEnd;
4622 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004623 int64_t bufEnd;
4624
John Grossmanc95cfbb2012-04-12 11:53:11 -07004625 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4626 // We have a next buffer. Just use its PTS as the PTS of the frame
4627 // following the last frame in this buffer. If the stream is sparse
4628 // (ie, there are deliberate gaps left in the stream which should be
4629 // filled with silence by the TimedAudioTrack), then this can result
4630 // in one extra buffer being left un-trimmed when it could have
4631 // been. In general, this is not typical, and we would rather
4632 // optimized away the TS calculation below for the more common case
4633 // where PTSes are contiguous.
4634 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4635 } else {
4636 // We have no next buffer. Compute the PTS of the frame following
4637 // the last frame in this buffer by computing the duration of of
4638 // this frame in media time units and adding it to the PTS of the
4639 // buffer.
4640 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4641 / mCblk->frameSize;
4642
4643 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4644 &bufEnd)) {
4645 ALOGE("Failed to convert frame count of %lld to media time"
4646 " duration" " (scale factor %d/%u) in %s",
4647 frameCount,
4648 mMediaTimeToSampleTransform.a_to_b_numer,
4649 mMediaTimeToSampleTransform.a_to_b_denom,
4650 __PRETTY_FUNCTION__);
4651 break;
4652 }
4653 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004654 }
John Grossman9fbdee12012-03-26 17:51:46 -07004655
4656 if (bufEnd > mediaTimeNow)
4657 break;
4658
4659 // Is the buffer we want to use in the middle of a mix operation right
4660 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4661 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004662 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004663 mTrimQueueHeadOnRelease = true;
4664 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004665 }
4666
John Grossman9fbdee12012-03-26 17:51:46 -07004667 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004668 if (trimStart < trimEnd) {
4669 // Update the bookkeeping for framesReady()
4670 for (size_t i = trimStart; i < trimEnd; ++i) {
4671 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4672 }
4673
4674 // Now actually remove the buffers from the queue.
4675 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004676 }
4677}
4678
John Grossman1c345192012-03-27 14:00:17 -07004679void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4680 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004681 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4682 "%s called (reason \"%s\"), but timed buffer queue has no"
4683 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004684
4685 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4686 mTimedBufferQueue.removeAt(0);
4687}
4688
4689void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4690 const TimedBuffer& buf,
4691 const char* logTag) {
4692 uint32_t bufBytes = buf.buffer()->size();
4693 uint32_t consumedAlready = buf.position();
4694
Eric Laurentb388e532012-04-14 13:32:48 -07004695 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004696 "Bad bookkeeping while updating frames pending. Timed buffer is"
4697 " only %u bytes long, but claims to have consumed %u"
4698 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004699 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004700
4701 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004702 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4703 "Bad bookkeeping while updating frames pending. Should have at"
4704 " least %u queued frames, but we think we have only %u. (update"
4705 " reason: \"%s\")",
4706 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004707
4708 mFramesPendingInQueue -= bufFrames;
4709}
4710
John Grossman4ff14ba2012-02-08 16:37:41 -08004711status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4712 const sp<IMemory>& buffer, int64_t pts) {
4713
4714 {
4715 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4716 if (!mMediaTimeTransformValid)
4717 return INVALID_OPERATION;
4718 }
4719
4720 Mutex::Autolock _l(mTimedBufferQueueLock);
4721
John Grossman1c345192012-03-27 14:00:17 -07004722 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4723 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004724 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4725
4726 return NO_ERROR;
4727}
4728
4729status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4730 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4731
John Grossman1c345192012-03-27 14:00:17 -07004732 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4733 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4734 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004735
4736 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4737 target == TimedAudioTrack::COMMON_TIME)) {
4738 return BAD_VALUE;
4739 }
4740
4741 Mutex::Autolock lock(mMediaTimeTransformLock);
4742 mMediaTimeTransform = xform;
4743 mMediaTimeTransformTarget = target;
4744 mMediaTimeTransformValid = true;
4745
4746 return NO_ERROR;
4747}
4748
4749#define min(a, b) ((a) < (b) ? (a) : (b))
4750
4751// implementation of getNextBuffer for tracks whose buffers have timestamps
4752status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4753 AudioBufferProvider::Buffer* buffer, int64_t pts)
4754{
4755 if (pts == AudioBufferProvider::kInvalidPTS) {
4756 buffer->raw = 0;
4757 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004758 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004759 return INVALID_OPERATION;
4760 }
4761
John Grossman4ff14ba2012-02-08 16:37:41 -08004762 Mutex::Autolock _l(mTimedBufferQueueLock);
4763
John Grossman9fbdee12012-03-26 17:51:46 -07004764 ALOG_ASSERT(!mQueueHeadInFlight,
4765 "getNextBuffer called without releaseBuffer!");
4766
John Grossman4ff14ba2012-02-08 16:37:41 -08004767 while (true) {
4768
4769 // if we have no timed buffers, then fail
4770 if (mTimedBufferQueue.isEmpty()) {
4771 buffer->raw = 0;
4772 buffer->frameCount = 0;
4773 return NOT_ENOUGH_DATA;
4774 }
4775
4776 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4777
4778 // calculate the PTS of the head of the timed buffer queue expressed in
4779 // local time
4780 int64_t headLocalPTS;
4781 {
4782 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4783
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004784 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004785
4786 if (mMediaTimeTransform.a_to_b_denom == 0) {
4787 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004788 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004789 return NO_ERROR;
4790 }
4791
4792 int64_t transformedPTS;
4793 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4794 &transformedPTS)) {
4795 // the transform failed. this shouldn't happen, but if it does
4796 // then just drop this buffer
4797 ALOGW("timedGetNextBuffer transform failed");
4798 buffer->raw = 0;
4799 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004800 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004801 return NO_ERROR;
4802 }
4803
4804 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4805 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4806 &headLocalPTS)) {
4807 buffer->raw = 0;
4808 buffer->frameCount = 0;
4809 return INVALID_OPERATION;
4810 }
4811 } else {
4812 headLocalPTS = transformedPTS;
4813 }
4814 }
4815
4816 // adjust the head buffer's PTS to reflect the portion of the head buffer
4817 // that has already been consumed
4818 int64_t effectivePTS = headLocalPTS +
4819 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4820
4821 // Calculate the delta in samples between the head of the input buffer
4822 // queue and the start of the next output buffer that will be written.
4823 // If the transformation fails because of over or underflow, it means
4824 // that the sample's position in the output stream is so far out of
4825 // whack that it should just be dropped.
4826 int64_t sampleDelta;
4827 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4828 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004829 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4830 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004831 continue;
4832 }
4833 if (!mLocalTimeToSampleTransform.doForwardTransform(
4834 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004835 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004836 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004837 continue;
4838 }
4839
John Grossman1c345192012-03-27 14:00:17 -07004840 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4841 " sampleDelta=[%d.%08x]",
4842 head.pts(), head.position(), pts,
4843 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4844 + (sampleDelta >> 32)),
4845 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004846
4847 // if the delta between the ideal placement for the next input sample and
4848 // the current output position is within this threshold, then we will
4849 // concatenate the next input samples to the previous output
4850 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004851 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004852
4853 // if this is the first buffer of audio that we're emitting from this track
4854 // then it should be almost exactly on time.
4855 const int64_t kSampleStartupThreshold = 1LL << 32;
4856
4857 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004858 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004859 // the next input is close enough to being on time, so concatenate it
4860 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004861 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004862
John Grossman1c345192012-03-27 14:00:17 -07004863 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4864 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004865 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004866 }
4867
4868 // Looks like our output is not on time. Reset our on timed status.
4869 // Next time we mix samples from our input queue, then should be within
4870 // the StartupThreshold.
4871 mTimedAudioOutputOnTime = false;
4872 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004873 // the gap between the current output position and the proper start of
4874 // the next input sample is too big, so fill it with silence
4875 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4876
John Grossman9fbdee12012-03-26 17:51:46 -07004877 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004878 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4879 return NO_ERROR;
4880 } else {
4881 // the next input sample is late
4882 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4883 size_t onTimeSamplePosition =
4884 head.position() + lateFrames * mCblk->frameSize;
4885
4886 if (onTimeSamplePosition > head.buffer()->size()) {
4887 // all the remaining samples in the head are too late, so
4888 // drop it and move on
4889 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004890 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004891 continue;
4892 } else {
4893 // skip over the late samples
4894 head.setPosition(onTimeSamplePosition);
4895
4896 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004897 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004898
4899 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4900 return NO_ERROR;
4901 }
4902 }
4903 }
4904}
4905
4906// Yield samples from the timed buffer queue head up to the given output
4907// buffer's capacity.
4908//
4909// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004910void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004911 AudioBufferProvider::Buffer* buffer) {
4912
4913 const TimedBuffer& head = mTimedBufferQueue[0];
4914
4915 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4916 head.position());
4917
4918 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4919 mCblk->frameSize);
4920 size_t framesRequested = buffer->frameCount;
4921 buffer->frameCount = min(framesLeftInHead, framesRequested);
4922
John Grossman9fbdee12012-03-26 17:51:46 -07004923 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004924 mTimedAudioOutputOnTime = true;
4925}
4926
4927// Yield samples of silence up to the given output buffer's capacity
4928//
4929// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004930void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004931 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4932
4933 // lazily allocate a buffer filled with silence
4934 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4935 delete [] mTimedSilenceBuffer;
4936 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4937 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4938 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4939 }
4940
4941 buffer->raw = mTimedSilenceBuffer;
4942 size_t framesRequested = buffer->frameCount;
4943 buffer->frameCount = min(numFrames, framesRequested);
4944
4945 mTimedAudioOutputOnTime = false;
4946}
4947
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004948// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004949void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4950 AudioBufferProvider::Buffer* buffer) {
4951
4952 Mutex::Autolock _l(mTimedBufferQueueLock);
4953
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004954 // If the buffer which was just released is part of the buffer at the head
4955 // of the queue, be sure to update the amt of the buffer which has been
4956 // consumed. If the buffer being returned is not part of the head of the
4957 // queue, its either because the buffer is part of the silence buffer, or
4958 // because the head of the timed queue was trimmed after the mixer called
4959 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004960 if (buffer->raw == mTimedSilenceBuffer) {
4961 ALOG_ASSERT(!mQueueHeadInFlight,
4962 "Queue head in flight during release of silence buffer!");
4963 goto done;
4964 }
4965
4966 ALOG_ASSERT(mQueueHeadInFlight,
4967 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4968 " head in flight.");
4969
4970 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004971 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004972
4973 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004974 void* end = reinterpret_cast<void*>(
4975 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4976 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004977
John Grossman9fbdee12012-03-26 17:51:46 -07004978 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4979 "released buffer not within the head of the timed buffer"
4980 " queue; qHead = [%p, %p], released buffer = %p",
4981 start, end, buffer->raw);
4982
4983 head.setPosition(head.position() +
4984 (buffer->frameCount * mCblk->frameSize));
4985 mQueueHeadInFlight = false;
4986
John Grossman1c345192012-03-27 14:00:17 -07004987 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4988 "Bad bookkeeping during releaseBuffer! Should have at"
4989 " least %u queued frames, but we think we have only %u",
4990 buffer->frameCount, mFramesPendingInQueue);
4991
4992 mFramesPendingInQueue -= buffer->frameCount;
4993
John Grossman9fbdee12012-03-26 17:51:46 -07004994 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4995 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004996 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004997 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004998 }
John Grossman9fbdee12012-03-26 17:51:46 -07004999 } else {
5000 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5001 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005002 }
5003
John Grossman9fbdee12012-03-26 17:51:46 -07005004done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005005 buffer->raw = 0;
5006 buffer->frameCount = 0;
5007}
5008
Glenn Kasten288ed212012-04-25 17:52:27 -07005009size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005010 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005011 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005012}
5013
5014AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5015 : mPTS(0), mPosition(0) {}
5016
5017AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5018 const sp<IMemory>& buffer, int64_t pts)
5019 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5020
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021// ----------------------------------------------------------------------------
5022
5023// RecordTrack constructor must be called with AudioFlinger::mLock held
5024AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005025 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 const sp<Client>& client,
5027 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005028 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005029 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005030 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 int sessionId)
5032 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005033 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 mOverflow(false)
5035{
5036 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005037 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5038 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5039 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5040 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5041 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5042 } else {
5043 mCblk->frameSize = sizeof(int8_t);
5044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 }
5046}
5047
5048AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5049{
5050 sp<ThreadBase> thread = mThread.promote();
5051 if (thread != 0) {
5052 AudioSystem::releaseInput(thread->id());
5053 }
5054}
5055
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005056// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005057status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058{
5059 audio_track_cblk_t* cblk = this->cblk();
5060 uint32_t framesAvail;
5061 uint32_t framesReq = buffer->frameCount;
5062
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005063 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005064 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005066 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005067 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068 }
5069
5070 framesAvail = cblk->framesAvailable_l();
5071
Glenn Kastenf6b16782011-12-15 09:51:17 -08005072 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 uint32_t s = cblk->server;
5074 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5075
5076 if (framesReq > framesAvail) {
5077 framesReq = framesAvail;
5078 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005079 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 framesReq = bufferEnd - s;
5081 }
5082
5083 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005084 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005085
5086 buffer->frameCount = framesReq;
5087 return NO_ERROR;
5088 }
5089
5090getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005091 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092 buffer->frameCount = 0;
5093 return NOT_ENOUGH_DATA;
5094}
5095
Glenn Kasten3acbd052012-02-28 10:39:56 -08005096status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005097 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098{
5099 sp<ThreadBase> thread = mThread.promote();
5100 if (thread != 0) {
5101 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005102 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 } else {
5104 return BAD_VALUE;
5105 }
5106}
5107
5108void AudioFlinger::RecordThread::RecordTrack::stop()
5109{
5110 sp<ThreadBase> thread = mThread.promote();
5111 if (thread != 0) {
5112 RecordThread *recordThread = (RecordThread *)thread.get();
5113 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005114 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005115 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005116 // read from buffer
5117 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 }
5119}
5120
5121void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5122{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005123 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005124 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005126 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 mSessionId,
5128 mFrameCount,
5129 mState,
5130 mCblk->sampleRate,
5131 mCblk->server,
5132 mCblk->user);
5133}
5134
5135
5136// ----------------------------------------------------------------------------
5137
5138AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005139 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005140 DuplicatingThread *sourceThread,
5141 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005142 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005143 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005144 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005145 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5146 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 mActive(false), mSourceThread(sourceThread)
5148{
5149
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150 if (mCblk != NULL) {
5151 mCblk->flags |= CBLK_DIRECTION_OUT;
5152 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005153 mOutBuffer.frameCount = 0;
5154 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005155 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005156 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5157 mCblk, mBuffer, mCblk->buffers,
5158 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005160 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 }
5162}
5163
5164AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5165{
5166 clearBufferQueue();
5167}
5168
Glenn Kasten3acbd052012-02-28 10:39:56 -08005169status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005170 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005172 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 if (status != NO_ERROR) {
5174 return status;
5175 }
5176
5177 mActive = true;
5178 mRetryCount = 127;
5179 return status;
5180}
5181
5182void AudioFlinger::PlaybackThread::OutputTrack::stop()
5183{
5184 Track::stop();
5185 clearBufferQueue();
5186 mOutBuffer.frameCount = 0;
5187 mActive = false;
5188}
5189
5190bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5191{
5192 Buffer *pInBuffer;
5193 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005194 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005195 bool outputBufferFull = false;
5196 inBuffer.frameCount = frames;
5197 inBuffer.i16 = data;
5198
5199 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5200
5201 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005202 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 sp<ThreadBase> thread = mThread.promote();
5204 if (thread != 0) {
5205 MixerThread *mixerThread = (MixerThread *)thread.get();
5206 if (mCblk->frameCount > frames){
5207 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5208 uint32_t startFrames = (mCblk->frameCount - frames);
5209 pInBuffer = new Buffer;
5210 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5211 pInBuffer->frameCount = startFrames;
5212 pInBuffer->i16 = pInBuffer->mBuffer;
5213 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5214 mBufferQueue.add(pInBuffer);
5215 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005216 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 }
5218 }
5219 }
5220 }
5221
5222 while (waitTimeLeftMs) {
5223 // First write pending buffers, then new data
5224 if (mBufferQueue.size()) {
5225 pInBuffer = mBufferQueue.itemAt(0);
5226 } else {
5227 pInBuffer = &inBuffer;
5228 }
5229
5230 if (pInBuffer->frameCount == 0) {
5231 break;
5232 }
5233
5234 if (mOutBuffer.frameCount == 0) {
5235 mOutBuffer.frameCount = pInBuffer->frameCount;
5236 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005237 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005238 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005239 outputBufferFull = true;
5240 break;
5241 }
5242 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5243 if (waitTimeLeftMs >= waitTimeMs) {
5244 waitTimeLeftMs -= waitTimeMs;
5245 } else {
5246 waitTimeLeftMs = 0;
5247 }
5248 }
5249
5250 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5251 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5252 mCblk->stepUser(outFrames);
5253 pInBuffer->frameCount -= outFrames;
5254 pInBuffer->i16 += outFrames * channelCount;
5255 mOutBuffer.frameCount -= outFrames;
5256 mOutBuffer.i16 += outFrames * channelCount;
5257
5258 if (pInBuffer->frameCount == 0) {
5259 if (mBufferQueue.size()) {
5260 mBufferQueue.removeAt(0);
5261 delete [] pInBuffer->mBuffer;
5262 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005263 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 } else {
5265 break;
5266 }
5267 }
5268 }
5269
5270 // If we could not write all frames, allocate a buffer and queue it for next time.
5271 if (inBuffer.frameCount) {
5272 sp<ThreadBase> thread = mThread.promote();
5273 if (thread != 0 && !thread->standby()) {
5274 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5275 pInBuffer = new Buffer;
5276 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5277 pInBuffer->frameCount = inBuffer.frameCount;
5278 pInBuffer->i16 = pInBuffer->mBuffer;
5279 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5280 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005281 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005283 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284 }
5285 }
5286 }
5287
5288 // Calling write() with a 0 length buffer, means that no more data will be written:
5289 // If no more buffers are pending, fill output track buffer to make sure it is started
5290 // by output mixer.
5291 if (frames == 0 && mBufferQueue.size() == 0) {
5292 if (mCblk->user < mCblk->frameCount) {
5293 frames = mCblk->frameCount - mCblk->user;
5294 pInBuffer = new Buffer;
5295 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5296 pInBuffer->frameCount = frames;
5297 pInBuffer->i16 = pInBuffer->mBuffer;
5298 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5299 mBufferQueue.add(pInBuffer);
5300 } else if (mActive) {
5301 stop();
5302 }
5303 }
5304
5305 return outputBufferFull;
5306}
5307
5308status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5309{
5310 int active;
5311 status_t result;
5312 audio_track_cblk_t* cblk = mCblk;
5313 uint32_t framesReq = buffer->frameCount;
5314
Steve Block3856b092011-10-20 11:56:00 +01005315// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 buffer->frameCount = 0;
5317
5318 uint32_t framesAvail = cblk->framesAvailable();
5319
5320
5321 if (framesAvail == 0) {
5322 Mutex::Autolock _l(cblk->lock);
5323 goto start_loop_here;
5324 while (framesAvail == 0) {
5325 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005326 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005327 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005328 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 }
5330 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5331 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005332 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 }
5334 // read the server count again
5335 start_loop_here:
5336 framesAvail = cblk->framesAvailable_l();
5337 }
5338 }
5339
5340// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005341// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342// }
5343
5344 if (framesReq > framesAvail) {
5345 framesReq = framesAvail;
5346 }
5347
5348 uint32_t u = cblk->user;
5349 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5350
Marco Nelissena1472d92012-03-30 14:36:54 -07005351 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352 framesReq = bufferEnd - u;
5353 }
5354
5355 buffer->frameCount = framesReq;
5356 buffer->raw = (void *)cblk->buffer(u);
5357 return NO_ERROR;
5358}
5359
5360
5361void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5362{
5363 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364
5365 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005366 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 delete [] pBuffer->mBuffer;
5368 delete pBuffer;
5369 }
5370 mBufferQueue.clear();
5371}
5372
5373// ----------------------------------------------------------------------------
5374
5375AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5376 : RefBase(),
5377 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005378 // 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 -07005379 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005380 mPid(pid),
5381 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382{
5383 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5384}
5385
5386// Client destructor must be called with AudioFlinger::mLock held
5387AudioFlinger::Client::~Client()
5388{
5389 mAudioFlinger->removeClient_l(mPid);
5390}
5391
Glenn Kasten435dbe62012-01-30 10:15:48 -08005392sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393{
5394 return mMemoryDealer;
5395}
5396
John Grossman4ff14ba2012-02-08 16:37:41 -08005397// Reserve one of the limited slots for a timed audio track associated
5398// with this client
5399bool AudioFlinger::Client::reserveTimedTrack()
5400{
5401 const int kMaxTimedTracksPerClient = 4;
5402
5403 Mutex::Autolock _l(mTimedTrackLock);
5404
5405 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5406 ALOGW("can not create timed track - pid %d has exceeded the limit",
5407 mPid);
5408 return false;
5409 }
5410
5411 mTimedTrackCount++;
5412 return true;
5413}
5414
5415// Release a slot for a timed audio track
5416void AudioFlinger::Client::releaseTimedTrack()
5417{
5418 Mutex::Autolock _l(mTimedTrackLock);
5419 mTimedTrackCount--;
5420}
5421
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422// ----------------------------------------------------------------------------
5423
5424AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5425 const sp<IAudioFlingerClient>& client,
5426 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005427 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428{
5429}
5430
5431AudioFlinger::NotificationClient::~NotificationClient()
5432{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433}
5434
5435void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5436{
5437 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005438 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439}
5440
5441// ----------------------------------------------------------------------------
5442
5443AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5444 : BnAudioTrack(),
5445 mTrack(track)
5446{
5447}
5448
5449AudioFlinger::TrackHandle::~TrackHandle() {
5450 // just stop the track on deletion, associated resources
5451 // will be freed from the main thread once all pending buffers have
5452 // been played. Unless it's not in the active track list, in which
5453 // case we free everything now...
5454 mTrack->destroy();
5455}
5456
Glenn Kasten90716c52012-01-26 13:40:12 -08005457sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5458 return mTrack->getCblk();
5459}
5460
Glenn Kasten3acbd052012-02-28 10:39:56 -08005461status_t AudioFlinger::TrackHandle::start() {
5462 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463}
5464
5465void AudioFlinger::TrackHandle::stop() {
5466 mTrack->stop();
5467}
5468
5469void AudioFlinger::TrackHandle::flush() {
5470 mTrack->flush();
5471}
5472
5473void AudioFlinger::TrackHandle::mute(bool e) {
5474 mTrack->mute(e);
5475}
5476
5477void AudioFlinger::TrackHandle::pause() {
5478 mTrack->pause();
5479}
5480
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5482{
5483 return mTrack->attachAuxEffect(EffectId);
5484}
5485
John Grossman4ff14ba2012-02-08 16:37:41 -08005486status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5487 sp<IMemory>* buffer) {
5488 if (!mTrack->isTimedTrack())
5489 return INVALID_OPERATION;
5490
5491 PlaybackThread::TimedTrack* tt =
5492 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5493 return tt->allocateTimedBuffer(size, buffer);
5494}
5495
5496status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5497 int64_t pts) {
5498 if (!mTrack->isTimedTrack())
5499 return INVALID_OPERATION;
5500
5501 PlaybackThread::TimedTrack* tt =
5502 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5503 return tt->queueTimedBuffer(buffer, pts);
5504}
5505
5506status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5507 const LinearTransform& xform, int target) {
5508
5509 if (!mTrack->isTimedTrack())
5510 return INVALID_OPERATION;
5511
5512 PlaybackThread::TimedTrack* tt =
5513 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5514 return tt->setMediaTimeTransform(
5515 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5516}
5517
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518status_t AudioFlinger::TrackHandle::onTransact(
5519 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5520{
5521 return BnAudioTrack::onTransact(code, data, reply, flags);
5522}
5523
5524// ----------------------------------------------------------------------------
5525
5526sp<IAudioRecord> AudioFlinger::openRecord(
5527 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005528 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005530 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005531 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005533 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 int *sessionId,
5535 status_t *status)
5536{
5537 sp<RecordThread::RecordTrack> recordTrack;
5538 sp<RecordHandle> recordHandle;
5539 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 status_t lStatus;
5541 RecordThread *thread;
5542 size_t inFrameCount;
5543 int lSessionId;
5544
5545 // check calling permissions
5546 if (!recordingAllowed()) {
5547 lStatus = PERMISSION_DENIED;
5548 goto Exit;
5549 }
5550
5551 // add client to list
5552 { // scope for mLock
5553 Mutex::Autolock _l(mLock);
5554 thread = checkRecordThread_l(input);
5555 if (thread == NULL) {
5556 lStatus = BAD_VALUE;
5557 goto Exit;
5558 }
5559
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005560 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561
5562 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005563 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 lSessionId = *sessionId;
5565 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005566 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 if (sessionId != NULL) {
5568 *sessionId = lSessionId;
5569 }
5570 }
5571 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005572 recordTrack = thread->createRecordTrack_l(client,
5573 sampleRate,
5574 format,
5575 channelMask,
5576 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005577 lSessionId,
5578 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005580 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5582 // destructor is called by the TrackBase destructor with mLock held
5583 client.clear();
5584 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 goto Exit;
5586 }
5587
5588 // return to handle to client
5589 recordHandle = new RecordHandle(recordTrack);
5590 lStatus = NO_ERROR;
5591
5592Exit:
5593 if (status) {
5594 *status = lStatus;
5595 }
5596 return recordHandle;
5597}
5598
5599// ----------------------------------------------------------------------------
5600
5601AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5602 : BnAudioRecord(),
5603 mRecordTrack(recordTrack)
5604{
5605}
5606
5607AudioFlinger::RecordHandle::~RecordHandle() {
5608 stop();
5609}
5610
Glenn Kasten90716c52012-01-26 13:40:12 -08005611sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5612 return mRecordTrack->getCblk();
5613}
5614
Glenn Kasten3acbd052012-02-28 10:39:56 -08005615status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005616 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005617 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618}
5619
5620void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005621 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 mRecordTrack->stop();
5623}
5624
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625status_t AudioFlinger::RecordHandle::onTransact(
5626 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5627{
5628 return BnAudioRecord::onTransact(code, data, reply, flags);
5629}
5630
5631// ----------------------------------------------------------------------------
5632
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005633AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5634 AudioStreamIn *input,
5635 uint32_t sampleRate,
5636 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005637 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005638 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005639 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005640 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5641 // mRsmpInIndex and mInputBytes set by readInputParameters()
5642 mReqChannelCount(popcount(channels)),
5643 mReqSampleRate(sampleRate)
5644 // mBytesRead is only meaningful while active, and so is cleared in start()
5645 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646{
Glenn Kasten480b4682012-02-28 12:30:08 -08005647 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005648
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 readInputParameters();
5650}
5651
5652
5653AudioFlinger::RecordThread::~RecordThread()
5654{
5655 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005656 delete mResampler;
5657 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658}
5659
5660void AudioFlinger::RecordThread::onFirstRef()
5661{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005662 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663}
5664
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005665status_t AudioFlinger::RecordThread::readyToRun()
5666{
5667 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005668 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005669 return status;
5670}
5671
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672bool AudioFlinger::RecordThread::threadLoop()
5673{
5674 AudioBufferProvider::Buffer buffer;
5675 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005676 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677
Eric Laurent44d98482010-09-30 16:12:31 -07005678 nsecs_t lastWarning = 0;
5679
Eric Laurentfeb0db62011-07-22 09:04:31 -07005680 acquireWakeLock();
5681
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 // start recording
5683 while (!exitPending()) {
5684
5685 processConfigEvents();
5686
5687 { // scope for mLock
5688 Mutex::Autolock _l(mLock);
5689 checkForNewParameters_l();
5690 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5691 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005692 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 mStandby = true;
5694 }
5695
5696 if (exitPending()) break;
5697
Eric Laurentfeb0db62011-07-22 09:04:31 -07005698 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005699 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 // go to sleep
5701 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005702 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005703 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 continue;
5705 }
5706 if (mActiveTrack != 0) {
5707 if (mActiveTrack->mState == TrackBase::PAUSING) {
5708 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005709 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 mStandby = true;
5711 }
5712 mActiveTrack.clear();
5713 mStartStopCond.broadcast();
5714 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5715 if (mReqChannelCount != mActiveTrack->channelCount()) {
5716 mActiveTrack.clear();
5717 mStartStopCond.broadcast();
5718 } else if (mBytesRead != 0) {
5719 // record start succeeds only if first read from audio input
5720 // succeeds
5721 if (mBytesRead > 0) {
5722 mActiveTrack->mState = TrackBase::ACTIVE;
5723 } else {
5724 mActiveTrack.clear();
5725 }
5726 mStartStopCond.broadcast();
5727 }
5728 mStandby = false;
5729 }
5730 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005731 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 }
5733
5734 if (mActiveTrack != 0) {
5735 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5736 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005737 unlockEffectChains(effectChains);
5738 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 continue;
5740 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005741 for (size_t i = 0; i < effectChains.size(); i ++) {
5742 effectChains[i]->process_l();
5743 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005744
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005746 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005748 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749 // no resampling
5750 while (framesOut) {
5751 size_t framesIn = mFrameCount - mRsmpInIndex;
5752 if (framesIn) {
5753 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5754 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5755 if (framesIn > framesOut)
5756 framesIn = framesOut;
5757 mRsmpInIndex += framesIn;
5758 framesOut -= framesIn;
5759 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005760 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 memcpy(dst, src, framesIn * mFrameSize);
5762 } else {
5763 int16_t *src16 = (int16_t *)src;
5764 int16_t *dst16 = (int16_t *)dst;
5765 if (mChannelCount == 1) {
5766 while (framesIn--) {
5767 *dst16++ = *src16;
5768 *dst16++ = *src16++;
5769 }
5770 } else {
5771 while (framesIn--) {
5772 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5773 src16 += 2;
5774 }
5775 }
5776 }
5777 }
5778 if (framesOut && mFrameCount == mRsmpInIndex) {
5779 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005780 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005781 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 framesOut = 0;
5783 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005784 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785 mRsmpInIndex = 0;
5786 }
5787 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005788 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5790 // Force input into standby so that it tries to
5791 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005792 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005793 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 }
5795 mRsmpInIndex = mFrameCount;
5796 framesOut = 0;
5797 buffer.frameCount = 0;
5798 }
5799 }
5800 }
5801 } else {
5802 // resampling
5803
5804 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5805 // alter output frame count as if we were expecting stereo samples
5806 if (mChannelCount == 1 && mReqChannelCount == 1) {
5807 framesOut >>= 1;
5808 }
5809 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5810 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5811 // are 32 bit aligned which should be always true.
5812 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005813 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814 // the resampler always outputs stereo samples: do post stereo to mono conversion
5815 int16_t *src = (int16_t *)mRsmpOutBuffer;
5816 int16_t *dst = buffer.i16;
5817 while (framesOut--) {
5818 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5819 src += 2;
5820 }
5821 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005822 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 }
5824
5825 }
Eric Laurenta011e352012-03-29 15:51:43 -07005826 if (mFramestoDrop == 0) {
5827 mActiveTrack->releaseBuffer(&buffer);
5828 } else {
5829 if (mFramestoDrop > 0) {
5830 mFramestoDrop -= buffer.frameCount;
5831 if (mFramestoDrop < 0) {
5832 mFramestoDrop = 0;
5833 }
5834 }
5835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 mActiveTrack->overflow();
5837 }
5838 // client isn't retrieving buffers fast enough
5839 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005840 if (!mActiveTrack->setOverflow()) {
5841 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005842 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005843 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005844 lastWarning = now;
5845 }
5846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 // Release the processor for a while before asking for a new buffer.
5848 // This will give the application more chance to read from the buffer and
5849 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 }
5852 }
Eric Laurentec437d82011-07-26 20:54:46 -07005853 // enable changes in effect chain
5854 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005855 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 }
5857
5858 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005859 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860 }
5861 mActiveTrack.clear();
5862
5863 mStartStopCond.broadcast();
5864
Eric Laurentfeb0db62011-07-22 09:04:31 -07005865 releaseWakeLock();
5866
Steve Block3856b092011-10-20 11:56:00 +01005867 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 return false;
5869}
5870
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005871
5872sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5873 const sp<AudioFlinger::Client>& client,
5874 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005875 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005876 int channelMask,
5877 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005878 int sessionId,
5879 status_t *status)
5880{
5881 sp<RecordTrack> track;
5882 status_t lStatus;
5883
5884 lStatus = initCheck();
5885 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005886 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887 goto Exit;
5888 }
5889
5890 { // scope for mLock
5891 Mutex::Autolock _l(mLock);
5892
5893 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005894 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005895
Glenn Kasten7378ca52012-01-20 13:44:40 -08005896 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005897 lStatus = NO_MEMORY;
5898 goto Exit;
5899 }
5900
5901 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005902 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5903 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005904 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005905 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5906 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005907 }
5908 lStatus = NO_ERROR;
5909
5910Exit:
5911 if (status) {
5912 *status = lStatus;
5913 }
5914 return track;
5915}
5916
Eric Laurenta011e352012-03-29 15:51:43 -07005917status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005918 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005919 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920{
Glenn Kasten58912562012-04-03 10:45:00 -07005921 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005922 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005924
5925 if (event == AudioSystem::SYNC_EVENT_NONE) {
5926 mSyncStartEvent.clear();
5927 mFramestoDrop = 0;
5928 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5929 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5930 triggerSession,
5931 recordTrack->sessionId(),
5932 syncStartEventCallback,
5933 this);
5934 mFramestoDrop = -1;
5935 }
5936
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005938 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939 if (mActiveTrack != 0) {
5940 if (recordTrack != mActiveTrack.get()) {
5941 status = -EBUSY;
5942 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5943 mActiveTrack->mState = TrackBase::ACTIVE;
5944 }
5945 return status;
5946 }
5947
5948 recordTrack->mState = TrackBase::IDLE;
5949 mActiveTrack = recordTrack;
5950 mLock.unlock();
5951 status_t status = AudioSystem::startInput(mId);
5952 mLock.lock();
5953 if (status != NO_ERROR) {
5954 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005955 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 return status;
5957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 mRsmpInIndex = mFrameCount;
5959 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005960 if (mResampler != NULL) {
5961 mResampler->reset();
5962 }
5963 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005965 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 mWaitWorkCV.signal();
5967 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005968 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 mActiveTrack.clear();
5970 status = INVALID_OPERATION;
5971 goto startError;
5972 }
5973 mStartStopCond.wait(mLock);
5974 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005975 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 status = BAD_VALUE;
5977 goto startError;
5978 }
Steve Block3856b092011-10-20 11:56:00 +01005979 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 return status;
5981 }
5982startError:
5983 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005984 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 return status;
5986}
5987
Eric Laurenta011e352012-03-29 15:51:43 -07005988void AudioFlinger::RecordThread::clearSyncStartEvent()
5989{
5990 if (mSyncStartEvent != 0) {
5991 mSyncStartEvent->cancel();
5992 }
5993 mSyncStartEvent.clear();
5994}
5995
5996void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5997{
5998 sp<SyncEvent> strongEvent = event.promote();
5999
6000 if (strongEvent != 0) {
6001 RecordThread *me = (RecordThread *)strongEvent->cookie();
6002 me->handleSyncStartEvent(strongEvent);
6003 }
6004}
6005
6006void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6007{
6008 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6009 mActiveTrack.get(),
6010 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6011 event->listenerSession());
6012
6013 if (mActiveTrack != 0 &&
6014 event == mSyncStartEvent) {
6015 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6016 // from audio HAL
6017 mFramestoDrop = mFrameCount * 2;
6018 mSyncStartEvent.clear();
6019 }
6020}
6021
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006023 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006024 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006026 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6028 mActiveTrack->mState = TrackBase::PAUSING;
6029 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006030 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 return;
6032 }
6033 mStartStopCond.wait(mLock);
6034 // if we have been restarted, recordTrack == mActiveTrack.get() here
6035 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6036 mLock.unlock();
6037 AudioSystem::stopInput(mId);
6038 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006039 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 }
6041 }
6042 }
6043}
6044
Eric Laurenta011e352012-03-29 15:51:43 -07006045bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6046{
6047 return false;
6048}
6049
6050status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6051{
6052 if (!isValidSyncEvent(event)) {
6053 return BAD_VALUE;
6054 }
6055
6056 Mutex::Autolock _l(mLock);
6057
6058 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6059 mTrack->setSyncEvent(event);
6060 return NO_ERROR;
6061 }
6062 return NAME_NOT_FOUND;
6063}
6064
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6066{
6067 const size_t SIZE = 256;
6068 char buffer[SIZE];
6069 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070
6071 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6072 result.append(buffer);
6073
6074 if (mActiveTrack != 0) {
6075 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006076 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 mActiveTrack->dump(buffer, SIZE);
6078 result.append(buffer);
6079
6080 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6081 result.append(buffer);
6082 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6083 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006084 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 result.append(buffer);
6086 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6087 result.append(buffer);
6088 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6089 result.append(buffer);
6090
6091
6092 } else {
6093 result.append("No record client\n");
6094 }
6095 write(fd, result.string(), result.size());
6096
6097 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006098 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099
6100 return NO_ERROR;
6101}
6102
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006103// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006104status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105{
6106 size_t framesReq = buffer->frameCount;
6107 size_t framesReady = mFrameCount - mRsmpInIndex;
6108 int channelCount;
6109
6110 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006111 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006113 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6115 // Force input into standby so that it tries to
6116 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006117 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006118 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006120 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 buffer->frameCount = 0;
6122 return NOT_ENOUGH_DATA;
6123 }
6124 mRsmpInIndex = 0;
6125 framesReady = mFrameCount;
6126 }
6127
6128 if (framesReq > framesReady) {
6129 framesReq = framesReady;
6130 }
6131
6132 if (mChannelCount == 1 && mReqChannelCount == 2) {
6133 channelCount = 1;
6134 } else {
6135 channelCount = 2;
6136 }
6137 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6138 buffer->frameCount = framesReq;
6139 return NO_ERROR;
6140}
6141
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006142// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6144{
6145 mRsmpInIndex += buffer->frameCount;
6146 buffer->frameCount = 0;
6147}
6148
6149bool AudioFlinger::RecordThread::checkForNewParameters_l()
6150{
6151 bool reconfig = false;
6152
6153 while (!mNewParameters.isEmpty()) {
6154 status_t status = NO_ERROR;
6155 String8 keyValuePair = mNewParameters[0];
6156 AudioParameter param = AudioParameter(keyValuePair);
6157 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006158 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159 int reqSamplingRate = mReqSampleRate;
6160 int reqChannelCount = mReqChannelCount;
6161
6162 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6163 reqSamplingRate = value;
6164 reconfig = true;
6165 }
6166 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006167 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 reconfig = true;
6169 }
6170 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006171 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 reconfig = true;
6173 }
6174 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6175 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006176 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 // if frame count is changed after track creation
6178 if (mActiveTrack != 0) {
6179 status = INVALID_OPERATION;
6180 } else {
6181 reconfig = true;
6182 }
6183 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006184 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6185 // forward device change to effects that have requested to be
6186 // aware of attached audio device.
6187 for (size_t i = 0; i < mEffectChains.size(); i++) {
6188 mEffectChains[i]->setDevice_l(value);
6189 }
6190 // store input device and output device but do not forward output device to audio HAL.
6191 // Note that status is ignored by the caller for output device
6192 // (see AudioFlinger::setParameters()
6193 if (value & AUDIO_DEVICE_OUT_ALL) {
6194 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6195 status = BAD_VALUE;
6196 } else {
6197 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006198 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6199 if (mTrack != NULL) {
6200 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006201 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006202 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6203 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6204 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006205 }
6206 mDevice |= (uint32_t)value;
6207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006209 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006211 mInput->stream->common.standby(&mInput->stream->common);
6212 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6213 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 }
6215 if (reconfig) {
6216 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006217 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006218 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006219 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006220 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6221 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 status = NO_ERROR;
6223 }
6224 if (status == NO_ERROR) {
6225 readInputParameters();
6226 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6227 }
6228 }
6229 }
6230
6231 mNewParameters.removeAt(0);
6232
6233 mParamStatus = status;
6234 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006235 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6236 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006237 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006238 }
6239 return reconfig;
6240}
6241
6242String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6243{
Dima Zavinfce7a472011-04-19 22:30:36 -07006244 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006245 String8 out_s8 = String8();
6246
6247 Mutex::Autolock _l(mLock);
6248 if (initCheck() != NO_ERROR) {
6249 return out_s8;
6250 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006251
Dima Zavin799a70e2011-04-18 16:57:27 -07006252 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006253 out_s8 = String8(s);
6254 free(s);
6255 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256}
6257
6258void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6259 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006260 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261
6262 switch (event) {
6263 case AudioSystem::INPUT_OPENED:
6264 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006265 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 desc.samplingRate = mSampleRate;
6267 desc.format = mFormat;
6268 desc.frameCount = mFrameCount;
6269 desc.latency = 0;
6270 param2 = &desc;
6271 break;
6272
6273 case AudioSystem::INPUT_CLOSED:
6274 default:
6275 break;
6276 }
6277 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6278}
6279
6280void AudioFlinger::RecordThread::readInputParameters()
6281{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006282 delete mRsmpInBuffer;
6283 // mRsmpInBuffer is always assigned a new[] below
6284 delete mRsmpOutBuffer;
6285 mRsmpOutBuffer = NULL;
6286 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006287 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288
Dima Zavin799a70e2011-04-18 16:57:27 -07006289 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006290 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6291 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006292 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006293 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006294 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006296 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6298
Glenn Kasten53d76db2012-03-08 12:32:47 -08006299 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 {
6301 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006302 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6303 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 if (mChannelCount == 1 && mReqChannelCount == 2) {
6305 channelCount = 1;
6306 } else {
6307 channelCount = 2;
6308 }
6309 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6310 mResampler->setSampleRate(mSampleRate);
6311 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6312 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6313
6314 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6315 if (mChannelCount == 1 && mReqChannelCount == 1) {
6316 mFrameCount >>= 1;
6317 }
6318
6319 }
6320 mRsmpInIndex = mFrameCount;
6321}
6322
6323unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6324{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006325 Mutex::Autolock _l(mLock);
6326 if (initCheck() != NO_ERROR) {
6327 return 0;
6328 }
6329
Dima Zavin799a70e2011-04-18 16:57:27 -07006330 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331}
6332
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006333uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6334{
6335 Mutex::Autolock _l(mLock);
6336 uint32_t result = 0;
6337 if (getEffectChain_l(sessionId) != 0) {
6338 result = EFFECT_SESSION;
6339 }
6340
6341 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6342 result |= TRACK_SESSION;
6343 }
6344
6345 return result;
6346}
6347
Eric Laurent59bd0da2011-08-01 09:52:20 -07006348AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6349{
6350 Mutex::Autolock _l(mLock);
6351 return mTrack;
6352}
6353
Glenn Kastenaed850d2012-01-26 09:46:34 -08006354AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006355{
6356 Mutex::Autolock _l(mLock);
6357 return mInput;
6358}
6359
6360AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6361{
6362 Mutex::Autolock _l(mLock);
6363 AudioStreamIn *input = mInput;
6364 mInput = NULL;
6365 return input;
6366}
6367
6368// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006369audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006370{
6371 if (mInput == NULL) {
6372 return NULL;
6373 }
6374 return &mInput->stream->common;
6375}
6376
6377
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378// ----------------------------------------------------------------------------
6379
Eric Laurenta4c5a552012-03-29 10:12:40 -07006380audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6381{
6382 if (!settingsAllowed()) {
6383 return 0;
6384 }
6385 Mutex::Autolock _l(mLock);
6386 return loadHwModule_l(name);
6387}
6388
6389// loadHwModule_l() must be called with AudioFlinger::mLock held
6390audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6391{
6392 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6393 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6394 ALOGW("loadHwModule() module %s already loaded", name);
6395 return mAudioHwDevs.keyAt(i);
6396 }
6397 }
6398
Eric Laurenta4c5a552012-03-29 10:12:40 -07006399 audio_hw_device_t *dev;
6400
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006401 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006402 if (rc) {
6403 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6404 return 0;
6405 }
6406
6407 mHardwareStatus = AUDIO_HW_INIT;
6408 rc = dev->init_check(dev);
6409 mHardwareStatus = AUDIO_HW_IDLE;
6410 if (rc) {
6411 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6412 return 0;
6413 }
6414
6415 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6416 (NULL != dev->set_master_volume)) {
6417 AutoMutex lock(mHardwareLock);
6418 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6419 dev->set_master_volume(dev, mMasterVolume);
6420 mHardwareStatus = AUDIO_HW_IDLE;
6421 }
6422
6423 audio_module_handle_t handle = nextUniqueId();
6424 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6425
6426 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006427 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006428
6429 return handle;
6430
6431}
6432
6433audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6434 audio_devices_t *pDevices,
6435 uint32_t *pSamplingRate,
6436 audio_format_t *pFormat,
6437 audio_channel_mask_t *pChannelMask,
6438 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006439 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440{
6441 status_t status;
6442 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006443 struct audio_config config = {
6444 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6445 channel_mask: pChannelMask ? *pChannelMask : 0,
6446 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6447 };
6448 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006449 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450
Eric Laurenta4c5a552012-03-29 10:12:40 -07006451 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6452 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006453 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006454 config.sample_rate,
6455 config.format,
6456 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006457 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458
6459 if (pDevices == NULL || *pDevices == 0) {
6460 return 0;
6461 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006462
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 Mutex::Autolock _l(mLock);
6464
Eric Laurenta4c5a552012-03-29 10:12:40 -07006465 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006466 if (outHwDev == NULL)
6467 return 0;
6468
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006469 audio_io_handle_t id = nextUniqueId();
6470
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006471 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006472
6473 status = outHwDev->open_output_stream(outHwDev,
6474 id,
6475 *pDevices,
6476 (audio_output_flags_t)flags,
6477 &config,
6478 &outStream);
6479
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006480 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006481 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006482 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006483 config.sample_rate,
6484 config.format,
6485 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 status);
6487
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006488 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006489 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006490
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006491 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006492 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6493 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006495 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 } else {
6497 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006498 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 }
6500 mPlaybackThreads.add(id, thread);
6501
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006502 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6503 if (pFormat != NULL) *pFormat = config.format;
6504 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006505 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506
6507 // notify client processes of the new output creation
6508 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006509
6510 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006511 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006512 ALOGI("Using module %d has the primary audio interface", module);
6513 mPrimaryHardwareDev = outHwDev;
6514
6515 AutoMutex lock(mHardwareLock);
6516 mHardwareStatus = AUDIO_HW_SET_MODE;
6517 outHwDev->set_mode(outHwDev, mMode);
6518
6519 // Determine the level of master volume support the primary audio HAL has,
6520 // and set the initial master volume at the same time.
6521 float initialVolume = 1.0;
6522 mMasterVolumeSupportLvl = MVS_NONE;
6523
6524 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6525 if ((NULL != outHwDev->get_master_volume) &&
6526 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6527 mMasterVolumeSupportLvl = MVS_FULL;
6528 } else {
6529 mMasterVolumeSupportLvl = MVS_SETONLY;
6530 initialVolume = 1.0;
6531 }
6532
6533 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6534 if ((NULL == outHwDev->set_master_volume) ||
6535 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6536 mMasterVolumeSupportLvl = MVS_NONE;
6537 }
6538 // now that we have a primary device, initialize master volume on other devices
6539 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6540 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6541
6542 if ((dev != mPrimaryHardwareDev) &&
6543 (NULL != dev->set_master_volume)) {
6544 dev->set_master_volume(dev, initialVolume);
6545 }
6546 }
6547 mHardwareStatus = AUDIO_HW_IDLE;
6548 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6549 ? initialVolume
6550 : 1.0;
6551 mMasterVolume = initialVolume;
6552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 return id;
6554 }
6555
6556 return 0;
6557}
6558
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006559audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6560 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561{
6562 Mutex::Autolock _l(mLock);
6563 MixerThread *thread1 = checkMixerThread_l(output1);
6564 MixerThread *thread2 = checkMixerThread_l(output2);
6565
6566 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006567 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 return 0;
6569 }
6570
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006571 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6573 thread->addOutputTrack(thread2);
6574 mPlaybackThreads.add(id, thread);
6575 // notify client processes of the new output creation
6576 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6577 return id;
6578}
6579
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006580status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581{
6582 // keep strong reference on the playback thread so that
6583 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006584 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 {
6586 Mutex::Autolock _l(mLock);
6587 thread = checkPlaybackThread_l(output);
6588 if (thread == NULL) {
6589 return BAD_VALUE;
6590 }
6591
Steve Block3856b092011-10-20 11:56:00 +01006592 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006594 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006596 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6598 dupThread->removeOutputTrack((MixerThread *)thread.get());
6599 }
6600 }
6601 }
Glenn Kastena1117922012-01-26 10:53:32 -08006602 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 mPlaybackThreads.removeItem(output);
6604 }
6605 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006606 // The thread entity (active unit of execution) is no longer running here,
6607 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006609 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006610 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006611 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006612 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006613 out->hwDev->close_output_stream(out->hwDev, out->stream);
6614 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 }
6616 return NO_ERROR;
6617}
6618
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006619status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620{
6621 Mutex::Autolock _l(mLock);
6622 PlaybackThread *thread = checkPlaybackThread_l(output);
6623
6624 if (thread == NULL) {
6625 return BAD_VALUE;
6626 }
6627
Steve Block3856b092011-10-20 11:56:00 +01006628 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 thread->suspend();
6630
6631 return NO_ERROR;
6632}
6633
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006634status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006635{
6636 Mutex::Autolock _l(mLock);
6637 PlaybackThread *thread = checkPlaybackThread_l(output);
6638
6639 if (thread == NULL) {
6640 return BAD_VALUE;
6641 }
6642
Steve Block3856b092011-10-20 11:56:00 +01006643 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644
6645 thread->restore();
6646
6647 return NO_ERROR;
6648}
6649
Eric Laurenta4c5a552012-03-29 10:12:40 -07006650audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6651 audio_devices_t *pDevices,
6652 uint32_t *pSamplingRate,
6653 audio_format_t *pFormat,
6654 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655{
6656 status_t status;
6657 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006658 struct audio_config config = {
6659 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6660 channel_mask: pChannelMask ? *pChannelMask : 0,
6661 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6662 };
6663 uint32_t reqSamplingRate = config.sample_rate;
6664 audio_format_t reqFormat = config.format;
6665 audio_channel_mask_t reqChannels = config.channel_mask;
6666 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006667 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668
6669 if (pDevices == NULL || *pDevices == 0) {
6670 return 0;
6671 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006672
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 Mutex::Autolock _l(mLock);
6674
Eric Laurenta4c5a552012-03-29 10:12:40 -07006675 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006676 if (inHwDev == NULL)
6677 return 0;
6678
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006679 audio_io_handle_t id = nextUniqueId();
6680
6681 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006682 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006683 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006684 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006685 config.sample_rate,
6686 config.format,
6687 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 status);
6689
6690 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6691 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6692 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006693 if (status == BAD_VALUE &&
6694 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6695 (config.sample_rate <= 2 * reqSamplingRate) &&
6696 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006697 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006698 inStream = NULL;
6699 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 }
6701
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006702 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006703 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6704
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006705 // Start record thread
6706 // RecorThread require both input and output device indication to forward to audio
6707 // pre processing modules
6708 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6709 thread = new RecordThread(this,
6710 input,
6711 reqSamplingRate,
6712 reqChannels,
6713 id,
6714 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006716 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006717 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006718 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006719 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720
Dima Zavin799a70e2011-04-18 16:57:27 -07006721 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722
6723 // notify client processes of the new input creation
6724 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6725 return id;
6726 }
6727
6728 return 0;
6729}
6730
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006731status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732{
6733 // keep strong reference on the record thread so that
6734 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006735 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 {
6737 Mutex::Autolock _l(mLock);
6738 thread = checkRecordThread_l(input);
6739 if (thread == NULL) {
6740 return BAD_VALUE;
6741 }
6742
Steve Block3856b092011-10-20 11:56:00 +01006743 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006744 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 mRecordThreads.removeItem(input);
6746 }
6747 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006748 // The thread entity (active unit of execution) is no longer running here,
6749 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006751 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006752 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006753 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006754 in->hwDev->close_input_stream(in->hwDev, in->stream);
6755 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756
6757 return NO_ERROR;
6758}
6759
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006760status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761{
6762 Mutex::Autolock _l(mLock);
6763 MixerThread *dstThread = checkMixerThread_l(output);
6764 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006765 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006766 return BAD_VALUE;
6767 }
6768
Steve Block3856b092011-10-20 11:56:00 +01006769 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006770 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6771
6772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6773 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006774 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 MixerThread *srcThread = (MixerThread *)thread;
6776 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 }
Eric Laurentde070132010-07-13 04:45:46 -07006778 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779
6780 return NO_ERROR;
6781}
6782
6783
6784int AudioFlinger::newAudioSessionId()
6785{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006786 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787}
6788
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006789void AudioFlinger::acquireAudioSessionId(int audioSession)
6790{
6791 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006792 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006793 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006794 size_t num = mAudioSessionRefs.size();
6795 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006796 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006797 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6798 ref->mCnt++;
6799 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006800 return;
6801 }
6802 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006803 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6804 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006805}
6806
6807void AudioFlinger::releaseAudioSessionId(int audioSession)
6808{
6809 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006810 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006811 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006812 size_t num = mAudioSessionRefs.size();
6813 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006814 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006815 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6816 ref->mCnt--;
6817 ALOGV(" decremented refcount to %d", ref->mCnt);
6818 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006819 mAudioSessionRefs.removeAt(i);
6820 delete ref;
6821 purgeStaleEffects_l();
6822 }
6823 return;
6824 }
6825 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006826 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006827}
6828
6829void AudioFlinger::purgeStaleEffects_l() {
6830
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006832
6833 Vector< sp<EffectChain> > chains;
6834
6835 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6836 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6837 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6838 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006839 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6840 chains.push(ec);
6841 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006842 }
6843 }
6844 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6845 sp<RecordThread> t = mRecordThreads.valueAt(i);
6846 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6847 sp<EffectChain> ec = t->mEffectChains[j];
6848 chains.push(ec);
6849 }
6850 }
6851
6852 for (size_t i = 0; i < chains.size(); i++) {
6853 sp<EffectChain> ec = chains[i];
6854 int sessionid = ec->sessionId();
6855 sp<ThreadBase> t = ec->mThread.promote();
6856 if (t == 0) {
6857 continue;
6858 }
6859 size_t numsessionrefs = mAudioSessionRefs.size();
6860 bool found = false;
6861 for (size_t k = 0; k < numsessionrefs; k++) {
6862 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006863 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006864 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006865 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006866 found = true;
6867 break;
6868 }
6869 }
6870 if (!found) {
6871 // remove all effects from the chain
6872 while (ec->mEffects.size()) {
6873 sp<EffectModule> effect = ec->mEffects[0];
6874 effect->unPin();
6875 Mutex::Autolock _l (t->mLock);
6876 t->removeEffect_l(effect);
6877 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6878 sp<EffectHandle> handle = effect->mHandles[j].promote();
6879 if (handle != 0) {
6880 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006881 if (handle->mHasControl && handle->mEnabled) {
6882 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6883 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006884 }
6885 }
6886 AudioSystem::unregisterEffect(effect->id());
6887 }
6888 }
6889 }
6890 return;
6891}
6892
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006894AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895{
Glenn Kastena1117922012-01-26 10:53:32 -08006896 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897}
6898
6899// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006900AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901{
6902 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006903 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904}
6905
6906// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006907AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908{
Glenn Kastena1117922012-01-26 10:53:32 -08006909 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910}
6911
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006912uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006914 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915}
6916
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006917AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006918{
6919 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6920 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006921 AudioStreamOut *output = thread->getOutput();
6922 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006923 return thread;
6924 }
6925 }
6926 return NULL;
6927}
6928
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006929uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006930{
6931 PlaybackThread *thread = primaryPlaybackThread_l();
6932
6933 if (thread == NULL) {
6934 return 0;
6935 }
6936
6937 return thread->device();
6938}
6939
Eric Laurenta011e352012-03-29 15:51:43 -07006940sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6941 int triggerSession,
6942 int listenerSession,
6943 sync_event_callback_t callBack,
6944 void *cookie)
6945{
6946 Mutex::Autolock _l(mLock);
6947
6948 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6949 status_t playStatus = NAME_NOT_FOUND;
6950 status_t recStatus = NAME_NOT_FOUND;
6951 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6952 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6953 if (playStatus == NO_ERROR) {
6954 return event;
6955 }
6956 }
6957 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6958 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6959 if (recStatus == NO_ERROR) {
6960 return event;
6961 }
6962 }
6963 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6964 mPendingSyncEvents.add(event);
6965 } else {
6966 ALOGV("createSyncEvent() invalid event %d", event->type());
6967 event.clear();
6968 }
6969 return event;
6970}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006971
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972// ----------------------------------------------------------------------------
6973// Effect management
6974// ----------------------------------------------------------------------------
6975
6976
Glenn Kastenf587ba52012-01-26 16:25:10 -08006977status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978{
6979 Mutex::Autolock _l(mLock);
6980 return EffectQueryNumberEffects(numEffects);
6981}
6982
Glenn Kastenf587ba52012-01-26 16:25:10 -08006983status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984{
6985 Mutex::Autolock _l(mLock);
6986 return EffectQueryEffect(index, descriptor);
6987}
6988
Glenn Kasten5e92a782012-01-30 07:40:52 -08006989status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006990 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991{
6992 Mutex::Autolock _l(mLock);
6993 return EffectGetDescriptor(pUuid, descriptor);
6994}
6995
6996
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6998 effect_descriptor_t *pDesc,
6999 const sp<IEffectClient>& effectClient,
7000 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007001 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002 int sessionId,
7003 status_t *status,
7004 int *id,
7005 int *enabled)
7006{
7007 status_t lStatus = NO_ERROR;
7008 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007011 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007012 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013
7014 if (pDesc == NULL) {
7015 lStatus = BAD_VALUE;
7016 goto Exit;
7017 }
7018
Eric Laurent84e9a102010-09-23 16:10:16 -07007019 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007020 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007021 lStatus = PERMISSION_DENIED;
7022 goto Exit;
7023 }
7024
Dima Zavinfce7a472011-04-19 22:30:36 -07007025 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007026 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007027 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007028 lStatus = PERMISSION_DENIED;
7029 goto Exit;
7030 }
7031
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007032 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007033 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007034 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007035 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007036 lStatus = BAD_VALUE;
7037 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007038 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007039 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007040 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007041 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007042 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007043 }
7044 }
7045
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 {
7047 Mutex::Autolock _l(mLock);
7048
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049
7050 if (!EffectIsNullUuid(&pDesc->uuid)) {
7051 // if uuid is specified, request effect descriptor
7052 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7053 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007054 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 goto Exit;
7056 }
7057 } else {
7058 // if uuid is not specified, look for an available implementation
7059 // of the required type in effect factory
7060 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007061 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062 lStatus = BAD_VALUE;
7063 goto Exit;
7064 }
7065 uint32_t numEffects = 0;
7066 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007067 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 bool found = false;
7069
7070 lStatus = EffectQueryNumberEffects(&numEffects);
7071 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007072 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 goto Exit;
7074 }
7075 for (uint32_t i = 0; i < numEffects; i++) {
7076 lStatus = EffectQueryEffect(i, &desc);
7077 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007078 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 continue;
7080 }
7081 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7082 // If matching type found save effect descriptor. If the session is
7083 // 0 and the effect is not auxiliary, continue enumeration in case
7084 // an auxiliary version of this effect type is available
7085 found = true;
7086 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007087 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7089 break;
7090 }
7091 }
7092 }
7093 if (!found) {
7094 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007095 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007096 goto Exit;
7097 }
7098 // For same effect type, chose auxiliary version over insert version if
7099 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007100 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7102 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7103 }
7104 }
7105
7106 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007107 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7109 lStatus = INVALID_OPERATION;
7110 goto Exit;
7111 }
7112
Eric Laurent59255e42011-07-27 19:49:51 -07007113 // check recording permission for visualizer
7114 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7115 !recordingAllowed()) {
7116 lStatus = PERMISSION_DENIED;
7117 goto Exit;
7118 }
7119
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 // return effect descriptor
7121 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7122
7123 // If output is not specified try to find a matching audio session ID in one of the
7124 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007125 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7126 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007127 // Note: io is never 0 when creating an effect on an input
7128 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007129 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007130 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7131 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007132 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007133 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007136 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007137 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7138 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7139 io = mRecordThreads.keyAt(i);
7140 break;
7141 }
7142 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007143 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007144 // If no output thread contains the requested session ID, default to
7145 // first output. The effect chain will be moved to the correct output
7146 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007147 if (io == 0 && mPlaybackThreads.size()) {
7148 io = mPlaybackThreads.keyAt(0);
7149 }
Steve Block3856b092011-10-20 11:56:00 +01007150 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007151 }
7152 ThreadBase *thread = checkRecordThread_l(io);
7153 if (thread == NULL) {
7154 thread = checkPlaybackThread_l(io);
7155 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007156 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007157 lStatus = BAD_VALUE;
7158 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007161
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007162 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007164 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007165 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7166 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167 if (handle != 0 && id != NULL) {
7168 *id = handle->id();
7169 }
7170 }
7171
7172Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007173 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174 *status = lStatus;
7175 }
7176 return handle;
7177}
7178
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007179status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7180 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007181{
Steve Block3856b092011-10-20 11:56:00 +01007182 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007183 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007184 Mutex::Autolock _l(mLock);
7185 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007186 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007187 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 }
Eric Laurentde070132010-07-13 04:45:46 -07007189 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7190 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007191 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007192 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 }
Eric Laurentde070132010-07-13 04:45:46 -07007194 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7195 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007196 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007197 return BAD_VALUE;
7198 }
7199
7200 Mutex::Autolock _dl(dstThread->mLock);
7201 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007202 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007203
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 return NO_ERROR;
7205}
7206
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007207// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007208status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007209 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007210 AudioFlinger::PlaybackThread *dstThread,
7211 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007212{
Steve Block3856b092011-10-20 11:56:00 +01007213 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007214 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007215
Eric Laurent59255e42011-07-27 19:49:51 -07007216 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007217 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007218 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007219 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007220 return INVALID_OPERATION;
7221 }
7222
Eric Laurent39e94f82010-07-28 01:32:47 -07007223 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007224 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007225 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007226 // removed.
7227 srcThread->removeEffectChain_l(chain);
7228
7229 // transfer all effects one by one so that new effect chain is created on new thread with
7230 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007231 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007232 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007233 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007234 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7235 while (effect != 0) {
7236 srcThread->removeEffect_l(effect);
7237 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007238 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7239 if (effect->state() == EffectModule::ACTIVE ||
7240 effect->state() == EffectModule::STOPPING) {
7241 effect->start();
7242 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007243 // if the move request is not received from audio policy manager, the effect must be
7244 // re-registered with the new strategy and output
7245 if (dstChain == 0) {
7246 dstChain = effect->chain().promote();
7247 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007248 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007249 srcThread->addEffect_l(effect);
7250 return NO_INIT;
7251 }
7252 strategy = dstChain->strategy();
7253 }
7254 if (reRegister) {
7255 AudioSystem::unregisterEffect(effect->id());
7256 AudioSystem::registerEffect(&effect->desc(),
7257 dstOutput,
7258 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007259 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007260 effect->id());
7261 }
Eric Laurentde070132010-07-13 04:45:46 -07007262 effect = chain->getEffectFromId_l(0);
7263 }
7264
7265 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266}
7267
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007268
Mathias Agopian65ab4712010-07-14 17:59:35 -07007269// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007270sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271 const sp<AudioFlinger::Client>& client,
7272 const sp<IEffectClient>& effectClient,
7273 int32_t priority,
7274 int sessionId,
7275 effect_descriptor_t *desc,
7276 int *enabled,
7277 status_t *status
7278 )
7279{
7280 sp<EffectModule> effect;
7281 sp<EffectHandle> handle;
7282 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007284 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 bool effectCreated = false;
7286 bool effectRegistered = false;
7287
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007288 lStatus = initCheck();
7289 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007290 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291 goto Exit;
7292 }
7293
7294 // Do not allow effects with session ID 0 on direct output or duplicating threads
7295 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007296 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007297 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007298 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299 lStatus = BAD_VALUE;
7300 goto Exit;
7301 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007302 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007303 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007304 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007305 desc->name, desc->flags, mType);
7306 lStatus = BAD_VALUE;
7307 goto Exit;
7308 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309
Steve Block3856b092011-10-20 11:56:00 +01007310 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311
7312 { // scope for mLock
7313 Mutex::Autolock _l(mLock);
7314
7315 // check for existing effect chain with the requested audio session
7316 chain = getEffectChain_l(sessionId);
7317 if (chain == 0) {
7318 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007319 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 chain = new EffectChain(this, sessionId);
7321 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007322 chain->setStrategy(getStrategyForSession_l(sessionId));
7323 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007325 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 }
7327
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007328 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329
7330 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007331 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007333 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 if (lStatus != NO_ERROR) {
7335 goto Exit;
7336 }
7337 effectRegistered = true;
7338 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007339 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340 lStatus = effect->status();
7341 if (lStatus != NO_ERROR) {
7342 goto Exit;
7343 }
Eric Laurentcab11242010-07-15 12:50:15 -07007344 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 if (lStatus != NO_ERROR) {
7346 goto Exit;
7347 }
7348 effectCreated = true;
7349
7350 effect->setDevice(mDevice);
7351 effect->setMode(mAudioFlinger->getMode());
7352 }
7353 // create effect handle and connect it to effect module
7354 handle = new EffectHandle(effect, client, effectClient, priority);
7355 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007356 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 *enabled = (int)effect->isEnabled();
7358 }
7359 }
7360
7361Exit:
7362 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007363 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007365 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 }
7367 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007368 AudioSystem::unregisterEffect(effect->id());
7369 }
7370 if (chainCreated) {
7371 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 }
7373 handle.clear();
7374 }
7375
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007376 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 *status = lStatus;
7378 }
7379 return handle;
7380}
7381
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007382sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7383{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007384 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007385 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007386}
7387
Eric Laurentde070132010-07-13 04:45:46 -07007388// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7389// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007390status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007391{
7392 // check for existing effect chain with the requested audio session
7393 int sessionId = effect->sessionId();
7394 sp<EffectChain> chain = getEffectChain_l(sessionId);
7395 bool chainCreated = false;
7396
7397 if (chain == 0) {
7398 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007399 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007400 chain = new EffectChain(this, sessionId);
7401 addEffectChain_l(chain);
7402 chain->setStrategy(getStrategyForSession_l(sessionId));
7403 chainCreated = true;
7404 }
Steve Block3856b092011-10-20 11:56:00 +01007405 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007406
7407 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007408 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007409 this, effect->desc().name, chain.get());
7410 return BAD_VALUE;
7411 }
7412
7413 status_t status = chain->addEffect_l(effect);
7414 if (status != NO_ERROR) {
7415 if (chainCreated) {
7416 removeEffectChain_l(chain);
7417 }
7418 return status;
7419 }
7420
7421 effect->setDevice(mDevice);
7422 effect->setMode(mAudioFlinger->getMode());
7423 return NO_ERROR;
7424}
7425
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007427
Steve Block3856b092011-10-20 11:56:00 +01007428 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007430 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7431 detachAuxEffect_l(effect->id());
7432 }
7433
7434 sp<EffectChain> chain = effect->chain().promote();
7435 if (chain != 0) {
7436 // remove effect chain if removing last effect
7437 if (chain->removeEffect_l(effect) == 0) {
7438 removeEffectChain_l(chain);
7439 }
7440 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007441 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007442 }
7443}
7444
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007445void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007446 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007447{
7448 effectChains = mEffectChains;
7449 for (size_t i = 0; i < mEffectChains.size(); i++) {
7450 mEffectChains[i]->lock();
7451 }
7452}
7453
7454void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007455 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456{
7457 for (size_t i = 0; i < effectChains.size(); i++) {
7458 effectChains[i]->unlock();
7459 }
7460}
7461
7462sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7463{
7464 Mutex::Autolock _l(mLock);
7465 return getEffectChain_l(sessionId);
7466}
7467
7468sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7469{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007470 size_t size = mEffectChains.size();
7471 for (size_t i = 0; i < size; i++) {
7472 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007473 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007474 }
7475 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007476 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007477}
7478
Glenn Kastenf78aee72012-01-04 11:00:47 -08007479void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007480{
7481 Mutex::Autolock _l(mLock);
7482 size_t size = mEffectChains.size();
7483 for (size_t i = 0; i < size; i++) {
7484 mEffectChains[i]->setMode_l(mode);
7485 }
7486}
7487
7488void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007489 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007490 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007491
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007493 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007494 // delete the effect module if removing last handle on it
7495 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007496 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007497 removeEffect_l(effect);
7498 AudioSystem::unregisterEffect(effect->id());
7499 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500 }
7501}
7502
7503status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7504{
7505 int session = chain->sessionId();
7506 int16_t *buffer = mMixBuffer;
7507 bool ownsBuffer = false;
7508
Steve Block3856b092011-10-20 11:56:00 +01007509 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510 if (session > 0) {
7511 // Only one effect chain can be present in direct output thread and it uses
7512 // the mix buffer as input
7513 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007514 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515 buffer = new int16_t[numSamples];
7516 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007517 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518 ownsBuffer = true;
7519 }
7520
7521 // Attach all tracks with same session ID to this chain.
7522 for (size_t i = 0; i < mTracks.size(); ++i) {
7523 sp<Track> track = mTracks[i];
7524 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007525 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007527 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007528 }
7529 }
7530
7531 // indicate all active tracks in the chain
7532 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7533 sp<Track> track = mActiveTracks[i].promote();
7534 if (track == 0) continue;
7535 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007536 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007537 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538 }
7539 }
7540 }
7541
7542 chain->setInBuffer(buffer, ownsBuffer);
7543 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007544 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007545 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007546 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7547 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007549 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7550 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007551 // Effect chain for other sessions are inserted at beginning of effect
7552 // chains list to be processed before output mix effects. Relative order between other
7553 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 size_t size = mEffectChains.size();
7555 size_t i = 0;
7556 for (i = 0; i < size; i++) {
7557 if (mEffectChains[i]->sessionId() < session) break;
7558 }
7559 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007560 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561
7562 return NO_ERROR;
7563}
7564
7565size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7566{
7567 int session = chain->sessionId();
7568
Steve Block3856b092011-10-20 11:56:00 +01007569 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007570
7571 for (size_t i = 0; i < mEffectChains.size(); i++) {
7572 if (chain == mEffectChains[i]) {
7573 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007574 // detach all active tracks from the chain
7575 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7576 sp<Track> track = mActiveTracks[i].promote();
7577 if (track == 0) continue;
7578 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007579 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007580 chain.get(), session);
7581 chain->decActiveTrackCnt();
7582 }
7583 }
7584
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 // detach all tracks with same session ID from this chain
7586 for (size_t i = 0; i < mTracks.size(); ++i) {
7587 sp<Track> track = mTracks[i];
7588 if (session == track->sessionId()) {
7589 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007590 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 }
7592 }
Eric Laurentde070132010-07-13 04:45:46 -07007593 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594 }
7595 }
7596 return mEffectChains.size();
7597}
7598
Eric Laurentde070132010-07-13 04:45:46 -07007599status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7600 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601{
7602 Mutex::Autolock _l(mLock);
7603 return attachAuxEffect_l(track, EffectId);
7604}
7605
Eric Laurentde070132010-07-13 04:45:46 -07007606status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7607 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608{
7609 status_t status = NO_ERROR;
7610
7611 if (EffectId == 0) {
7612 track->setAuxBuffer(0, NULL);
7613 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007614 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7615 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 if (effect != 0) {
7617 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7618 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7619 } else {
7620 status = INVALID_OPERATION;
7621 }
7622 } else {
7623 status = BAD_VALUE;
7624 }
7625 }
7626 return status;
7627}
7628
7629void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7630{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007631 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 sp<Track> track = mTracks[i];
7633 if (track->auxEffectId() == effectId) {
7634 attachAuxEffect_l(track, 0);
7635 }
7636 }
7637}
7638
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007639status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7640{
7641 // only one chain per input thread
7642 if (mEffectChains.size() != 0) {
7643 return INVALID_OPERATION;
7644 }
Steve Block3856b092011-10-20 11:56:00 +01007645 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007646
7647 chain->setInBuffer(NULL);
7648 chain->setOutBuffer(NULL);
7649
Eric Laurent59255e42011-07-27 19:49:51 -07007650 checkSuspendOnAddEffectChain_l(chain);
7651
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652 mEffectChains.add(chain);
7653
7654 return NO_ERROR;
7655}
7656
7657size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7658{
Steve Block3856b092011-10-20 11:56:00 +01007659 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007660 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007661 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7662 chain.get(), mEffectChains.size(), this);
7663 if (mEffectChains.size() == 1) {
7664 mEffectChains.removeAt(0);
7665 }
7666 return 0;
7667}
7668
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669// ----------------------------------------------------------------------------
7670// EffectModule implementation
7671// ----------------------------------------------------------------------------
7672
7673#undef LOG_TAG
7674#define LOG_TAG "AudioFlinger::EffectModule"
7675
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007676AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677 const wp<AudioFlinger::EffectChain>& chain,
7678 effect_descriptor_t *desc,
7679 int id,
7680 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007681 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007682 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683{
Steve Block3856b092011-10-20 11:56:00 +01007684 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007686 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 return;
7688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689
7690 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7691
7692 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007693 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694
7695 if (mStatus != NO_ERROR) {
7696 return;
7697 }
7698 lStatus = init();
7699 if (lStatus < 0) {
7700 mStatus = lStatus;
7701 goto Error;
7702 }
7703
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007704 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7705 mPinned = true;
7706 }
Steve Block3856b092011-10-20 11:56:00 +01007707 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 return;
7709Error:
7710 EffectRelease(mEffectInterface);
7711 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007712 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713}
7714
7715AudioFlinger::EffectModule::~EffectModule()
7716{
Steve Block3856b092011-10-20 11:56:00 +01007717 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007719 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7720 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7721 sp<ThreadBase> thread = mThread.promote();
7722 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007723 audio_stream_t *stream = thread->stream();
7724 if (stream != NULL) {
7725 stream->remove_audio_effect(stream, mEffectInterface);
7726 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007727 }
7728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 // release effect engine
7730 EffectRelease(mEffectInterface);
7731 }
7732}
7733
Glenn Kasten435dbe62012-01-30 10:15:48 -08007734status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735{
7736 status_t status;
7737
7738 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007739 int priority = handle->priority();
7740 size_t size = mHandles.size();
7741 sp<EffectHandle> h;
7742 size_t i;
7743 for (i = 0; i < size; i++) {
7744 h = mHandles[i].promote();
7745 if (h == 0) continue;
7746 if (h->priority() <= priority) break;
7747 }
7748 // if inserted in first place, move effect control from previous owner to this handle
7749 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007750 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007752 enabled = h->enabled();
7753 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 }
Eric Laurent59255e42011-07-27 19:49:51 -07007755 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 status = NO_ERROR;
7757 } else {
7758 status = ALREADY_EXISTS;
7759 }
Steve Block3856b092011-10-20 11:56:00 +01007760 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761 mHandles.insertAt(handle, i);
7762 return status;
7763}
7764
7765size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7766{
7767 Mutex::Autolock _l(mLock);
7768 size_t size = mHandles.size();
7769 size_t i;
7770 for (i = 0; i < size; i++) {
7771 if (mHandles[i] == handle) break;
7772 }
7773 if (i == size) {
7774 return size;
7775 }
Steve Block3856b092011-10-20 11:56:00 +01007776 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007777
7778 bool enabled = false;
7779 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007780 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007781 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007782 enabled = hdl->enabled();
7783 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 mHandles.removeAt(i);
7785 size = mHandles.size();
7786 // if removed from first place, move effect control from this handle to next in line
7787 if (i == 0 && size != 0) {
7788 sp<EffectHandle> h = mHandles[0].promote();
7789 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007790 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 }
7792 }
7793
Eric Laurentec437d82011-07-26 20:54:46 -07007794 // Prevent calls to process() and other functions on effect interface from now on.
7795 // The effect engine will be released by the destructor when the last strong reference on
7796 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007797 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007798 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007799 }
7800
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 return size;
7802}
7803
Eric Laurent59255e42011-07-27 19:49:51 -07007804sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7805{
7806 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007807 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007808}
7809
Glenn Kasten58123c32012-02-03 10:32:24 -08007810void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007812 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007813 // keep a strong reference on this EffectModule to avoid calling the
7814 // destructor before we exit
7815 sp<EffectModule> keep(this);
7816 {
7817 sp<ThreadBase> thread = mThread.promote();
7818 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007819 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 }
7821 }
7822}
7823
7824void AudioFlinger::EffectModule::updateState() {
7825 Mutex::Autolock _l(mLock);
7826
7827 switch (mState) {
7828 case RESTART:
7829 reset_l();
7830 // FALL THROUGH
7831
7832 case STARTING:
7833 // clear auxiliary effect input buffer for next accumulation
7834 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7835 memset(mConfig.inputCfg.buffer.raw,
7836 0,
7837 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7838 }
7839 start_l();
7840 mState = ACTIVE;
7841 break;
7842 case STOPPING:
7843 stop_l();
7844 mDisableWaitCnt = mMaxDisableWaitCnt;
7845 mState = STOPPED;
7846 break;
7847 case STOPPED:
7848 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7849 // turn off sequence.
7850 if (--mDisableWaitCnt == 0) {
7851 reset_l();
7852 mState = IDLE;
7853 }
7854 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007855 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 break;
7857 }
7858}
7859
7860void AudioFlinger::EffectModule::process()
7861{
7862 Mutex::Autolock _l(mLock);
7863
Eric Laurentec437d82011-07-26 20:54:46 -07007864 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007865 mConfig.inputCfg.buffer.raw == NULL ||
7866 mConfig.outputCfg.buffer.raw == NULL) {
7867 return;
7868 }
7869
Eric Laurent8f45bd72010-08-31 13:50:07 -07007870 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7872 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007873 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007875 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 }
7877
7878 // do the actual processing in the effect engine
7879 int ret = (*mEffectInterface)->process(mEffectInterface,
7880 &mConfig.inputCfg.buffer,
7881 &mConfig.outputCfg.buffer);
7882
7883 // force transition to IDLE state when engine is ready
7884 if (mState == STOPPED && ret == -ENODATA) {
7885 mDisableWaitCnt = 1;
7886 }
7887
7888 // clear auxiliary effect input buffer for next accumulation
7889 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007890 memset(mConfig.inputCfg.buffer.raw, 0,
7891 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892 }
7893 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007894 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7895 // If an insert effect is idle and input buffer is different from output buffer,
7896 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007897 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007898 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007899 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7900 int16_t *in = mConfig.inputCfg.buffer.s16;
7901 int16_t *out = mConfig.outputCfg.buffer.s16;
7902 for (size_t i = 0; i < frameCnt; i++) {
7903 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905 }
7906 }
7907}
7908
7909void AudioFlinger::EffectModule::reset_l()
7910{
7911 if (mEffectInterface == NULL) {
7912 return;
7913 }
7914 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7915}
7916
7917status_t AudioFlinger::EffectModule::configure()
7918{
7919 uint32_t channels;
7920 if (mEffectInterface == NULL) {
7921 return NO_INIT;
7922 }
7923
7924 sp<ThreadBase> thread = mThread.promote();
7925 if (thread == 0) {
7926 return DEAD_OBJECT;
7927 }
7928
7929 // TODO: handle configuration of effects replacing track process
7930 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007931 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007933 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007934 }
7935
7936 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007937 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 } else {
7939 mConfig.inputCfg.channels = channels;
7940 }
7941 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007942 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7943 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 mConfig.inputCfg.samplingRate = thread->sampleRate();
7945 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7946 mConfig.inputCfg.bufferProvider.cookie = NULL;
7947 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7948 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7949 mConfig.outputCfg.bufferProvider.cookie = NULL;
7950 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7951 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7952 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7953 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007954 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007955 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 // - in other sessions:
7957 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7958 // other effect: overwrites output buffer: input buffer == output buffer
7959 // Auxiliary effect:
7960 // accumulates in output buffer: input buffer != output buffer
7961 // Therefore: accumulate <=> input buffer != output buffer
7962 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7963 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7964 } else {
7965 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7966 }
7967 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7968 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7969 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7970 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7971
Steve Block3856b092011-10-20 11:56:00 +01007972 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007973 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7974
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007976 uint32_t size = sizeof(int);
7977 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007978 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007979 sizeof(effect_config_t),
7980 &mConfig,
7981 &size,
7982 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 if (status == 0) {
7984 status = cmdStatus;
7985 }
7986
7987 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7988 (1000 * mConfig.outputCfg.buffer.frameCount);
7989
7990 return status;
7991}
7992
7993status_t AudioFlinger::EffectModule::init()
7994{
7995 Mutex::Autolock _l(mLock);
7996 if (mEffectInterface == NULL) {
7997 return NO_INIT;
7998 }
7999 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008000 uint32_t size = sizeof(status_t);
8001 status_t status = (*mEffectInterface)->command(mEffectInterface,
8002 EFFECT_CMD_INIT,
8003 0,
8004 NULL,
8005 &size,
8006 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 if (status == 0) {
8008 status = cmdStatus;
8009 }
8010 return status;
8011}
8012
Eric Laurentec35a142011-10-05 17:42:25 -07008013status_t AudioFlinger::EffectModule::start()
8014{
8015 Mutex::Autolock _l(mLock);
8016 return start_l();
8017}
8018
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019status_t AudioFlinger::EffectModule::start_l()
8020{
8021 if (mEffectInterface == NULL) {
8022 return NO_INIT;
8023 }
8024 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008025 uint32_t size = sizeof(status_t);
8026 status_t status = (*mEffectInterface)->command(mEffectInterface,
8027 EFFECT_CMD_ENABLE,
8028 0,
8029 NULL,
8030 &size,
8031 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032 if (status == 0) {
8033 status = cmdStatus;
8034 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008035 if (status == 0 &&
8036 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8037 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8038 sp<ThreadBase> thread = mThread.promote();
8039 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008040 audio_stream_t *stream = thread->stream();
8041 if (stream != NULL) {
8042 stream->add_audio_effect(stream, mEffectInterface);
8043 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008044 }
8045 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 return status;
8047}
8048
Eric Laurentec437d82011-07-26 20:54:46 -07008049status_t AudioFlinger::EffectModule::stop()
8050{
8051 Mutex::Autolock _l(mLock);
8052 return stop_l();
8053}
8054
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055status_t AudioFlinger::EffectModule::stop_l()
8056{
8057 if (mEffectInterface == NULL) {
8058 return NO_INIT;
8059 }
8060 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008061 uint32_t size = sizeof(status_t);
8062 status_t status = (*mEffectInterface)->command(mEffectInterface,
8063 EFFECT_CMD_DISABLE,
8064 0,
8065 NULL,
8066 &size,
8067 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068 if (status == 0) {
8069 status = cmdStatus;
8070 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008071 if (status == 0 &&
8072 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8073 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8074 sp<ThreadBase> thread = mThread.promote();
8075 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008076 audio_stream_t *stream = thread->stream();
8077 if (stream != NULL) {
8078 stream->remove_audio_effect(stream, mEffectInterface);
8079 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008080 }
8081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082 return status;
8083}
8084
Eric Laurent25f43952010-07-28 05:40:18 -07008085status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8086 uint32_t cmdSize,
8087 void *pCmdData,
8088 uint32_t *replySize,
8089 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008090{
8091 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008092// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093
Eric Laurentec437d82011-07-26 20:54:46 -07008094 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095 return NO_INIT;
8096 }
Eric Laurent25f43952010-07-28 05:40:18 -07008097 status_t status = (*mEffectInterface)->command(mEffectInterface,
8098 cmdCode,
8099 cmdSize,
8100 pCmdData,
8101 replySize,
8102 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008103 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008104 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105 for (size_t i = 1; i < mHandles.size(); i++) {
8106 sp<EffectHandle> h = mHandles[i].promote();
8107 if (h != 0) {
8108 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8109 }
8110 }
8111 }
8112 return status;
8113}
8114
8115status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8116{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008117
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008119 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120
8121 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008122 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8123 if (enabled && status != NO_ERROR) {
8124 return status;
8125 }
8126
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127 switch (mState) {
8128 // going from disabled to enabled
8129 case IDLE:
8130 mState = STARTING;
8131 break;
8132 case STOPPED:
8133 mState = RESTART;
8134 break;
8135 case STOPPING:
8136 mState = ACTIVE;
8137 break;
8138
8139 // going from enabled to disabled
8140 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008141 mState = STOPPED;
8142 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008143 case STARTING:
8144 mState = IDLE;
8145 break;
8146 case ACTIVE:
8147 mState = STOPPING;
8148 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008149 case DESTROYED:
8150 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151 }
8152 for (size_t i = 1; i < mHandles.size(); i++) {
8153 sp<EffectHandle> h = mHandles[i].promote();
8154 if (h != 0) {
8155 h->setEnabled(enabled);
8156 }
8157 }
8158 }
8159 return NO_ERROR;
8160}
8161
Glenn Kastenc59c0042012-02-02 14:06:11 -08008162bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163{
8164 switch (mState) {
8165 case RESTART:
8166 case STARTING:
8167 case ACTIVE:
8168 return true;
8169 case IDLE:
8170 case STOPPING:
8171 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008172 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 default:
8174 return false;
8175 }
8176}
8177
Glenn Kastenc59c0042012-02-02 14:06:11 -08008178bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008179{
8180 switch (mState) {
8181 case RESTART:
8182 case ACTIVE:
8183 case STOPPING:
8184 case STOPPED:
8185 return true;
8186 case IDLE:
8187 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008188 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008189 default:
8190 return false;
8191 }
8192}
8193
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8195{
8196 Mutex::Autolock _l(mLock);
8197 status_t status = NO_ERROR;
8198
8199 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8200 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008201 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008202 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8203 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008204 status_t cmdStatus;
8205 uint32_t volume[2];
8206 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008207 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208 volume[0] = *left;
8209 volume[1] = *right;
8210 if (controller) {
8211 pVolume = volume;
8212 }
Eric Laurent25f43952010-07-28 05:40:18 -07008213 status = (*mEffectInterface)->command(mEffectInterface,
8214 EFFECT_CMD_SET_VOLUME,
8215 size,
8216 volume,
8217 &size,
8218 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8220 *left = volume[0];
8221 *right = volume[1];
8222 }
8223 }
8224 return status;
8225}
8226
8227status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8228{
8229 Mutex::Autolock _l(mLock);
8230 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008231 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8232 // audio pre processing modules on RecordThread can receive both output and
8233 // input device indication in the same call
8234 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8235 if (dev) {
8236 status_t cmdStatus;
8237 uint32_t size = sizeof(status_t);
8238
8239 status = (*mEffectInterface)->command(mEffectInterface,
8240 EFFECT_CMD_SET_DEVICE,
8241 sizeof(uint32_t),
8242 &dev,
8243 &size,
8244 &cmdStatus);
8245 if (status == NO_ERROR) {
8246 status = cmdStatus;
8247 }
8248 }
8249 dev = device & AUDIO_DEVICE_IN_ALL;
8250 if (dev) {
8251 status_t cmdStatus;
8252 uint32_t size = sizeof(status_t);
8253
8254 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8255 EFFECT_CMD_SET_INPUT_DEVICE,
8256 sizeof(uint32_t),
8257 &dev,
8258 &size,
8259 &cmdStatus);
8260 if (status2 == NO_ERROR) {
8261 status2 = cmdStatus;
8262 }
8263 if (status == NO_ERROR) {
8264 status = status2;
8265 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008266 }
8267 }
8268 return status;
8269}
8270
Glenn Kastenf78aee72012-01-04 11:00:47 -08008271status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272{
8273 Mutex::Autolock _l(mLock);
8274 status_t status = NO_ERROR;
8275 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008276 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008277 uint32_t size = sizeof(status_t);
8278 status = (*mEffectInterface)->command(mEffectInterface,
8279 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008280 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008281 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008282 &size,
8283 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008284 if (status == NO_ERROR) {
8285 status = cmdStatus;
8286 }
8287 }
8288 return status;
8289}
8290
Eric Laurent59255e42011-07-27 19:49:51 -07008291void AudioFlinger::EffectModule::setSuspended(bool suspended)
8292{
8293 Mutex::Autolock _l(mLock);
8294 mSuspended = suspended;
8295}
Glenn Kastena3a85482012-01-04 11:01:11 -08008296
8297bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008298{
8299 Mutex::Autolock _l(mLock);
8300 return mSuspended;
8301}
8302
Mathias Agopian65ab4712010-07-14 17:59:35 -07008303status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8304{
8305 const size_t SIZE = 256;
8306 char buffer[SIZE];
8307 String8 result;
8308
8309 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8310 result.append(buffer);
8311
8312 bool locked = tryLock(mLock);
8313 // failed to lock - AudioFlinger is probably deadlocked
8314 if (!locked) {
8315 result.append("\t\tCould not lock Fx mutex:\n");
8316 }
8317
8318 result.append("\t\tSession Status State Engine:\n");
8319 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8320 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8321 result.append(buffer);
8322
8323 result.append("\t\tDescriptor:\n");
8324 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8325 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8326 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8327 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8328 result.append(buffer);
8329 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8330 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8331 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8332 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8333 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008334 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335 mDescriptor.apiVersion,
8336 mDescriptor.flags);
8337 result.append(buffer);
8338 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8339 mDescriptor.name);
8340 result.append(buffer);
8341 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8342 mDescriptor.implementor);
8343 result.append(buffer);
8344
8345 result.append("\t\t- Input configuration:\n");
8346 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8347 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8348 (uint32_t)mConfig.inputCfg.buffer.raw,
8349 mConfig.inputCfg.buffer.frameCount,
8350 mConfig.inputCfg.samplingRate,
8351 mConfig.inputCfg.channels,
8352 mConfig.inputCfg.format);
8353 result.append(buffer);
8354
8355 result.append("\t\t- Output configuration:\n");
8356 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8357 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8358 (uint32_t)mConfig.outputCfg.buffer.raw,
8359 mConfig.outputCfg.buffer.frameCount,
8360 mConfig.outputCfg.samplingRate,
8361 mConfig.outputCfg.channels,
8362 mConfig.outputCfg.format);
8363 result.append(buffer);
8364
8365 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8366 result.append(buffer);
8367 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8368 for (size_t i = 0; i < mHandles.size(); ++i) {
8369 sp<EffectHandle> handle = mHandles[i].promote();
8370 if (handle != 0) {
8371 handle->dump(buffer, SIZE);
8372 result.append(buffer);
8373 }
8374 }
8375
8376 result.append("\n");
8377
8378 write(fd, result.string(), result.length());
8379
8380 if (locked) {
8381 mLock.unlock();
8382 }
8383
8384 return NO_ERROR;
8385}
8386
8387// ----------------------------------------------------------------------------
8388// EffectHandle implementation
8389// ----------------------------------------------------------------------------
8390
8391#undef LOG_TAG
8392#define LOG_TAG "AudioFlinger::EffectHandle"
8393
8394AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8395 const sp<AudioFlinger::Client>& client,
8396 const sp<IEffectClient>& effectClient,
8397 int32_t priority)
8398 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008399 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008400 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401{
Steve Block3856b092011-10-20 11:56:00 +01008402 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008403
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008404 if (client == 0) {
8405 return;
8406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8408 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8409 if (mCblkMemory != 0) {
8410 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8411
Glenn Kastena0d68332012-01-27 16:47:15 -08008412 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413 new(mCblk) effect_param_cblk_t();
8414 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008416 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008417 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 return;
8419 }
8420}
8421
8422AudioFlinger::EffectHandle::~EffectHandle()
8423{
Steve Block3856b092011-10-20 11:56:00 +01008424 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008425 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008426 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427}
8428
8429status_t AudioFlinger::EffectHandle::enable()
8430{
Steve Block3856b092011-10-20 11:56:00 +01008431 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008432 if (!mHasControl) return INVALID_OPERATION;
8433 if (mEffect == 0) return DEAD_OBJECT;
8434
Eric Laurentdb7c0792011-08-10 10:37:50 -07008435 if (mEnabled) {
8436 return NO_ERROR;
8437 }
8438
Eric Laurent59255e42011-07-27 19:49:51 -07008439 mEnabled = true;
8440
8441 sp<ThreadBase> thread = mEffect->thread().promote();
8442 if (thread != 0) {
8443 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8444 }
8445
8446 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8447 if (mEffect->suspended()) {
8448 return NO_ERROR;
8449 }
8450
Eric Laurentdb7c0792011-08-10 10:37:50 -07008451 status_t status = mEffect->setEnabled(true);
8452 if (status != NO_ERROR) {
8453 if (thread != 0) {
8454 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8455 }
8456 mEnabled = false;
8457 }
8458 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008459}
8460
8461status_t AudioFlinger::EffectHandle::disable()
8462{
Steve Block3856b092011-10-20 11:56:00 +01008463 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008465 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008466
Eric Laurentdb7c0792011-08-10 10:37:50 -07008467 if (!mEnabled) {
8468 return NO_ERROR;
8469 }
Eric Laurent59255e42011-07-27 19:49:51 -07008470 mEnabled = false;
8471
8472 if (mEffect->suspended()) {
8473 return NO_ERROR;
8474 }
8475
8476 status_t status = mEffect->setEnabled(false);
8477
8478 sp<ThreadBase> thread = mEffect->thread().promote();
8479 if (thread != 0) {
8480 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8481 }
8482
8483 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008484}
8485
8486void AudioFlinger::EffectHandle::disconnect()
8487{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008488 disconnect(true);
8489}
8490
Glenn Kasten58123c32012-02-03 10:32:24 -08008491void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008492{
Glenn Kasten58123c32012-02-03 10:32:24 -08008493 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008494 if (mEffect == 0) {
8495 return;
8496 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008497 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008498
Eric Laurenta85a74a2011-10-19 11:44:54 -07008499 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008500 sp<ThreadBase> thread = mEffect->thread().promote();
8501 if (thread != 0) {
8502 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8503 }
Eric Laurent59255e42011-07-27 19:49:51 -07008504 }
8505
Mathias Agopian65ab4712010-07-14 17:59:35 -07008506 // release sp on module => module destructor can be called now
8507 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008508 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008509 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008510 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008511 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8512 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008513 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008514 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008515 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8516 mClient.clear();
8517 }
8518}
8519
Eric Laurent25f43952010-07-28 05:40:18 -07008520status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8521 uint32_t cmdSize,
8522 void *pCmdData,
8523 uint32_t *replySize,
8524 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525{
Steve Block3856b092011-10-20 11:56:00 +01008526// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008527// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528
8529 // only get parameter command is permitted for applications not controlling the effect
8530 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8531 return INVALID_OPERATION;
8532 }
8533 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008534 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535
8536 // handle commands that are not forwarded transparently to effect engine
8537 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8538 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8539 // no risk to block the whole media server process or mixer threads is we are stuck here
8540 Mutex::Autolock _l(mCblk->lock);
8541 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8542 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8543 mCblk->serverIndex = 0;
8544 mCblk->clientIndex = 0;
8545 return BAD_VALUE;
8546 }
8547 status_t status = NO_ERROR;
8548 while (mCblk->serverIndex < mCblk->clientIndex) {
8549 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008550 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 int *p = (int *)(mBuffer + mCblk->serverIndex);
8552 int size = *p++;
8553 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008554 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008555 break;
8556 }
8557 effect_param_t *param = (effect_param_t *)p;
8558 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008559 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 mCblk->serverIndex += size;
8561 continue;
8562 }
Eric Laurent25f43952010-07-28 05:40:18 -07008563 uint32_t psize = sizeof(effect_param_t) +
8564 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8565 param->vsize;
8566 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8567 psize,
8568 p,
8569 &rsize,
8570 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008571 // stop at first error encountered
8572 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008574 *(int *)pReplyData = reply;
8575 break;
8576 } else if (reply != NO_ERROR) {
8577 *(int *)pReplyData = reply;
8578 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008579 }
8580 mCblk->serverIndex += size;
8581 }
8582 mCblk->serverIndex = 0;
8583 mCblk->clientIndex = 0;
8584 return status;
8585 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008586 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587 return enable();
8588 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008589 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 return disable();
8591 }
8592
8593 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8594}
8595
Eric Laurent59255e42011-07-27 19:49:51 -07008596void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597{
Steve Block3856b092011-10-20 11:56:00 +01008598 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008599
8600 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008601 mEnabled = enabled;
8602
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 if (signal && mEffectClient != 0) {
8604 mEffectClient->controlStatusChanged(hasControl);
8605 }
8606}
8607
Eric Laurent25f43952010-07-28 05:40:18 -07008608void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8609 uint32_t cmdSize,
8610 void *pCmdData,
8611 uint32_t replySize,
8612 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008613{
8614 if (mEffectClient != 0) {
8615 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8616 }
8617}
8618
8619
8620
8621void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8622{
8623 if (mEffectClient != 0) {
8624 mEffectClient->enableStatusChanged(enabled);
8625 }
8626}
8627
8628status_t AudioFlinger::EffectHandle::onTransact(
8629 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8630{
8631 return BnEffect::onTransact(code, data, reply, flags);
8632}
8633
8634
8635void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8636{
Glenn Kastena0d68332012-01-27 16:47:15 -08008637 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008638
8639 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008640 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008641 mPriority,
8642 mHasControl,
8643 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008644 mCblk ? mCblk->clientIndex : 0,
8645 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008646 );
8647
8648 if (locked) {
8649 mCblk->lock.unlock();
8650 }
8651}
8652
8653#undef LOG_TAG
8654#define LOG_TAG "AudioFlinger::EffectChain"
8655
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008656AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008658 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008659 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8660 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008661{
Dima Zavinfce7a472011-04-19 22:30:36 -07008662 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008663 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008664 return;
8665 }
8666 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8667 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008668}
8669
8670AudioFlinger::EffectChain::~EffectChain()
8671{
8672 if (mOwnInBuffer) {
8673 delete mInBuffer;
8674 }
8675
8676}
8677
Eric Laurent59255e42011-07-27 19:49:51 -07008678// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008679sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008681 size_t size = mEffects.size();
8682
8683 for (size_t i = 0; i < size; i++) {
8684 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008685 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008686 }
8687 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008688 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008689}
8690
Eric Laurent59255e42011-07-27 19:49:51 -07008691// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008692sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694 size_t size = mEffects.size();
8695
8696 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008697 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8698 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008699 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700 }
8701 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008702 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008703}
8704
Eric Laurent59255e42011-07-27 19:49:51 -07008705// getEffectFromType_l() must be called with ThreadBase::mLock held
8706sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8707 const effect_uuid_t *type)
8708{
Eric Laurent59255e42011-07-27 19:49:51 -07008709 size_t size = mEffects.size();
8710
8711 for (size_t i = 0; i < size; i++) {
8712 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008713 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008714 }
8715 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008716 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008717}
8718
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719// Must be called with EffectChain::mLock locked
8720void AudioFlinger::EffectChain::process_l()
8721{
Eric Laurentdac69112010-09-28 14:09:57 -07008722 sp<ThreadBase> thread = mThread.promote();
8723 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008724 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008725 return;
8726 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008727 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8728 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008729 // always process effects unless no more tracks are on the session and the effect tail
8730 // has been rendered
8731 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008732 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008733 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008734
Eric Laurent544fe9b2011-11-11 15:42:52 -08008735 if (!tracksOnSession && mTailBufferCount == 0) {
8736 doProcess = false;
8737 }
8738
8739 if (activeTrackCnt() == 0) {
8740 // if no track is active and the effect tail has not been rendered,
8741 // the input buffer must be cleared here as the mixer process will not do it
8742 if (tracksOnSession || mTailBufferCount > 0) {
8743 size_t numSamples = thread->frameCount() * thread->channelCount();
8744 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8745 if (mTailBufferCount > 0) {
8746 mTailBufferCount--;
8747 }
8748 }
8749 }
Eric Laurentdac69112010-09-28 14:09:57 -07008750 }
8751
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008753 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008754 for (size_t i = 0; i < size; i++) {
8755 mEffects[i]->process();
8756 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757 }
8758 for (size_t i = 0; i < size; i++) {
8759 mEffects[i]->updateState();
8760 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761}
8762
Eric Laurentcab11242010-07-15 12:50:15 -07008763// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008764status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765{
8766 effect_descriptor_t desc = effect->desc();
8767 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8768
8769 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008770 effect->setChain(this);
8771 sp<ThreadBase> thread = mThread.promote();
8772 if (thread == 0) {
8773 return NO_INIT;
8774 }
8775 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008776
8777 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8778 // Auxiliary effects are inserted at the beginning of mEffects vector as
8779 // they are processed first and accumulated in chain input buffer
8780 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008781
Mathias Agopian65ab4712010-07-14 17:59:35 -07008782 // the input buffer for auxiliary effect contains mono samples in
8783 // 32 bit format. This is to avoid saturation in AudoMixer
8784 // accumulation stage. Saturation is done in EffectModule::process() before
8785 // calling the process in effect engine
8786 size_t numSamples = thread->frameCount();
8787 int32_t *buffer = new int32_t[numSamples];
8788 memset(buffer, 0, numSamples * sizeof(int32_t));
8789 effect->setInBuffer((int16_t *)buffer);
8790 // auxiliary effects output samples to chain input buffer for further processing
8791 // by insert effects
8792 effect->setOutBuffer(mInBuffer);
8793 } else {
8794 // Insert effects are inserted at the end of mEffects vector as they are processed
8795 // after track and auxiliary effects.
8796 // Insert effect order as a function of indicated preference:
8797 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8798 // another effect is present
8799 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8800 // last effect claiming first position
8801 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8802 // first effect claiming last position
8803 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8804 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8805 // already present
8806
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008807 size_t size = mEffects.size();
8808 size_t idx_insert = size;
8809 ssize_t idx_insert_first = -1;
8810 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008812 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 effect_descriptor_t d = mEffects[i]->desc();
8814 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8815 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8816 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8817 // check invalid effect chaining combinations
8818 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8819 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008820 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008821 return INVALID_OPERATION;
8822 }
8823 // remember position of first insert effect and by default
8824 // select this as insert position for new effect
8825 if (idx_insert == size) {
8826 idx_insert = i;
8827 }
8828 // remember position of last insert effect claiming
8829 // first position
8830 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8831 idx_insert_first = i;
8832 }
8833 // remember position of first insert effect claiming
8834 // last position
8835 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8836 idx_insert_last == -1) {
8837 idx_insert_last = i;
8838 }
8839 }
8840 }
8841
8842 // modify idx_insert from first position if needed
8843 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8844 if (idx_insert_last != -1) {
8845 idx_insert = idx_insert_last;
8846 } else {
8847 idx_insert = size;
8848 }
8849 } else {
8850 if (idx_insert_first != -1) {
8851 idx_insert = idx_insert_first + 1;
8852 }
8853 }
8854
8855 // always read samples from chain input buffer
8856 effect->setInBuffer(mInBuffer);
8857
8858 // if last effect in the chain, output samples to chain
8859 // output buffer, otherwise to chain input buffer
8860 if (idx_insert == size) {
8861 if (idx_insert != 0) {
8862 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8863 mEffects[idx_insert-1]->configure();
8864 }
8865 effect->setOutBuffer(mOutBuffer);
8866 } else {
8867 effect->setOutBuffer(mInBuffer);
8868 }
8869 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008870
Steve Block3856b092011-10-20 11:56:00 +01008871 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008872 }
8873 effect->configure();
8874 return NO_ERROR;
8875}
8876
Eric Laurentcab11242010-07-15 12:50:15 -07008877// removeEffect_l() must be called with PlaybackThread::mLock held
8878size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008879{
8880 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008881 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8883
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008884 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008886 // calling stop here will remove pre-processing effect from the audio HAL.
8887 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8888 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008889 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8890 mEffects[i]->state() == EffectModule::STOPPING) {
8891 mEffects[i]->stop();
8892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008893 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8894 delete[] effect->inBuffer();
8895 } else {
8896 if (i == size - 1 && i != 0) {
8897 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8898 mEffects[i - 1]->configure();
8899 }
8900 }
8901 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008902 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 break;
8904 }
8905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008906
8907 return mEffects.size();
8908}
8909
Eric Laurentcab11242010-07-15 12:50:15 -07008910// setDevice_l() must be called with PlaybackThread::mLock held
8911void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912{
8913 size_t size = mEffects.size();
8914 for (size_t i = 0; i < size; i++) {
8915 mEffects[i]->setDevice(device);
8916 }
8917}
8918
Eric Laurentcab11242010-07-15 12:50:15 -07008919// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008920void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921{
8922 size_t size = mEffects.size();
8923 for (size_t i = 0; i < size; i++) {
8924 mEffects[i]->setMode(mode);
8925 }
8926}
8927
Eric Laurentcab11242010-07-15 12:50:15 -07008928// setVolume_l() must be called with PlaybackThread::mLock held
8929bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008930{
8931 uint32_t newLeft = *left;
8932 uint32_t newRight = *right;
8933 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008934 int ctrlIdx = -1;
8935 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936
Eric Laurentcab11242010-07-15 12:50:15 -07008937 // first update volume controller
8938 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008939 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008940 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8941 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008942 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008943 break;
8944 }
8945 }
8946
8947 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008948 if (hasControl) {
8949 *left = mNewLeftVolume;
8950 *right = mNewRightVolume;
8951 }
8952 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008953 }
8954
8955 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008956 mLeftVolume = newLeft;
8957 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008958
8959 // second get volume update from volume controller
8960 if (ctrlIdx >= 0) {
8961 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008962 mNewLeftVolume = newLeft;
8963 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008964 }
8965 // then indicate volume to all other effects in chain.
8966 // Pass altered volume to effects before volume controller
8967 // and requested volume to effects after controller
8968 uint32_t lVol = newLeft;
8969 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008970
Mathias Agopian65ab4712010-07-14 17:59:35 -07008971 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008972 if ((int)i == ctrlIdx) continue;
8973 // this also works for ctrlIdx == -1 when there is no volume controller
8974 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 lVol = *left;
8976 rVol = *right;
8977 }
8978 mEffects[i]->setVolume(&lVol, &rVol, false);
8979 }
8980 *left = newLeft;
8981 *right = newRight;
8982
8983 return hasControl;
8984}
8985
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8987{
8988 const size_t SIZE = 256;
8989 char buffer[SIZE];
8990 String8 result;
8991
8992 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8993 result.append(buffer);
8994
8995 bool locked = tryLock(mLock);
8996 // failed to lock - AudioFlinger is probably deadlocked
8997 if (!locked) {
8998 result.append("\tCould not lock mutex:\n");
8999 }
9000
Eric Laurentcab11242010-07-15 12:50:15 -07009001 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9002 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003 mEffects.size(),
9004 (uint32_t)mInBuffer,
9005 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006 mActiveTrackCnt);
9007 result.append(buffer);
9008 write(fd, result.string(), result.size());
9009
9010 for (size_t i = 0; i < mEffects.size(); ++i) {
9011 sp<EffectModule> effect = mEffects[i];
9012 if (effect != 0) {
9013 effect->dump(fd, args);
9014 }
9015 }
9016
9017 if (locked) {
9018 mLock.unlock();
9019 }
9020
9021 return NO_ERROR;
9022}
9023
Eric Laurent59255e42011-07-27 19:49:51 -07009024// must be called with ThreadBase::mLock held
9025void AudioFlinger::EffectChain::setEffectSuspended_l(
9026 const effect_uuid_t *type, bool suspend)
9027{
9028 sp<SuspendedEffectDesc> desc;
9029 // use effect type UUID timelow as key as there is no real risk of identical
9030 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009031 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009032 if (suspend) {
9033 if (index >= 0) {
9034 desc = mSuspendedEffects.valueAt(index);
9035 } else {
9036 desc = new SuspendedEffectDesc();
9037 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9038 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009039 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009040 }
9041 if (desc->mRefCount++ == 0) {
9042 sp<EffectModule> effect = getEffectIfEnabled(type);
9043 if (effect != 0) {
9044 desc->mEffect = effect;
9045 effect->setSuspended(true);
9046 effect->setEnabled(false);
9047 }
9048 }
9049 } else {
9050 if (index < 0) {
9051 return;
9052 }
9053 desc = mSuspendedEffects.valueAt(index);
9054 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009055 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009056 desc->mRefCount = 1;
9057 }
9058 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009059 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009060 if (desc->mEffect != 0) {
9061 sp<EffectModule> effect = desc->mEffect.promote();
9062 if (effect != 0) {
9063 effect->setSuspended(false);
9064 sp<EffectHandle> handle = effect->controlHandle();
9065 if (handle != 0) {
9066 effect->setEnabled(handle->enabled());
9067 }
9068 }
9069 desc->mEffect.clear();
9070 }
9071 mSuspendedEffects.removeItemsAt(index);
9072 }
9073 }
9074}
9075
9076// must be called with ThreadBase::mLock held
9077void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9078{
9079 sp<SuspendedEffectDesc> desc;
9080
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009081 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009082 if (suspend) {
9083 if (index >= 0) {
9084 desc = mSuspendedEffects.valueAt(index);
9085 } else {
9086 desc = new SuspendedEffectDesc();
9087 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009088 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009089 }
9090 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009091 Vector< sp<EffectModule> > effects;
9092 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009093 for (size_t i = 0; i < effects.size(); i++) {
9094 setEffectSuspended_l(&effects[i]->desc().type, true);
9095 }
9096 }
9097 } else {
9098 if (index < 0) {
9099 return;
9100 }
9101 desc = mSuspendedEffects.valueAt(index);
9102 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009103 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009104 desc->mRefCount = 1;
9105 }
9106 if (--desc->mRefCount == 0) {
9107 Vector<const effect_uuid_t *> types;
9108 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9109 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9110 continue;
9111 }
9112 types.add(&mSuspendedEffects.valueAt(i)->mType);
9113 }
9114 for (size_t i = 0; i < types.size(); i++) {
9115 setEffectSuspended_l(types[i], false);
9116 }
Steve Block3856b092011-10-20 11:56:00 +01009117 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009118 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9119 }
9120 }
9121}
9122
Eric Laurent6bffdb82011-09-23 08:40:41 -07009123
9124// The volume effect is used for automated tests only
9125#ifndef OPENSL_ES_H_
9126static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9127 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9128const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9129#endif //OPENSL_ES_H_
9130
Eric Laurentdb7c0792011-08-10 10:37:50 -07009131bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9132{
9133 // auxiliary effects and visualizer are never suspended on output mix
9134 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9135 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009136 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9137 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009138 return false;
9139 }
9140 return true;
9141}
9142
Glenn Kastend0539712012-01-30 12:56:03 -08009143void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009144{
Glenn Kastend0539712012-01-30 12:56:03 -08009145 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009146 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009147 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9148 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009149 }
Eric Laurent59255e42011-07-27 19:49:51 -07009150 }
Eric Laurent59255e42011-07-27 19:49:51 -07009151}
9152
9153sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9154 const effect_uuid_t *type)
9155{
Glenn Kasten090f0192012-01-30 13:00:02 -08009156 sp<EffectModule> effect = getEffectFromType_l(type);
9157 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009158}
9159
9160void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9161 bool enabled)
9162{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009163 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009164 if (enabled) {
9165 if (index < 0) {
9166 // if the effect is not suspend check if all effects are suspended
9167 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9168 if (index < 0) {
9169 return;
9170 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009171 if (!isEffectEligibleForSuspend(effect->desc())) {
9172 return;
9173 }
Eric Laurent59255e42011-07-27 19:49:51 -07009174 setEffectSuspended_l(&effect->desc().type, enabled);
9175 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009176 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009177 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009178 return;
9179 }
Eric Laurent59255e42011-07-27 19:49:51 -07009180 }
Steve Block3856b092011-10-20 11:56:00 +01009181 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009182 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009183 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9184 // if effect is requested to suspended but was not yet enabled, supend it now.
9185 if (desc->mEffect == 0) {
9186 desc->mEffect = effect;
9187 effect->setEnabled(false);
9188 effect->setSuspended(true);
9189 }
9190 } else {
9191 if (index < 0) {
9192 return;
9193 }
Steve Block3856b092011-10-20 11:56:00 +01009194 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009195 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009196 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9197 desc->mEffect.clear();
9198 effect->setSuspended(false);
9199 }
9200}
9201
Mathias Agopian65ab4712010-07-14 17:59:35 -07009202#undef LOG_TAG
9203#define LOG_TAG "AudioFlinger"
9204
9205// ----------------------------------------------------------------------------
9206
9207status_t AudioFlinger::onTransact(
9208 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9209{
9210 return BnAudioFlinger::onTransact(code, data, reply, flags);
9211}
9212
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213}; // namespace android