blob: c674c24f2737503c918d85847186ad907163005a [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
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Mathias Agopian65ab4712010-07-14 17:59:35 -070095static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080096static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
98// retry counts for buffer fill timeout
99// 50 * ~20msecs = 1 second
100static const int8_t kMaxTrackRetries = 50;
101static const int8_t kMaxTrackStartupRetries = 50;
102// allow less retry attempts on direct output thread.
103// direct outputs can be a scarce resource in audio hardware and should
104// be released as quickly as possible.
105static const int8_t kMaxTrackRetriesDirect = 2;
106
107static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800108static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109
Glenn Kasten7dede872011-12-13 11:04:14 -0800110// don't warn about blocked writes or record buffer overflows more often than this
111static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700113// RecordThread loop sleep time upon application overrun or audio HAL read error
114static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115
Glenn Kasten7dede872011-12-13 11:04:14 -0800116// maximum time to wait for setParameters to complete
117static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700118
Eric Laurent7cafbb32011-11-22 18:50:29 -0800119// minimum sleep time for the mixer thread loop when tracks are active but in underrun
120static const uint32_t kMinThreadSleepTimeUs = 5000;
121// maximum divider applied to the active sleep time in the mixer thread loop
122static const uint32_t kMaxThreadSleepTimeShift = 2;
123
John Grossman4ff14ba2012-02-08 16:37:41 -0800124nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800125
Mathias Agopian65ab4712010-07-14 17:59:35 -0700126// ----------------------------------------------------------------------------
127
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700128#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800129// To collect the amplifier usage
130static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800131 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
132 if (service == NULL) {
133 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800134 return;
135 }
136
137 service->addBatteryData(params);
138}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700139#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800140
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700141static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700142{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700143 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700144 int rc;
145
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700146 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
147 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
148 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
149 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700150 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700151 }
152 rc = audio_hw_device_open(mod, dev);
153 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
154 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
155 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700157 }
158 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
159 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
160 rc = BAD_VALUE;
161 goto out;
162 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 return 0;
164
165out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 *dev = NULL;
167 return rc;
168}
169
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170// ----------------------------------------------------------------------------
171
172AudioFlinger::AudioFlinger()
173 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 mPrimaryHardwareDev(NULL),
175 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
176 mMasterVolume(1.0f),
177 mMasterVolumeSupportLvl(MVS_NONE),
178 mMasterMute(false),
179 mNextUniqueId(1),
180 mMode(AUDIO_MODE_INVALID),
181 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700182{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700183}
184
185void AudioFlinger::onFirstRef()
186{
Dima Zavin799a70e2011-04-18 16:57:27 -0700187 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700188
Eric Laurent93575202011-01-18 18:39:02 -0800189 Mutex::Autolock _l(mLock);
190
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800192 char val_str[PROPERTY_VALUE_MAX] = { 0 };
193 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
194 uint32_t int_val;
195 if (1 == sscanf(val_str, "%u", &int_val)) {
196 mStandbyTimeInNsecs = milliseconds(int_val);
197 ALOGI("Using %u mSec as standby time.", int_val);
198 } else {
199 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
200 ALOGI("Using default %u mSec as standby time.",
201 (uint32_t)(mStandbyTimeInNsecs / 1000000));
202 }
203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700204
Eric Laurenta4c5a552012-03-29 10:12:40 -0700205 mMode = AUDIO_MODE_NORMAL;
206 mMasterVolumeSW = 1.0;
207 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800208 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700209}
210
211AudioFlinger::~AudioFlinger()
212{
Dima Zavin799a70e2011-04-18 16:57:27 -0700213
Mathias Agopian65ab4712010-07-14 17:59:35 -0700214 while (!mRecordThreads.isEmpty()) {
215 // closeInput() will remove first entry from mRecordThreads
216 closeInput(mRecordThreads.keyAt(0));
217 }
218 while (!mPlaybackThreads.isEmpty()) {
219 // closeOutput() will remove first entry from mPlaybackThreads
220 closeOutput(mPlaybackThreads.keyAt(0));
221 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700222
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800223 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
224 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700225 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
226 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227 }
228}
229
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230static const char * const audio_interfaces[] = {
231 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
232 AUDIO_HARDWARE_MODULE_ID_A2DP,
233 AUDIO_HARDWARE_MODULE_ID_USB,
234};
235#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
236
237audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700238{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700239 // if module is 0, the request comes from an old policy manager and we should load
240 // well known modules
241 if (module == 0) {
242 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
243 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
244 loadHwModule_l(audio_interfaces[i]);
245 }
246 } else {
247 // check a match for the requested module handle
248 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
249 if (audioHwdevice != NULL) {
250 return audioHwdevice->hwDevice();
251 }
252 }
253 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700259
Dima Zavin799a70e2011-04-18 16:57:27 -0700260 return NULL;
261}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262
263status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
264{
265 const size_t SIZE = 256;
266 char buffer[SIZE];
267 String8 result;
268
269 result.append("Clients:\n");
270 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800271 sp<Client> client = mClients.valueAt(i).promote();
272 if (client != 0) {
273 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
274 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275 }
276 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800279 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700283 result.append(buffer);
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800295 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
John Grossman4ff14ba2012-02-08 16:37:41 -0800297 snprintf(buffer, SIZE, "Hardware status: %d\n"
298 "Standby Time mSec: %u\n",
299 hardwareStatus,
300 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301 result.append(buffer);
302 write(fd, result.string(), result.size());
303 return NO_ERROR;
304}
305
306status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
307{
308 const size_t SIZE = 256;
309 char buffer[SIZE];
310 String8 result;
311 snprintf(buffer, SIZE, "Permission Denial: "
312 "can't dump AudioFlinger from pid=%d, uid=%d\n",
313 IPCThreadState::self()->getCallingPid(),
314 IPCThreadState::self()->getCallingUid());
315 result.append(buffer);
316 write(fd, result.string(), result.size());
317 return NO_ERROR;
318}
319
320static bool tryLock(Mutex& mutex)
321{
322 bool locked = false;
323 for (int i = 0; i < kDumpLockRetries; ++i) {
324 if (mutex.tryLock() == NO_ERROR) {
325 locked = true;
326 break;
327 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800328 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 }
330 return locked;
331}
332
333status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
334{
Glenn Kasten44deb052012-02-05 18:09:08 -0800335 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336 dumpPermissionDenial(fd, args);
337 } else {
338 // get state of hardware lock
339 bool hardwareLocked = tryLock(mHardwareLock);
340 if (!hardwareLocked) {
341 String8 result(kHardwareLockedString);
342 write(fd, result.string(), result.size());
343 } else {
344 mHardwareLock.unlock();
345 }
346
347 bool locked = tryLock(mLock);
348
349 // failed to lock - AudioFlinger is probably deadlocked
350 if (!locked) {
351 String8 result(kDeadlockedString);
352 write(fd, result.string(), result.size());
353 }
354
355 dumpClients(fd, args);
356 dumpInternals(fd, args);
357
358 // dump playback threads
359 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
360 mPlaybackThreads.valueAt(i)->dump(fd, args);
361 }
362
363 // dump record threads
364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
365 mRecordThreads.valueAt(i)->dump(fd, args);
366 }
367
Dima Zavin799a70e2011-04-18 16:57:27 -0700368 // dump all hardware devs
369 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700370 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700371 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 }
373 if (locked) mLock.unlock();
374 }
375 return NO_ERROR;
376}
377
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800378sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
379{
380 // If pid is already in the mClients wp<> map, then use that entry
381 // (for which promote() is always != 0), otherwise create a new entry and Client.
382 sp<Client> client = mClients.valueFor(pid).promote();
383 if (client == 0) {
384 client = new Client(this, pid);
385 mClients.add(pid, client);
386 }
387
388 return client;
389}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390
391// IAudioFlinger interface
392
393
394sp<IAudioTrack> AudioFlinger::createTrack(
395 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800396 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800398 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700399 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800401 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800403 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 int *sessionId,
405 status_t *status)
406{
407 sp<PlaybackThread::Track> track;
408 sp<TrackHandle> trackHandle;
409 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 status_t lStatus;
411 int lSessionId;
412
Glenn Kasten263709e2012-01-06 08:40:01 -0800413 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
414 // but if someone uses binder directly they could bypass that and cause us to crash
415 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000416 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 lStatus = BAD_VALUE;
418 goto Exit;
419 }
420
421 {
422 Mutex::Autolock _l(mLock);
423 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700424 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000426 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 lStatus = BAD_VALUE;
428 goto Exit;
429 }
430
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800431 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432
Steve Block3856b092011-10-20 11:56:00 +0100433 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700434 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700436 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
437 if (mPlaybackThreads.keyAt(i) != output) {
438 // prevent same audio session on different output threads
439 uint32_t sessions = t->hasAudioSession(*sessionId);
440 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000441 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700442 lStatus = BAD_VALUE;
443 goto Exit;
444 }
445 // check if an effect with same session ID is waiting for a track to be created
446 if (sessions & PlaybackThread::EFFECT_SESSION) {
447 effectThread = t.get();
448 }
Eric Laurentde070132010-07-13 04:45:46 -0700449 }
450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 lSessionId = *sessionId;
452 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700453 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700454 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 if (sessionId != NULL) {
456 *sessionId = lSessionId;
457 }
458 }
Steve Block3856b092011-10-20 11:56:00 +0100459 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460
Glenn Kastena075db42012-03-06 11:22:44 -0800461 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -0700463 channelMask, frameCount, sharedBuffer, lSessionId, flags, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700464
465 // move effect chain to this output thread if an effect on same session was waiting
466 // for a track to be created
467 if (lStatus == NO_ERROR && effectThread != NULL) {
468 Mutex::Autolock _dl(thread->mLock);
469 Mutex::Autolock _sl(effectThread->mLock);
470 moveEffectChain_l(lSessionId, effectThread, thread, true);
471 }
Eric Laurenta011e352012-03-29 15:51:43 -0700472
473 // Look for sync events awaiting for a session to be used.
474 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
475 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
476 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
477 track->setSyncEvent(mPendingSyncEvents[i]);
478 mPendingSyncEvents.removeAt(i);
479 i--;
480 }
481 }
482 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 }
484 if (lStatus == NO_ERROR) {
485 trackHandle = new TrackHandle(track);
486 } else {
487 // remove local strong reference to Client before deleting the Track so that the Client
488 // destructor is called by the TrackBase destructor with mLock held
489 client.clear();
490 track.clear();
491 }
492
493Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700494 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 *status = lStatus;
496 }
497 return trackHandle;
498}
499
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800500uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501{
502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000505 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 return 0;
507 }
508 return thread->sampleRate();
509}
510
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800511int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512{
513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000516 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517 return 0;
518 }
519 return thread->channelCount();
520}
521
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800522audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700523{
524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000527 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800528 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 }
530 return thread->format();
531}
532
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800533size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534{
535 Mutex::Autolock _l(mLock);
536 PlaybackThread *thread = checkPlaybackThread_l(output);
537 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000538 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 return 0;
540 }
541 return thread->frameCount();
542}
543
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800544uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545{
546 Mutex::Autolock _l(mLock);
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000549 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 return 0;
551 }
552 return thread->latency();
553}
554
555status_t AudioFlinger::setMasterVolume(float value)
556{
Eric Laurenta1884f92011-08-23 08:25:03 -0700557 status_t ret = initCheck();
558 if (ret != NO_ERROR) {
559 return ret;
560 }
561
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 // check calling permissions
563 if (!settingsAllowed()) {
564 return PERMISSION_DENIED;
565 }
566
John Grossman4ff14ba2012-02-08 16:37:41 -0800567 float swmv = value;
568
Eric Laurenta4c5a552012-03-29 10:12:40 -0700569 Mutex::Autolock _l(mLock);
570
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800572 if (MVS_NONE != mMasterVolumeSupportLvl) {
573 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
574 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700575 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800576
577 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
578 if (NULL != dev->set_master_volume) {
579 dev->set_master_volume(dev, value);
580 }
581 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800582 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800583
584 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586
John Grossman4ff14ba2012-02-08 16:37:41 -0800587 mMasterVolume = value;
588 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800589 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700590 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591
592 return NO_ERROR;
593}
594
Glenn Kastenf78aee72012-01-04 11:00:47 -0800595status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596{
Eric Laurenta1884f92011-08-23 08:25:03 -0700597 status_t ret = initCheck();
598 if (ret != NO_ERROR) {
599 return ret;
600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601
602 // check calling permissions
603 if (!settingsAllowed()) {
604 return PERMISSION_DENIED;
605 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800606 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000607 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 return BAD_VALUE;
609 }
610
611 { // scope for the lock
612 AutoMutex lock(mHardwareLock);
613 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700614 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 mHardwareStatus = AUDIO_HW_IDLE;
616 }
617
618 if (NO_ERROR == ret) {
619 Mutex::Autolock _l(mLock);
620 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800621 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700622 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 }
624
625 return ret;
626}
627
628status_t AudioFlinger::setMicMute(bool state)
629{
Eric Laurenta1884f92011-08-23 08:25:03 -0700630 status_t ret = initCheck();
631 if (ret != NO_ERROR) {
632 return ret;
633 }
634
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 // check calling permissions
636 if (!settingsAllowed()) {
637 return PERMISSION_DENIED;
638 }
639
640 AutoMutex lock(mHardwareLock);
641 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700642 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643 mHardwareStatus = AUDIO_HW_IDLE;
644 return ret;
645}
646
647bool AudioFlinger::getMicMute() const
648{
Eric Laurenta1884f92011-08-23 08:25:03 -0700649 status_t ret = initCheck();
650 if (ret != NO_ERROR) {
651 return false;
652 }
653
Dima Zavinfce7a472011-04-19 22:30:36 -0700654 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800655 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700657 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 mHardwareStatus = AUDIO_HW_IDLE;
659 return state;
660}
661
662status_t AudioFlinger::setMasterMute(bool muted)
663{
664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
668
Eric Laurent93575202011-01-18 18:39:02 -0800669 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800670 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800672 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700673 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700674
675 return NO_ERROR;
676}
677
678float AudioFlinger::masterVolume() const
679{
Glenn Kasten98067102011-12-13 11:47:54 -0800680 Mutex::Autolock _l(mLock);
681 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682}
683
John Grossman4ff14ba2012-02-08 16:37:41 -0800684float AudioFlinger::masterVolumeSW() const
685{
686 Mutex::Autolock _l(mLock);
687 return masterVolumeSW_l();
688}
689
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690bool AudioFlinger::masterMute() const
691{
Glenn Kasten98067102011-12-13 11:47:54 -0800692 Mutex::Autolock _l(mLock);
693 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694}
695
John Grossman4ff14ba2012-02-08 16:37:41 -0800696float AudioFlinger::masterVolume_l() const
697{
698 if (MVS_FULL == mMasterVolumeSupportLvl) {
699 float ret_val;
700 AutoMutex lock(mHardwareLock);
701
702 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800703 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
704 (NULL != mPrimaryHardwareDev->get_master_volume),
705 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800706
707 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
708 mHardwareStatus = AUDIO_HW_IDLE;
709 return ret_val;
710 }
711
712 return mMasterVolume;
713}
714
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800715status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
716 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717{
718 // check calling permissions
719 if (!settingsAllowed()) {
720 return PERMISSION_DENIED;
721 }
722
Glenn Kasten263709e2012-01-06 08:40:01 -0800723 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000724 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 return BAD_VALUE;
726 }
727
728 AutoMutex lock(mLock);
729 PlaybackThread *thread = NULL;
730 if (output) {
731 thread = checkPlaybackThread_l(output);
732 if (thread == NULL) {
733 return BAD_VALUE;
734 }
735 }
736
737 mStreamTypes[stream].volume = value;
738
739 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800740 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700741 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 }
743 } else {
744 thread->setStreamVolume(stream, value);
745 }
746
747 return NO_ERROR;
748}
749
Glenn Kastenfff6d712012-01-12 16:38:12 -0800750status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751{
752 // check calling permissions
753 if (!settingsAllowed()) {
754 return PERMISSION_DENIED;
755 }
756
Glenn Kasten263709e2012-01-06 08:40:01 -0800757 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700758 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000759 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 return BAD_VALUE;
761 }
762
Eric Laurent93575202011-01-18 18:39:02 -0800763 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mStreamTypes[stream].mute = muted;
765 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700766 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767
768 return NO_ERROR;
769}
770
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800771float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772{
Glenn Kasten263709e2012-01-06 08:40:01 -0800773 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774 return 0.0f;
775 }
776
777 AutoMutex lock(mLock);
778 float volume;
779 if (output) {
780 PlaybackThread *thread = checkPlaybackThread_l(output);
781 if (thread == NULL) {
782 return 0.0f;
783 }
784 volume = thread->streamVolume(stream);
785 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800786 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 }
788
789 return volume;
790}
791
Glenn Kastenfff6d712012-01-12 16:38:12 -0800792bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 return true;
796 }
797
Glenn Kasten6637baa2012-01-09 09:40:36 -0800798 AutoMutex lock(mLock);
799 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800}
801
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800802status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800804 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
806 // check calling permissions
807 if (!settingsAllowed()) {
808 return PERMISSION_DENIED;
809 }
810
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 // ioHandle == 0 means the parameters are global to the audio hardware interface
812 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700813 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700814 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800815 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700816 AutoMutex lock(mHardwareLock);
817 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
818 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
819 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
820 status_t result = dev->set_parameters(dev, keyValuePairs.string());
821 final_result = result ?: final_result;
822 }
823 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800824 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700825 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
826 AudioParameter param = AudioParameter(keyValuePairs);
827 String8 value;
828 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700829 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
830 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700831 for (size_t i = 0; i < mRecordThreads.size(); i++) {
832 sp<RecordThread> thread = mRecordThreads.valueAt(i);
833 RecordThread::RecordTrack *track = thread->track();
834 if (track != NULL) {
835 audio_devices_t device = (audio_devices_t)(
836 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700837 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700838 thread->setEffectSuspended(FX_IID_AEC,
839 suspend,
840 track->sessionId());
841 thread->setEffectSuspended(FX_IID_NS,
842 suspend,
843 track->sessionId());
844 }
845 }
Eric Laurentbee53372011-08-29 12:42:48 -0700846 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700847 }
848 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700849 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 }
851
852 // hold a strong ref on thread in case closeOutput() or closeInput() is called
853 // and the thread is exited once the lock is released
854 sp<ThreadBase> thread;
855 {
856 Mutex::Autolock _l(mLock);
857 thread = checkPlaybackThread_l(ioHandle);
858 if (thread == NULL) {
859 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800860 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700861 // indicate output device change to all input threads for pre processing
862 AudioParameter param = AudioParameter(keyValuePairs);
863 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700864 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
865 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700866 for (size_t i = 0; i < mRecordThreads.size(); i++) {
867 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
868 }
869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 }
871 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800872 if (thread != 0) {
873 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874 }
875 return BAD_VALUE;
876}
877
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800878String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800880// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
882
Eric Laurenta4c5a552012-03-29 10:12:40 -0700883 Mutex::Autolock _l(mLock);
884
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700886 String8 out_s8;
887
Dima Zavin799a70e2011-04-18 16:57:27 -0700888 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800889 char *s;
890 {
891 AutoMutex lock(mHardwareLock);
892 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700893 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800894 s = dev->get_parameters(dev, keys.string());
895 mHardwareStatus = AUDIO_HW_IDLE;
896 }
John Grossmanef7740b2012-02-09 11:28:36 -0800897 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700898 free(s);
899 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700900 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
902
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
904 if (playbackThread != NULL) {
905 return playbackThread->getParameters(keys);
906 }
907 RecordThread *recordThread = checkRecordThread_l(ioHandle);
908 if (recordThread != NULL) {
909 return recordThread->getParameters(keys);
910 }
911 return String8("");
912}
913
Glenn Kastenf587ba52012-01-26 16:25:10 -0800914size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915{
Eric Laurenta1884f92011-08-23 08:25:03 -0700916 status_t ret = initCheck();
917 if (ret != NO_ERROR) {
918 return 0;
919 }
920
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800921 AutoMutex lock(mHardwareLock);
922 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700923 struct audio_config config = {
924 sample_rate: sampleRate,
925 channel_mask: audio_channel_in_mask_from_count(channelCount),
926 format: format,
927 };
928 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800929 mHardwareStatus = AUDIO_HW_IDLE;
930 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931}
932
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800933unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934{
935 if (ioHandle == 0) {
936 return 0;
937 }
938
939 Mutex::Autolock _l(mLock);
940
941 RecordThread *recordThread = checkRecordThread_l(ioHandle);
942 if (recordThread != NULL) {
943 return recordThread->getInputFramesLost();
944 }
945 return 0;
946}
947
948status_t AudioFlinger::setVoiceVolume(float value)
949{
Eric Laurenta1884f92011-08-23 08:25:03 -0700950 status_t ret = initCheck();
951 if (ret != NO_ERROR) {
952 return ret;
953 }
954
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 // check calling permissions
956 if (!settingsAllowed()) {
957 return PERMISSION_DENIED;
958 }
959
960 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800961 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700962 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 mHardwareStatus = AUDIO_HW_IDLE;
964
965 return ret;
966}
967
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800968status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
969 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970{
971 status_t status;
972
973 Mutex::Autolock _l(mLock);
974
975 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
976 if (playbackThread != NULL) {
977 return playbackThread->getRenderPosition(halFrames, dspFrames);
978 }
979
980 return BAD_VALUE;
981}
982
983void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
984{
985
986 Mutex::Autolock _l(mLock);
987
Glenn Kastenbb001922012-02-03 11:10:26 -0800988 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 if (mNotificationClients.indexOfKey(pid) < 0) {
990 sp<NotificationClient> notificationClient = new NotificationClient(this,
991 client,
992 pid);
Steve Block3856b092011-10-20 11:56:00 +0100993 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994
995 mNotificationClients.add(pid, notificationClient);
996
997 sp<IBinder> binder = client->asBinder();
998 binder->linkToDeath(notificationClient);
999
1000 // the config change is always sent from playback or record threads to avoid deadlock
1001 // with AudioSystem::gLock
1002 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1003 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1004 }
1005
1006 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1007 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1008 }
1009 }
1010}
1011
1012void AudioFlinger::removeNotificationClient(pid_t pid)
1013{
1014 Mutex::Autolock _l(mLock);
1015
Glenn Kastena3b09252012-01-20 09:19:01 -08001016 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001017
Steve Block3856b092011-10-20 11:56:00 +01001018 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001019 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001020 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001021 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001022 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001023 ALOGV(" pid %d @ %d", ref->mPid, i);
1024 if (ref->mPid == pid) {
1025 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001026 mAudioSessionRefs.removeAt(i);
1027 delete ref;
1028 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001029 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001030 } else {
1031 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001032 }
1033 }
1034 if (removed) {
1035 purgeStaleEffects_l();
1036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037}
1038
1039// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001040void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041{
1042 size_t size = mNotificationClients.size();
1043 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001044 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1045 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 }
1047}
1048
1049// removeClient_l() must be called with AudioFlinger::mLock held
1050void AudioFlinger::removeClient_l(pid_t pid)
1051{
Steve Block3856b092011-10-20 11:56:00 +01001052 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053 mClients.removeItem(pid);
1054}
1055
1056
1057// ----------------------------------------------------------------------------
1058
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001059AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1060 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001062 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001063 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
1064 // mChannelMask
1065 mChannelCount(0),
1066 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1067 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001068 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001069 mDevice(device),
1070 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071{
1072}
1073
1074AudioFlinger::ThreadBase::~ThreadBase()
1075{
1076 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001077 // do not lock the mutex in destructor
1078 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001079 if (mPowerManager != 0) {
1080 sp<IBinder> binder = mPowerManager->asBinder();
1081 binder->unlinkToDeath(mDeathRecipient);
1082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083}
1084
1085void AudioFlinger::ThreadBase::exit()
1086{
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001089 // This lock prevents the following race in thread (uniprocessor for illustration):
1090 // if (!exitPending()) {
1091 // // context switch from here to exit()
1092 // // exit() calls requestExit(), what exitPending() observes
1093 // // exit() calls signal(), which is dropped since no waiters
1094 // // context switch back from exit() to here
1095 // mWaitWorkCV.wait(...);
1096 // // now thread is hung
1097 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001098 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 requestExit();
1100 mWaitWorkCV.signal();
1101 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001102 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1103 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 requestExitAndWait();
1105}
1106
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1108{
1109 status_t status;
1110
Steve Block3856b092011-10-20 11:56:00 +01001111 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 Mutex::Autolock _l(mLock);
1113
1114 mNewParameters.add(keyValuePairs);
1115 mWaitWorkCV.signal();
1116 // wait condition with timeout in case the thread loop has exited
1117 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001118 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 status = mParamStatus;
1120 mWaitWorkCV.signal();
1121 } else {
1122 status = TIMED_OUT;
1123 }
1124 return status;
1125}
1126
1127void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1128{
1129 Mutex::Autolock _l(mLock);
1130 sendConfigEvent_l(event, param);
1131}
1132
1133// sendConfigEvent_l() must be called with ThreadBase::mLock held
1134void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1135{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001136 ConfigEvent configEvent;
1137 configEvent.mEvent = event;
1138 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001140 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 mWaitWorkCV.signal();
1142}
1143
1144void AudioFlinger::ThreadBase::processConfigEvents()
1145{
1146 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001147 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001149 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 mConfigEvents.removeAt(0);
1151 // release mLock before locking AudioFlinger mLock: lock order is always
1152 // AudioFlinger then ThreadBase to avoid cross deadlock
1153 mLock.unlock();
1154 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001155 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 mLock.lock();
1158 }
1159 mLock.unlock();
1160}
1161
1162status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1163{
1164 const size_t SIZE = 256;
1165 char buffer[SIZE];
1166 String8 result;
1167
1168 bool locked = tryLock(mLock);
1169 if (!locked) {
1170 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1171 write(fd, buffer, strlen(buffer));
1172 }
1173
Eric Laurent612bbb52012-03-14 15:03:26 -07001174 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1175 result.append(buffer);
1176 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1177 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1179 result.append(buffer);
1180 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1181 result.append(buffer);
1182 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1183 result.append(buffer);
1184 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1185 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001186 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1187 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1189 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001190 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 result.append(buffer);
1192
1193 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1194 result.append(buffer);
1195 result.append(" Index Command");
1196 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1197 snprintf(buffer, SIZE, "\n %02d ", i);
1198 result.append(buffer);
1199 result.append(mNewParameters[i]);
1200 }
1201
1202 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1203 result.append(buffer);
1204 snprintf(buffer, SIZE, " Index event param\n");
1205 result.append(buffer);
1206 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001207 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208 result.append(buffer);
1209 }
1210 result.append("\n");
1211
1212 write(fd, result.string(), result.size());
1213
1214 if (locked) {
1215 mLock.unlock();
1216 }
1217 return NO_ERROR;
1218}
1219
Eric Laurent1d2bff02011-07-24 17:49:51 -07001220status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1221{
1222 const size_t SIZE = 256;
1223 char buffer[SIZE];
1224 String8 result;
1225
1226 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1227 write(fd, buffer, strlen(buffer));
1228
1229 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1230 sp<EffectChain> chain = mEffectChains[i];
1231 if (chain != 0) {
1232 chain->dump(fd, args);
1233 }
1234 }
1235 return NO_ERROR;
1236}
1237
Eric Laurentfeb0db62011-07-22 09:04:31 -07001238void AudioFlinger::ThreadBase::acquireWakeLock()
1239{
1240 Mutex::Autolock _l(mLock);
1241 acquireWakeLock_l();
1242}
1243
1244void AudioFlinger::ThreadBase::acquireWakeLock_l()
1245{
1246 if (mPowerManager == 0) {
1247 // use checkService() to avoid blocking if power service is not up yet
1248 sp<IBinder> binder =
1249 defaultServiceManager()->checkService(String16("power"));
1250 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001251 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001252 } else {
1253 mPowerManager = interface_cast<IPowerManager>(binder);
1254 binder->linkToDeath(mDeathRecipient);
1255 }
1256 }
1257 if (mPowerManager != 0) {
1258 sp<IBinder> binder = new BBinder();
1259 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1260 binder,
1261 String16(mName));
1262 if (status == NO_ERROR) {
1263 mWakeLockToken = binder;
1264 }
Steve Block3856b092011-10-20 11:56:00 +01001265 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001266 }
1267}
1268
1269void AudioFlinger::ThreadBase::releaseWakeLock()
1270{
1271 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001272 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001273}
1274
1275void AudioFlinger::ThreadBase::releaseWakeLock_l()
1276{
1277 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001278 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001279 if (mPowerManager != 0) {
1280 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1281 }
1282 mWakeLockToken.clear();
1283 }
1284}
1285
1286void AudioFlinger::ThreadBase::clearPowerManager()
1287{
1288 Mutex::Autolock _l(mLock);
1289 releaseWakeLock_l();
1290 mPowerManager.clear();
1291}
1292
1293void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1294{
1295 sp<ThreadBase> thread = mThread.promote();
1296 if (thread != 0) {
1297 thread->clearPowerManager();
1298 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001299 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001300}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001301
Eric Laurent59255e42011-07-27 19:49:51 -07001302void AudioFlinger::ThreadBase::setEffectSuspended(
1303 const effect_uuid_t *type, bool suspend, int sessionId)
1304{
1305 Mutex::Autolock _l(mLock);
1306 setEffectSuspended_l(type, suspend, sessionId);
1307}
1308
1309void AudioFlinger::ThreadBase::setEffectSuspended_l(
1310 const effect_uuid_t *type, bool suspend, int sessionId)
1311{
Glenn Kasten090f0192012-01-30 13:00:02 -08001312 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001313 if (chain != 0) {
1314 if (type != NULL) {
1315 chain->setEffectSuspended_l(type, suspend);
1316 } else {
1317 chain->setEffectSuspendedAll_l(suspend);
1318 }
1319 }
1320
1321 updateSuspendedSessions_l(type, suspend, sessionId);
1322}
1323
1324void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1325{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001326 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001327 if (index < 0) {
1328 return;
1329 }
1330
1331 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1332 mSuspendedSessions.editValueAt(index);
1333
1334 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001335 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001336 for (int j = 0; j < desc->mRefCount; j++) {
1337 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1338 chain->setEffectSuspendedAll_l(true);
1339 } else {
Steve Block3856b092011-10-20 11:56:00 +01001340 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001341 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001342 chain->setEffectSuspended_l(&desc->mType, true);
1343 }
1344 }
1345 }
1346}
1347
Eric Laurent59255e42011-07-27 19:49:51 -07001348void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1349 bool suspend,
1350 int sessionId)
1351{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001352 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001353
1354 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1355
1356 if (suspend) {
1357 if (index >= 0) {
1358 sessionEffects = mSuspendedSessions.editValueAt(index);
1359 } else {
1360 mSuspendedSessions.add(sessionId, sessionEffects);
1361 }
1362 } else {
1363 if (index < 0) {
1364 return;
1365 }
1366 sessionEffects = mSuspendedSessions.editValueAt(index);
1367 }
1368
1369
1370 int key = EffectChain::kKeyForSuspendAll;
1371 if (type != NULL) {
1372 key = type->timeLow;
1373 }
1374 index = sessionEffects.indexOfKey(key);
1375
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001376 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001377 if (suspend) {
1378 if (index >= 0) {
1379 desc = sessionEffects.valueAt(index);
1380 } else {
1381 desc = new SuspendedSessionDesc();
1382 if (type != NULL) {
1383 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1384 }
1385 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001386 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001387 }
1388 desc->mRefCount++;
1389 } else {
1390 if (index < 0) {
1391 return;
1392 }
1393 desc = sessionEffects.valueAt(index);
1394 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001395 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001396 sessionEffects.removeItemsAt(index);
1397 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001398 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001399 sessionId);
1400 mSuspendedSessions.removeItem(sessionId);
1401 }
1402 }
1403 }
1404 if (!sessionEffects.isEmpty()) {
1405 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1406 }
1407}
1408
1409void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1410 bool enabled,
1411 int sessionId)
1412{
1413 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001414 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1415}
Eric Laurent59255e42011-07-27 19:49:51 -07001416
Eric Laurenta85a74a2011-10-19 11:44:54 -07001417void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1418 bool enabled,
1419 int sessionId)
1420{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001421 if (mType != RECORD) {
1422 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1423 // another session. This gives the priority to well behaved effect control panels
1424 // and applications not using global effects.
1425 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1426 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1427 }
1428 }
Eric Laurent59255e42011-07-27 19:49:51 -07001429
1430 sp<EffectChain> chain = getEffectChain_l(sessionId);
1431 if (chain != 0) {
1432 chain->checkSuspendOnEffectEnabled(effect, enabled);
1433 }
1434}
1435
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436// ----------------------------------------------------------------------------
1437
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001438AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1439 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001440 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001441 uint32_t device,
1442 type_t type)
1443 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001444 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1445 // Assumes constructor is called by AudioFlinger with it's mLock held,
1446 // but it would be safer to explicitly pass initial masterMute as parameter
1447 mMasterMute(audioFlinger->masterMute_l()),
1448 // mStreamTypes[] initialized in constructor body
1449 mOutput(output),
1450 // Assumes constructor is called by AudioFlinger with it's mLock held,
1451 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001452 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001453 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001454 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001455 mPrevMixerStatus(MIXER_IDLE),
1456 standbyDelay(AudioFlinger::mStandbyTimeInNsecs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457{
Glenn Kasten480b4682012-02-28 12:30:08 -08001458 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001459
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 readOutputParameters();
1461
Glenn Kasten263709e2012-01-06 08:40:01 -08001462 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001463 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1464 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1465 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001466 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1467 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001469 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1470 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
1473AudioFlinger::PlaybackThread::~PlaybackThread()
1474{
1475 delete [] mMixBuffer;
1476}
1477
1478status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1479{
1480 dumpInternals(fd, args);
1481 dumpTracks(fd, args);
1482 dumpEffectChains(fd, args);
1483 return NO_ERROR;
1484}
1485
1486status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1487{
1488 const size_t SIZE = 256;
1489 char buffer[SIZE];
1490 String8 result;
1491
1492 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1493 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495 for (size_t i = 0; i < mTracks.size(); ++i) {
1496 sp<Track> track = mTracks[i];
1497 if (track != 0) {
1498 track->dump(buffer, SIZE);
1499 result.append(buffer);
1500 }
1501 }
1502
1503 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1504 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001505 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001507 sp<Track> track = mActiveTracks[i].promote();
1508 if (track != 0) {
1509 track->dump(buffer, SIZE);
1510 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 }
1512 }
1513 write(fd, result.string(), result.size());
1514 return NO_ERROR;
1515}
1516
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1518{
1519 const size_t SIZE = 256;
1520 char buffer[SIZE];
1521 String8 result;
1522
1523 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1524 result.append(buffer);
1525 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1526 result.append(buffer);
1527 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1528 result.append(buffer);
1529 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1530 result.append(buffer);
1531 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1532 result.append(buffer);
1533 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1534 result.append(buffer);
1535 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1536 result.append(buffer);
1537 write(fd, result.string(), result.size());
1538
1539 dumpBase(fd, args);
1540
1541 return NO_ERROR;
1542}
1543
1544// Thread virtuals
1545status_t AudioFlinger::PlaybackThread::readyToRun()
1546{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001547 status_t status = initCheck();
1548 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001549 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001550 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001551 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001553 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554}
1555
1556void AudioFlinger::PlaybackThread::onFirstRef()
1557{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001558 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559}
1560
1561// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001562sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001564 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001566 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001567 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 int frameCount,
1569 const sp<IMemory>& sharedBuffer,
1570 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001571 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 status_t *status)
1573{
1574 sp<Track> track;
1575 status_t lStatus;
1576
Glenn Kasten73d22752012-03-19 13:38:30 -07001577 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1578
1579 // client expresses a preference for FAST, but we get the final say
1580 if ((flags & IAudioFlinger::TRACK_FAST) &&
1581 !(
1582 // not timed
1583 (!isTimed) &&
1584 // either of these use cases:
1585 (
1586 // use case 1: shared buffer with any frame count
1587 (
1588 (sharedBuffer != 0)
1589 ) ||
1590 // use case 2: callback handler and small power-of-2 frame count
1591 (
1592 // unfortunately we can't verify that there's a callback until start()
1593 // FIXME supported frame counts should not be hard-coded
1594 (
1595 (frameCount == 128) ||
1596 (frameCount == 256) ||
1597 (frameCount == 512)
1598 )
1599 )
1600 ) &&
1601 // PCM data
1602 audio_is_linear_pcm(format) &&
1603 // mono or stereo
1604 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1605 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1606 // hardware sample rate
1607 (sampleRate == mSampleRate)
1608 // FIXME test that MixerThread for this fast track has a capable output HAL
1609 // FIXME add a permission test also?
1610 ) ) {
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001611 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied");
Glenn Kasten73d22752012-03-19 13:38:30 -07001612 flags &= ~IAudioFlinger::TRACK_FAST;
1613 }
1614
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001616 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1617 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001618 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001619 "for output %p with format %d",
1620 sampleRate, format, channelMask, mOutput, mFormat);
1621 lStatus = BAD_VALUE;
1622 goto Exit;
1623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 }
1625 } else {
1626 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1627 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001628 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 lStatus = BAD_VALUE;
1630 goto Exit;
1631 }
1632 }
1633
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001634 lStatus = initCheck();
1635 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001636 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 goto Exit;
1638 }
1639
1640 { // scope for mLock
1641 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001642
1643 // all tracks in same audio session must share the same routing strategy otherwise
1644 // conflicts will happen when tracks are moved from one output to another by audio policy
1645 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001646 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001647 for (size_t i = 0; i < mTracks.size(); ++i) {
1648 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001649 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001650 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001651 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001652 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001653 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001654 lStatus = BAD_VALUE;
1655 goto Exit;
1656 }
1657 }
1658 }
1659
John Grossman4ff14ba2012-02-08 16:37:41 -08001660 if (!isTimed) {
1661 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001662 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001663 } else {
1664 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1665 channelMask, frameCount, sharedBuffer, sessionId);
1666 }
1667 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668 lStatus = NO_MEMORY;
1669 goto Exit;
1670 }
1671 mTracks.add(track);
1672
1673 sp<EffectChain> chain = getEffectChain_l(sessionId);
1674 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001675 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001677 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001678 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 }
1680 }
1681 lStatus = NO_ERROR;
1682
1683Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001684 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 *status = lStatus;
1686 }
1687 return track;
1688}
1689
1690uint32_t AudioFlinger::PlaybackThread::latency() const
1691{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001692 Mutex::Autolock _l(mLock);
1693 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001694 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001695 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 return 0;
1697 }
1698}
1699
Glenn Kasten6637baa2012-01-09 09:40:36 -08001700void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001702 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704}
1705
Glenn Kasten6637baa2012-01-09 09:40:36 -08001706void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001708 Mutex::Autolock _l(mLock);
1709 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710}
1711
Glenn Kasten6637baa2012-01-09 09:40:36 -08001712void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001714 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716}
1717
Glenn Kasten6637baa2012-01-09 09:40:36 -08001718void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001720 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722}
1723
Glenn Kastenfff6d712012-01-12 16:38:12 -08001724float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001726 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 return mStreamTypes[stream].volume;
1728}
1729
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730// addTrack_l() must be called with ThreadBase::mLock held
1731status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1732{
1733 status_t status = ALREADY_EXISTS;
1734
1735 // set retry count for buffer fill
1736 track->mRetryCount = kMaxTrackStartupRetries;
1737 if (mActiveTracks.indexOf(track) < 0) {
1738 // the track is newly added, make sure it fills up all its
1739 // buffers before playing. This is to ensure the client will
1740 // effectively get the latency it requested.
1741 track->mFillingUpStatus = Track::FS_FILLING;
1742 track->mResetDone = false;
1743 mActiveTracks.add(track);
1744 if (track->mainBuffer() != mMixBuffer) {
1745 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1746 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001747 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001748 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 }
1750 }
1751
1752 status = NO_ERROR;
1753 }
1754
Steve Block3856b092011-10-20 11:56:00 +01001755 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 mWaitWorkCV.broadcast();
1757
1758 return status;
1759}
1760
1761// destroyTrack_l() must be called with ThreadBase::mLock held
1762void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1763{
1764 track->mState = TrackBase::TERMINATED;
1765 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001766 removeTrack_l(track);
1767 }
1768}
1769
1770void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1771{
1772 mTracks.remove(track);
1773 deleteTrackName_l(track->name());
1774 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1775 if (chain != 0) {
1776 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 }
1778}
1779
1780String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1781{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001782 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001783 char *s;
1784
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001785 Mutex::Autolock _l(mLock);
1786 if (initCheck() != NO_ERROR) {
1787 return out_s8;
1788 }
1789
Dima Zavin799a70e2011-04-18 16:57:27 -07001790 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001791 out_s8 = String8(s);
1792 free(s);
1793 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794}
1795
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001796// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1798 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001799 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800
Steve Block3856b092011-10-20 11:56:00 +01001801 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802
1803 switch (event) {
1804 case AudioSystem::OUTPUT_OPENED:
1805 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001806 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 desc.samplingRate = mSampleRate;
1808 desc.format = mFormat;
1809 desc.frameCount = mFrameCount;
1810 desc.latency = latency();
1811 param2 = &desc;
1812 break;
1813
1814 case AudioSystem::STREAM_CONFIG_CHANGED:
1815 param2 = &param;
1816 case AudioSystem::OUTPUT_CLOSED:
1817 default:
1818 break;
1819 }
1820 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1821}
1822
1823void AudioFlinger::PlaybackThread::readOutputParameters()
1824{
Dima Zavin799a70e2011-04-18 16:57:27 -07001825 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001826 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1827 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001828 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001829 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001830 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831
1832 // FIXME - Current mixer implementation only supports stereo output: Always
1833 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001834 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 mMixBuffer = new int16_t[mFrameCount * 2];
1836 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1837
Eric Laurentde070132010-07-13 04:45:46 -07001838 // force reconfiguration of effect chains and engines to take new buffer size and audio
1839 // parameters into account
1840 // Note that mLock is not held when readOutputParameters() is called from the constructor
1841 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1842 // matter.
1843 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1844 Vector< sp<EffectChain> > effectChains = mEffectChains;
1845 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001846 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001847 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848}
1849
1850status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1851{
Glenn Kastena0d68332012-01-27 16:47:15 -08001852 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 return BAD_VALUE;
1854 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001855 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001856 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 return INVALID_OPERATION;
1858 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001859 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860
Dima Zavin799a70e2011-04-18 16:57:27 -07001861 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862}
1863
Eric Laurent39e94f82010-07-28 01:32:47 -07001864uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865{
1866 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001867 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001869 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 }
1871
1872 for (size_t i = 0; i < mTracks.size(); ++i) {
1873 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001874 if (sessionId == track->sessionId() &&
1875 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001876 result |= TRACK_SESSION;
1877 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 }
1879 }
1880
Eric Laurent39e94f82010-07-28 01:32:47 -07001881 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882}
1883
Eric Laurentde070132010-07-13 04:45:46 -07001884uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1885{
Dima Zavinfce7a472011-04-19 22:30:36 -07001886 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001887 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001888 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1889 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001890 }
1891 for (size_t i = 0; i < mTracks.size(); i++) {
1892 sp<Track> track = mTracks[i];
1893 if (sessionId == track->sessionId() &&
1894 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001895 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001896 }
1897 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001898 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001899}
1900
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901
Glenn Kastenaed850d2012-01-26 09:46:34 -08001902AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001903{
1904 Mutex::Autolock _l(mLock);
1905 return mOutput;
1906}
1907
1908AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1909{
1910 Mutex::Autolock _l(mLock);
1911 AudioStreamOut *output = mOutput;
1912 mOutput = NULL;
1913 return output;
1914}
1915
1916// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001917audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001918{
1919 if (mOutput == NULL) {
1920 return NULL;
1921 }
1922 return &mOutput->stream->common;
1923}
1924
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001925uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08001926{
1927 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1928 // decoding and transfer time. So sleeping for half of the latency would likely cause
1929 // underruns
1930 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1931 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1932 } else {
1933 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1934 }
1935}
1936
Eric Laurenta011e352012-03-29 15:51:43 -07001937status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1938{
1939 if (!isValidSyncEvent(event)) {
1940 return BAD_VALUE;
1941 }
1942
1943 Mutex::Autolock _l(mLock);
1944
1945 for (size_t i = 0; i < mTracks.size(); ++i) {
1946 sp<Track> track = mTracks[i];
1947 if (event->triggerSession() == track->sessionId()) {
1948 track->setSyncEvent(event);
1949 return NO_ERROR;
1950 }
1951 }
1952
1953 return NAME_NOT_FOUND;
1954}
1955
1956bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
1957{
1958 switch (event->type()) {
1959 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
1960 return true;
1961 default:
1962 break;
1963 }
1964 return false;
1965}
1966
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967// ----------------------------------------------------------------------------
1968
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001969AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001970 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001971 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001973 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 // FIXME - Current mixer implementation only supports stereo output
1975 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001976 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 }
1978}
1979
1980AudioFlinger::MixerThread::~MixerThread()
1981{
1982 delete mAudioMixer;
1983}
1984
Glenn Kasten83efdd02012-02-24 07:21:32 -08001985class CpuStats {
1986public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001987 CpuStats();
1988 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08001989#ifdef DEBUG_CPU_USAGE
1990private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08001991 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
1992 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
1993
1994 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
1995
1996 int mCpuNum; // thread's current CPU number
1997 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08001998#endif
1999};
2000
Glenn Kasten190a46f2012-03-06 11:27:10 -08002001CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002002#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002003 : mCpuNum(-1), mCpukHz(-1)
2004#endif
2005{
2006}
2007
2008void CpuStats::sample(const String8 &title) {
2009#ifdef DEBUG_CPU_USAGE
2010 // get current thread's delta CPU time in wall clock ns
2011 double wcNs;
2012 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2013
2014 // record sample for wall clock statistics
2015 if (valid) {
2016 mWcStats.sample(wcNs);
2017 }
2018
2019 // get the current CPU number
2020 int cpuNum = sched_getcpu();
2021
2022 // get the current CPU frequency in kHz
2023 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2024
2025 // check if either CPU number or frequency changed
2026 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2027 mCpuNum = cpuNum;
2028 mCpukHz = cpukHz;
2029 // ignore sample for purposes of cycles
2030 valid = false;
2031 }
2032
2033 // if no change in CPU number or frequency, then record sample for cycle statistics
2034 if (valid && mCpukHz > 0) {
2035 double cycles = wcNs * cpukHz * 0.000001;
2036 mHzStats.sample(cycles);
2037 }
2038
2039 unsigned n = mWcStats.n();
2040 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002041 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002042 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002043 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2044 double perLoop = elapsed / (double) n;
2045 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002046 double perLoop1k = perLoop * 0.001;
2047 double mean = mWcStats.mean();
2048 double stddev = mWcStats.stddev();
2049 double minimum = mWcStats.minimum();
2050 double maximum = mWcStats.maximum();
2051 double meanCycles = mHzStats.mean();
2052 double stddevCycles = mHzStats.stddev();
2053 double minCycles = mHzStats.minimum();
2054 double maxCycles = mHzStats.maximum();
2055 mCpuUsage.resetElapsed();
2056 mWcStats.reset();
2057 mHzStats.reset();
2058 ALOGD("CPU usage for %s over past %.1f secs\n"
2059 " (%u mixer loops at %.1f mean ms per loop):\n"
2060 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2061 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2062 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2063 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002064 elapsed * .000000001, n, perLoop * .000001,
2065 mean * .001,
2066 stddev * .001,
2067 minimum * .001,
2068 maximum * .001,
2069 mean / perLoop100,
2070 stddev / perLoop100,
2071 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002072 maximum / perLoop100,
2073 meanCycles / perLoop1k,
2074 stddevCycles / perLoop1k,
2075 minCycles / perLoop1k,
2076 maxCycles / perLoop1k);
2077
Glenn Kasten83efdd02012-02-24 07:21:32 -08002078 }
2079 }
2080#endif
2081};
2082
Glenn Kasten37d825e2012-02-24 07:21:48 -08002083void AudioFlinger::PlaybackThread::checkSilentMode_l()
2084{
2085 if (!mMasterMute) {
2086 char value[PROPERTY_VALUE_MAX];
2087 if (property_get("ro.audio.silent", value, "0") > 0) {
2088 char *endptr;
2089 unsigned long ul = strtoul(value, &endptr, 0);
2090 if (*endptr == '\0' && ul != 0) {
2091 ALOGD("Silence is golden");
2092 // The setprop command will not allow a property to be changed after
2093 // the first time it is set, so we don't have to worry about un-muting.
2094 setMasterMute_l(true);
2095 }
2096 }
2097 }
2098}
2099
Glenn Kasten000f0e32012-03-01 17:10:56 -08002100bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101{
2102 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002103
Glenn Kasten000f0e32012-03-01 17:10:56 -08002104 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002105
2106 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002108if (mType == MIXER) {
2109 longStandbyExit = false;
2110}
Glenn Kasten688a6402012-02-29 07:57:06 -08002111
Glenn Kasten000f0e32012-03-01 17:10:56 -08002112 // DUPLICATING
2113 // FIXME could this be made local to while loop?
2114 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002115
Glenn Kasten66fcab92012-02-24 14:59:21 -08002116 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002117 sleepTime = idleSleepTime;
2118
2119if (mType == MIXER) {
2120 sleepTimeShift = 0;
2121}
2122
Glenn Kasten83efdd02012-02-24 07:21:32 -08002123 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002124 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
Eric Laurentfeb0db62011-07-22 09:04:31 -07002126 acquireWakeLock();
2127
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 while (!exitPending())
2129 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002130 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002131
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002132 Vector< sp<EffectChain> > effectChains;
2133
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 processConfigEvents();
2135
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 { // scope for mLock
2137
2138 Mutex::Autolock _l(mLock);
2139
2140 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002141 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142 }
2143
Glenn Kastenfa26a852012-03-06 11:28:04 -08002144 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002145
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002147 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002148 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002150
2151 threadLoop_standby();
2152
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 mStandby = true;
2154 mBytesWritten = 0;
2155 }
2156
Glenn Kasten3e074702012-02-28 18:40:35 -08002157 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 // we're about to wait, flush the binder command buffer
2159 IPCThreadState::self()->flushCommands();
2160
Glenn Kastenfa26a852012-03-06 11:28:04 -08002161 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002162
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 if (exitPending()) break;
2164
Eric Laurentfeb0db62011-07-22 09:04:31 -07002165 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002167 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002169 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002170 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171
Eric Laurent27741442012-01-17 19:20:12 -08002172 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002173
Glenn Kasten37d825e2012-02-24 07:21:48 -08002174 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175
Glenn Kasten000f0e32012-03-01 17:10:56 -08002176 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002178 if (mType == MIXER) {
2179 sleepTimeShift = 0;
2180 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002181
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 continue;
2183 }
2184 }
2185
Glenn Kastenfec279f2012-03-08 07:47:15 -08002186 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2187 // Shift in the new status; this could be a queue if it's
2188 // useful to filter the mixer status over several cycles.
2189 mPrevMixerStatus = mMixerStatus;
2190 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191
2192 // prevent any changes in effect chain list and in each effect chain
2193 // during mixing and effect process as the audio buffers could be deleted
2194 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002195 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197
Glenn Kastenfec279f2012-03-08 07:47:15 -08002198 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002199 threadLoop_mix();
2200 } else {
2201 threadLoop_sleepTime();
2202 }
2203
2204 if (mSuspended > 0) {
2205 sleepTime = suspendSleepTimeUs();
2206 }
2207
2208 // only process effects if we're going to write
2209 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002210 for (size_t i = 0; i < effectChains.size(); i ++) {
2211 effectChains[i]->process_l();
2212 }
2213 }
2214
2215 // enable changes in effect chain
2216 unlockEffectChains(effectChains);
2217
2218 // sleepTime == 0 means we must write to audio hardware
2219 if (sleepTime == 0) {
2220
2221 threadLoop_write();
2222
2223if (mType == MIXER) {
2224 // write blocked detection
2225 nsecs_t now = systemTime();
2226 nsecs_t delta = now - mLastWriteTime;
2227 if (!mStandby && delta > maxPeriod) {
2228 mNumDelayedWrites++;
2229 if ((now - lastWarning) > kWarningThrottleNs) {
2230 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2231 ns2ms(delta), mNumDelayedWrites, this);
2232 lastWarning = now;
2233 }
2234 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2235 // a different threshold. Or completely removed for what it is worth anyway...
2236 if (mStandby) {
2237 longStandbyExit = true;
2238 }
2239 }
2240}
2241
2242 mStandby = false;
2243 } else {
2244 usleep(sleepTime);
2245 }
2246
2247 // finally let go of removed track(s), without the lock held
2248 // since we can't guarantee the destructors won't acquire that
2249 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002250 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002251
Glenn Kastenfa26a852012-03-06 11:28:04 -08002252 // FIXME I don't understand the need for this here;
2253 // it was in the original code but maybe the
2254 // assignment in saveOutputTracks() makes this unnecessary?
2255 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002256
2257 // Effect chains will be actually deleted here if they were removed from
2258 // mEffectChains list during mixing or effects processing
2259 effectChains.clear();
2260
2261 // FIXME Note that the above .clear() is no longer necessary since effectChains
2262 // is now local to this block, but will keep it for now (at least until merge done).
2263 }
2264
2265if (mType == MIXER || mType == DIRECT) {
2266 // put output stream into standby mode
2267 if (!mStandby) {
2268 mOutput->stream->common.standby(&mOutput->stream->common);
2269 }
2270}
2271if (mType == DUPLICATING) {
2272 // for DuplicatingThread, standby mode is handled by the outputTracks
2273}
2274
2275 releaseWakeLock();
2276
2277 ALOGV("Thread %p type %d exiting", this, mType);
2278 return false;
2279}
2280
2281// shared by MIXER and DIRECT, overridden by DUPLICATING
2282void AudioFlinger::PlaybackThread::threadLoop_write()
2283{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002284 // FIXME rewrite to reduce number of system calls
2285 mLastWriteTime = systemTime();
2286 mInWrite = true;
2287 mBytesWritten += mixBufferSize;
2288 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2289 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2290 mNumWrites++;
2291 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002292}
2293
2294// shared by MIXER and DIRECT, overridden by DUPLICATING
2295void AudioFlinger::PlaybackThread::threadLoop_standby()
2296{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002297 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2298 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002299}
2300
2301void AudioFlinger::MixerThread::threadLoop_mix()
2302{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002303 // obtain the presentation timestamp of the next output buffer
2304 int64_t pts;
2305 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002306
Glenn Kasten952eeb22012-03-06 11:30:57 -08002307 if (NULL != mOutput->stream->get_next_write_timestamp) {
2308 status = mOutput->stream->get_next_write_timestamp(
2309 mOutput->stream, &pts);
2310 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002311
Glenn Kasten952eeb22012-03-06 11:30:57 -08002312 if (status != NO_ERROR) {
2313 pts = AudioBufferProvider::kInvalidPTS;
2314 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002315
Glenn Kasten952eeb22012-03-06 11:30:57 -08002316 // mix buffers...
2317 mAudioMixer->process(pts);
2318 // increase sleep time progressively when application underrun condition clears.
2319 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2320 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2321 // such that we would underrun the audio HAL.
2322 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2323 sleepTimeShift--;
2324 }
2325 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002326 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002327 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002328}
2329
2330void AudioFlinger::MixerThread::threadLoop_sleepTime()
2331{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002332 // If no tracks are ready, sleep once for the duration of an output
2333 // buffer size, then write 0s to the output
2334 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002335 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002336 sleepTime = activeSleepTime >> sleepTimeShift;
2337 if (sleepTime < kMinThreadSleepTimeUs) {
2338 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002340 // reduce sleep time in case of consecutive application underruns to avoid
2341 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2342 // duration we would end up writing less data than needed by the audio HAL if
2343 // the condition persists.
2344 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2345 sleepTimeShift++;
2346 }
2347 } else {
2348 sleepTime = idleSleepTime;
2349 }
2350 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002351 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002352 memset (mMixBuffer, 0, mixBufferSize);
2353 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002354 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002355 }
2356 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357}
2358
2359// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002360AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002361 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362{
2363
Glenn Kasten29c23c32012-01-26 13:37:52 -08002364 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002366 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 size_t mixedTracks = 0;
2368 size_t tracksWithEffect = 0;
2369
2370 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002371 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372
Eric Laurent571d49c2010-08-11 05:20:11 -07002373 if (masterMute) {
2374 masterVolume = 0;
2375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002377 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002379 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002380 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 masterVolume = (float)((v + (1 << 23)) >> 24);
2382 chain.clear();
2383 }
2384
2385 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002386 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 if (t == 0) continue;
2388
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002389 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 Track* const track = t.get();
2391 audio_track_cblk_t* cblk = track->cblk();
2392
2393 // The first time a track is added we wait
2394 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002395 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002396 // make sure that we have enough frames to mix one full buffer.
2397 // enforce this condition only once to enable draining the buffer in case the client
2398 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002399 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002400 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002401 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002402 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002403 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002404 if (t->sampleRate() == (int)mSampleRate) {
2405 minFrames = mFrameCount;
2406 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002407 // +1 for rounding and +1 for additional sample needed for interpolation
2408 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2409 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002410 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002411 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2412 // the minimum track buffer size is normally twice the number of frames necessary
2413 // to fill one buffer and the resampler should not leave more than one buffer worth
2414 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002415 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002416 }
2417 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002418 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 !track->isPaused() && !track->isTerminated())
2420 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002421 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422
2423 mixedTracks++;
2424
2425 // track->mainBuffer() != mMixBuffer means there is an effect chain
2426 // connected to the track
2427 chain.clear();
2428 if (track->mainBuffer() != mMixBuffer) {
2429 chain = getEffectChain_l(track->sessionId());
2430 // Delegate volume control to effect in track effect chain if needed
2431 if (chain != 0) {
2432 tracksWithEffect++;
2433 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002434 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002435 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 }
2437 }
2438
2439
2440 int param = AudioMixer::VOLUME;
2441 if (track->mFillingUpStatus == Track::FS_FILLED) {
2442 // no ramp for the first volume setting
2443 track->mFillingUpStatus = Track::FS_ACTIVE;
2444 if (track->mState == TrackBase::RESUMING) {
2445 track->mState = TrackBase::ACTIVE;
2446 param = AudioMixer::RAMP_VOLUME;
2447 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002448 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 } else if (cblk->server != 0) {
2450 // If the track is stopped before the first frame was mixed,
2451 // do not apply ramp
2452 param = AudioMixer::RAMP_VOLUME;
2453 }
2454
2455 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002456 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002457 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002458 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002459 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 if (track->isPausing()) {
2461 track->setPaused();
2462 }
2463 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002464
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002466 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002468 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002469 vl = vlr & 0xFFFF;
2470 vr = vlr >> 16;
2471 // track volumes come from shared memory, so can't be trusted and must be clamped
2472 if (vl > MAX_GAIN_INT) {
2473 ALOGV("Track left volume out of range: %04X", vl);
2474 vl = MAX_GAIN_INT;
2475 }
2476 if (vr > MAX_GAIN_INT) {
2477 ALOGV("Track right volume out of range: %04X", vr);
2478 vr = MAX_GAIN_INT;
2479 }
2480 // now apply the master volume and stream type volume
2481 vl = (uint32_t)(v * vl) << 12;
2482 vr = (uint32_t)(v * vr) << 12;
2483 // assuming master volume and stream type volume each go up to 1.0,
2484 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
Glenn Kasten05632a52012-01-03 14:22:33 -08002486 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2487 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002488 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002489 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002490 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002491 }
2492 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002494 // Delegate volume control to effect in track effect chain if needed
2495 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2496 // Do not ramp volume if volume is controlled by effect
2497 param = AudioMixer::VOLUME;
2498 track->mHasVolumeController = true;
2499 } else {
2500 // force no volume ramp when volume controller was just disabled or removed
2501 // from effect chain to avoid volume spike
2502 if (track->mHasVolumeController) {
2503 param = AudioMixer::VOLUME;
2504 }
2505 track->mHasVolumeController = false;
2506 }
2507
2508 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002509 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002510 vl = (vl + (1 << 11)) >> 12;
2511 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2512 vr = (vr + (1 << 11)) >> 12;
2513 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002514
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002515 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 -07002516
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002518 mAudioMixer->setBufferProvider(name, track);
2519 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002521 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2522 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2523 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002525 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 AudioMixer::TRACK,
2527 AudioMixer::FORMAT, (void *)track->format());
2528 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002529 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002531 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002533 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 AudioMixer::RESAMPLE,
2535 AudioMixer::SAMPLE_RATE,
2536 (void *)(cblk->sampleRate));
2537 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002538 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 AudioMixer::TRACK,
2540 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2541 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002542 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 AudioMixer::TRACK,
2544 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2545
2546 // reset retry count
2547 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002548
Eric Laurent27741442012-01-17 19:20:12 -08002549 // If one track is ready, set the mixer ready if:
2550 // - the mixer was not ready during previous round OR
2551 // - no other track is not ready
2552 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2553 mixerStatus != MIXER_TRACKS_ENABLED) {
2554 mixerStatus = MIXER_TRACKS_READY;
2555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002557 //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 -07002558 if (track->isStopped()) {
2559 track->reset();
2560 }
2561 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2562 // We have consumed all the buffers of this track.
2563 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002564 // TODO: use actual buffer filling status instead of latency when available from
2565 // audio HAL
2566 size_t audioHALFrames =
2567 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2568 size_t framesWritten =
2569 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2570 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2571 tracksToRemove->add(track);
2572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 } else {
2574 // No buffers for this track. Give it a few chances to
2575 // fill a buffer, then remove it from active list.
2576 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002577 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002579 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002580 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002581 // If one track is not ready, mark the mixer also not ready if:
2582 // - the mixer was ready during previous round OR
2583 // - no other track is ready
2584 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2585 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 mixerStatus = MIXER_TRACKS_ENABLED;
2587 }
2588 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002589 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 }
2591 }
2592
2593 // remove all the tracks that need to be...
2594 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002595 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 for (size_t i=0 ; i<count ; i++) {
2597 const sp<Track>& track = tracksToRemove->itemAt(i);
2598 mActiveTracks.remove(track);
2599 if (track->mainBuffer() != mMixBuffer) {
2600 chain = getEffectChain_l(track->sessionId());
2601 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002602 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002603 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 }
2605 }
2606 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002607 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 }
2609 }
2610 }
2611
2612 // mix buffer must be cleared if all tracks are connected to an
2613 // effect chain as in this case the mixer will not write to
2614 // mix buffer and track effects will accumulate into it
2615 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2616 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2617 }
2618
2619 return mixerStatus;
2620}
2621
Glenn Kasten66fcab92012-02-24 14:59:21 -08002622/*
2623The derived values that are cached:
2624 - mixBufferSize from frame count * frame size
2625 - activeSleepTime from activeSleepTimeUs()
2626 - idleSleepTime from idleSleepTimeUs()
2627 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2628 - maxPeriod from frame count and sample rate (MIXER only)
2629
2630The parameters that affect these derived values are:
2631 - frame count
2632 - frame size
2633 - sample rate
2634 - device type: A2DP or not
2635 - device latency
2636 - format: PCM or not
2637 - active sleep time
2638 - idle sleep time
2639*/
2640
2641void AudioFlinger::PlaybackThread::cacheParameters_l()
2642{
2643 mixBufferSize = mFrameCount * mFrameSize;
2644 activeSleepTime = activeSleepTimeUs();
2645 idleSleepTime = idleSleepTimeUs();
2646}
2647
Glenn Kastenfff6d712012-01-12 16:38:12 -08002648void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649{
Steve Block3856b092011-10-20 11:56:00 +01002650 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002651 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002653
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 size_t size = mTracks.size();
2655 for (size_t i = 0; i < size; i++) {
2656 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002657 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002658 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 }
2661 }
2662}
2663
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002665int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666{
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002667 int name = mAudioMixer->getTrackName();
2668 if (name >= 0) {
2669 mAudioMixer->setParameter(name,
2670 AudioMixer::TRACK,
2671 AudioMixer::CHANNEL_MASK, (void *)channelMask);
2672 }
2673 return name;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674}
2675
2676// deleteTrackName_l() must be called with ThreadBase::mLock held
2677void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2678{
Steve Block3856b092011-10-20 11:56:00 +01002679 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 mAudioMixer->deleteTrackName(name);
2681}
2682
2683// checkForNewParameters_l() must be called with ThreadBase::mLock held
2684bool AudioFlinger::MixerThread::checkForNewParameters_l()
2685{
2686 bool reconfig = false;
2687
2688 while (!mNewParameters.isEmpty()) {
2689 status_t status = NO_ERROR;
2690 String8 keyValuePair = mNewParameters[0];
2691 AudioParameter param = AudioParameter(keyValuePair);
2692 int value;
2693
2694 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2695 reconfig = true;
2696 }
2697 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002698 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699 status = BAD_VALUE;
2700 } else {
2701 reconfig = true;
2702 }
2703 }
2704 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002705 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 status = BAD_VALUE;
2707 } else {
2708 reconfig = true;
2709 }
2710 }
2711 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2712 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002713 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714 // if frame count is changed after track creation
2715 if (!mTracks.isEmpty()) {
2716 status = INVALID_OPERATION;
2717 } else {
2718 reconfig = true;
2719 }
2720 }
2721 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002722#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002723 // when changing the audio output device, call addBatteryData to notify
2724 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002725 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002726 uint32_t params = 0;
2727 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002728 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002729 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2730 }
2731
2732 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002733 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002734 // check if any other device (except speaker) is on
2735 if (value & deviceWithoutSpeaker ) {
2736 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2737 }
2738
2739 if (params != 0) {
2740 addBatteryData(params);
2741 }
2742 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002743#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002744
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 // forward device change to effects that have requested to be
2746 // aware of attached audio device.
2747 mDevice = (uint32_t)value;
2748 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002749 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750 }
2751 }
2752
2753 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002754 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002755 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002757 mOutput->stream->common.standby(&mOutput->stream->common);
2758 mStandby = true;
2759 mBytesWritten = 0;
2760 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002761 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762 }
2763 if (status == NO_ERROR && reconfig) {
2764 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002765 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2766 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 readOutputParameters();
2768 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2769 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002770 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 if (name < 0) break;
2772 mTracks[i]->mName = name;
2773 // limit track sample rate to 2 x new output sample rate
2774 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2775 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2776 }
2777 }
2778 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2779 }
2780 }
2781
2782 mNewParameters.removeAt(0);
2783
2784 mParamStatus = status;
2785 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002786 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2787 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002788 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 }
2790 return reconfig;
2791}
2792
2793status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2794{
2795 const size_t SIZE = 256;
2796 char buffer[SIZE];
2797 String8 result;
2798
2799 PlaybackThread::dumpInternals(fd, args);
2800
2801 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2802 result.append(buffer);
2803 write(fd, result.string(), result.size());
2804 return NO_ERROR;
2805}
2806
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002807uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808{
Eric Laurent60e18242010-07-29 06:50:24 -07002809 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810}
2811
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002812uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002813{
2814 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2815}
2816
Glenn Kasten66fcab92012-02-24 14:59:21 -08002817void AudioFlinger::MixerThread::cacheParameters_l()
2818{
2819 PlaybackThread::cacheParameters_l();
2820
2821 // FIXME: Relaxed timing because of a certain device that can't meet latency
2822 // Should be reduced to 2x after the vendor fixes the driver issue
2823 // increase threshold again due to low power audio mode. The way this warning
2824 // threshold is calculated and its usefulness should be reconsidered anyway.
2825 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2826}
2827
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002829AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2830 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002831 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002832 // mLeftVolFloat, mRightVolFloat
2833 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835}
2836
2837AudioFlinger::DirectOutputThread::~DirectOutputThread()
2838{
2839}
2840
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002841AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2842 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002843)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002845 sp<Track> trackToRemove;
2846
Glenn Kastenfec279f2012-03-08 07:47:15 -08002847 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848
Glenn Kasten952eeb22012-03-06 11:30:57 -08002849 // find out which tracks need to be processed
2850 if (mActiveTracks.size() != 0) {
2851 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002852 // The track died recently
2853 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854
Glenn Kasten952eeb22012-03-06 11:30:57 -08002855 Track* const track = t.get();
2856 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857
Glenn Kasten952eeb22012-03-06 11:30:57 -08002858 // The first time a track is added we wait
2859 // for all its buffers to be filled before processing it
2860 if (cblk->framesReady() && track->isReady() &&
2861 !track->isPaused() && !track->isTerminated())
2862 {
2863 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864
Glenn Kasten952eeb22012-03-06 11:30:57 -08002865 if (track->mFillingUpStatus == Track::FS_FILLED) {
2866 track->mFillingUpStatus = Track::FS_ACTIVE;
2867 mLeftVolFloat = mRightVolFloat = 0;
2868 mLeftVolShort = mRightVolShort = 0;
2869 if (track->mState == TrackBase::RESUMING) {
2870 track->mState = TrackBase::ACTIVE;
2871 rampVolume = true;
2872 }
2873 } else if (cblk->server != 0) {
2874 // If the track is stopped before the first frame was mixed,
2875 // do not apply ramp
2876 rampVolume = true;
2877 }
2878 // compute volume for this track
2879 float left, right;
2880 if (track->isMuted() || mMasterMute || track->isPausing() ||
2881 mStreamTypes[track->streamType()].mute) {
2882 left = right = 0;
2883 if (track->isPausing()) {
2884 track->setPaused();
2885 }
2886 } else {
2887 float typeVolume = mStreamTypes[track->streamType()].volume;
2888 float v = mMasterVolume * typeVolume;
2889 uint32_t vlr = cblk->getVolumeLR();
2890 float v_clamped = v * (vlr & 0xFFFF);
2891 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2892 left = v_clamped/MAX_GAIN;
2893 v_clamped = v * (vlr >> 16);
2894 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2895 right = v_clamped/MAX_GAIN;
2896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897
Glenn Kasten952eeb22012-03-06 11:30:57 -08002898 if (left != mLeftVolFloat || right != mRightVolFloat) {
2899 mLeftVolFloat = left;
2900 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901
Glenn Kasten952eeb22012-03-06 11:30:57 -08002902 // If audio HAL implements volume control,
2903 // force software volume to nominal value
2904 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2905 left = 1.0f;
2906 right = 1.0f;
2907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908
Glenn Kasten952eeb22012-03-06 11:30:57 -08002909 // Convert volumes from float to 8.24
2910 uint32_t vl = (uint32_t)(left * (1 << 24));
2911 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912
Glenn Kasten952eeb22012-03-06 11:30:57 -08002913 // Delegate volume control to effect in track effect chain if needed
2914 // only one effect chain can be present on DirectOutputThread, so if
2915 // there is one, the track is connected to it
2916 if (!mEffectChains.isEmpty()) {
2917 // Do not ramp volume if volume is controlled by effect
2918 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 rampVolume = false;
2920 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922
Glenn Kasten952eeb22012-03-06 11:30:57 -08002923 // Convert volumes from 8.24 to 4.12 format
2924 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2925 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2926 leftVol = (uint16_t)v_clamped;
2927 v_clamped = (vr + (1 << 11)) >> 12;
2928 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2929 rightVol = (uint16_t)v_clamped;
2930 } else {
2931 leftVol = mLeftVolShort;
2932 rightVol = mRightVolShort;
2933 rampVolume = false;
2934 }
2935
2936 // reset retry count
2937 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002938 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002939 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002940 } else {
2941 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2942 if (track->isStopped()) {
2943 track->reset();
2944 }
2945 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2946 // We have consumed all the buffers of this track.
2947 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002948 // TODO: implement behavior for compressed audio
2949 size_t audioHALFrames =
2950 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2951 size_t framesWritten =
2952 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2953 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2954 trackToRemove = track;
2955 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002956 } else {
2957 // No buffers for this track. Give it a few chances to
2958 // fill a buffer, then remove it from active list.
2959 if (--(track->mRetryCount) <= 0) {
2960 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2961 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002963 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 }
2965 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002966 }
2967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002969 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002970 // remove all the tracks that need to be...
2971 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002972 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002973 mActiveTracks.remove(trackToRemove);
2974 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002975 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002976 trackToRemove->sessionId());
2977 mEffectChains[0]->decActiveTrackCnt();
2978 }
2979 if (trackToRemove->isTerminated()) {
2980 removeTrack_l(trackToRemove);
2981 }
2982 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983
Glenn Kastenfec279f2012-03-08 07:47:15 -08002984 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002985}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986
Glenn Kasten000f0e32012-03-01 17:10:56 -08002987void AudioFlinger::DirectOutputThread::threadLoop_mix()
2988{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002989 AudioBufferProvider::Buffer buffer;
2990 size_t frameCount = mFrameCount;
2991 int8_t *curBuf = (int8_t *)mMixBuffer;
2992 // output audio to hardware
2993 while (frameCount) {
2994 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002995 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002996 if (CC_UNLIKELY(buffer.raw == NULL)) {
2997 memset(curBuf, 0, frameCount * mFrameSize);
2998 break;
2999 }
3000 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3001 frameCount -= buffer.frameCount;
3002 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003003 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003004 }
3005 sleepTime = 0;
3006 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003007 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003008
3009 // apply volume
3010
3011 // Do not apply volume on compressed audio
3012 if (!audio_is_linear_pcm(mFormat)) {
3013 return;
3014 }
3015
3016 // convert to signed 16 bit before volume calculation
3017 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3018 size_t count = mFrameCount * mChannelCount;
3019 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3020 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003021 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003022 *dst-- = (int16_t)(*src--^0x80) << 8;
3023 }
3024 }
3025
3026 frameCount = mFrameCount;
3027 int16_t *out = mMixBuffer;
3028 if (rampVolume) {
3029 if (mChannelCount == 1) {
3030 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3031 int32_t vlInc = d / (int32_t)frameCount;
3032 int32_t vl = ((int32_t)mLeftVolShort << 16);
3033 do {
3034 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3035 out++;
3036 vl += vlInc;
3037 } while (--frameCount);
3038
3039 } else {
3040 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3041 int32_t vlInc = d / (int32_t)frameCount;
3042 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3043 int32_t vrInc = d / (int32_t)frameCount;
3044 int32_t vl = ((int32_t)mLeftVolShort << 16);
3045 int32_t vr = ((int32_t)mRightVolShort << 16);
3046 do {
3047 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3048 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3049 out += 2;
3050 vl += vlInc;
3051 vr += vrInc;
3052 } while (--frameCount);
3053 }
3054 } else {
3055 if (mChannelCount == 1) {
3056 do {
3057 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3058 out++;
3059 } while (--frameCount);
3060 } else {
3061 do {
3062 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3063 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3064 out += 2;
3065 } while (--frameCount);
3066 }
3067 }
3068
3069 // convert back to unsigned 8 bit after volume calculation
3070 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3071 size_t count = mFrameCount * mChannelCount;
3072 int16_t *src = mMixBuffer;
3073 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003074 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003075 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3076 }
3077 }
3078
3079 mLeftVolShort = leftVol;
3080 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003081}
3082
3083void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3084{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003085 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003086 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003087 sleepTime = activeSleepTime;
3088 } else {
3089 sleepTime = idleSleepTime;
3090 }
3091 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3092 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3093 sleepTime = 0;
3094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095}
3096
3097// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003098int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099{
3100 return 0;
3101}
3102
3103// deleteTrackName_l() must be called with ThreadBase::mLock held
3104void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3105{
3106}
3107
3108// checkForNewParameters_l() must be called with ThreadBase::mLock held
3109bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3110{
3111 bool reconfig = false;
3112
3113 while (!mNewParameters.isEmpty()) {
3114 status_t status = NO_ERROR;
3115 String8 keyValuePair = mNewParameters[0];
3116 AudioParameter param = AudioParameter(keyValuePair);
3117 int value;
3118
3119 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3120 // do not accept frame count changes if tracks are open as the track buffer
3121 // size depends on frame count and correct behavior would not be garantied
3122 // if frame count is changed after track creation
3123 if (!mTracks.isEmpty()) {
3124 status = INVALID_OPERATION;
3125 } else {
3126 reconfig = true;
3127 }
3128 }
3129 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003130 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003131 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003133 mOutput->stream->common.standby(&mOutput->stream->common);
3134 mStandby = true;
3135 mBytesWritten = 0;
3136 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003137 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138 }
3139 if (status == NO_ERROR && reconfig) {
3140 readOutputParameters();
3141 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3142 }
3143 }
3144
3145 mNewParameters.removeAt(0);
3146
3147 mParamStatus = status;
3148 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003149 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3150 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003151 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 }
3153 return reconfig;
3154}
3155
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003156uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157{
3158 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003159 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003160 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 } else {
3162 time = 10000;
3163 }
3164 return time;
3165}
3166
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003167uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168{
3169 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003170 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003171 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 } else {
3173 time = 10000;
3174 }
3175 return time;
3176}
3177
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003178uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003179{
3180 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003181 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003182 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3183 } else {
3184 time = 10000;
3185 }
3186 return time;
3187}
3188
Glenn Kasten66fcab92012-02-24 14:59:21 -08003189void AudioFlinger::DirectOutputThread::cacheParameters_l()
3190{
3191 PlaybackThread::cacheParameters_l();
3192
3193 // use shorter standby delay as on normal output to release
3194 // hardware resources as soon as possible
3195 standbyDelay = microseconds(activeSleepTime*2);
3196}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003197
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198// ----------------------------------------------------------------------------
3199
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003200AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003201 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003202 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3203 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 addOutputTrack(mainThread);
3206}
3207
3208AudioFlinger::DuplicatingThread::~DuplicatingThread()
3209{
3210 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3211 mOutputTracks[i]->destroy();
3212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213}
3214
Glenn Kasten000f0e32012-03-01 17:10:56 -08003215void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003217 // mix buffers...
3218 if (outputsReady(outputTracks)) {
3219 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3220 } else {
3221 memset(mMixBuffer, 0, mixBufferSize);
3222 }
3223 sleepTime = 0;
3224 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003225}
3226
3227void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3228{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003229 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003230 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003231 sleepTime = activeSleepTime;
3232 } else {
3233 sleepTime = idleSleepTime;
3234 }
3235 } else if (mBytesWritten != 0) {
3236 // flush remaining overflow buffers in output tracks
3237 for (size_t i = 0; i < outputTracks.size(); i++) {
3238 if (outputTracks[i]->isActive()) {
3239 sleepTime = 0;
3240 writeFrames = 0;
3241 memset(mMixBuffer, 0, mixBufferSize);
3242 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003244 }
3245 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003246}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247
Glenn Kasten000f0e32012-03-01 17:10:56 -08003248void AudioFlinger::DuplicatingThread::threadLoop_write()
3249{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003250 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003251 for (size_t i = 0; i < outputTracks.size(); i++) {
3252 outputTracks[i]->write(mMixBuffer, writeFrames);
3253 }
3254 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003255}
Glenn Kasten688a6402012-02-29 07:57:06 -08003256
Glenn Kasten000f0e32012-03-01 17:10:56 -08003257void AudioFlinger::DuplicatingThread::threadLoop_standby()
3258{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003259 // DuplicatingThread implements standby by stopping all tracks
3260 for (size_t i = 0; i < outputTracks.size(); i++) {
3261 outputTracks[i]->stop();
3262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263}
3264
Glenn Kastenfa26a852012-03-06 11:28:04 -08003265void AudioFlinger::DuplicatingThread::saveOutputTracks()
3266{
3267 outputTracks = mOutputTracks;
3268}
3269
3270void AudioFlinger::DuplicatingThread::clearOutputTracks()
3271{
3272 outputTracks.clear();
3273}
3274
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3276{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003277 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003278 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003280 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 this,
3282 mSampleRate,
3283 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003284 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 frameCount);
3286 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003287 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003289 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003290 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 }
3292}
3293
3294void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3295{
3296 Mutex::Autolock _l(mLock);
3297 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003298 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 mOutputTracks[i]->destroy();
3300 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003301 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 return;
3303 }
3304 }
Steve Block3856b092011-10-20 11:56:00 +01003305 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306}
3307
Glenn Kasten438b0362012-03-06 11:24:48 -08003308// caller must hold mLock
3309void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310{
3311 mWaitTimeMs = UINT_MAX;
3312 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3313 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003314 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3316 if (waitTimeMs < mWaitTimeMs) {
3317 mWaitTimeMs = waitTimeMs;
3318 }
3319 }
3320 }
3321}
3322
3323
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003324bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325{
3326 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003327 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003329 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 return false;
3331 }
3332 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3333 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003334 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 return false;
3336 }
3337 }
3338 return true;
3339}
3340
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003341uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342{
3343 return (mWaitTimeMs * 1000) / 2;
3344}
3345
Glenn Kasten66fcab92012-02-24 14:59:21 -08003346void AudioFlinger::DuplicatingThread::cacheParameters_l()
3347{
3348 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3349 updateWaitTime_l();
3350
3351 MixerThread::cacheParameters_l();
3352}
3353
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354// ----------------------------------------------------------------------------
3355
3356// TrackBase constructor must be called with AudioFlinger::mLock held
3357AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003358 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 const sp<Client>& client,
3360 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003361 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003362 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364 const sp<IMemory>& sharedBuffer,
3365 int sessionId)
3366 : RefBase(),
3367 mThread(thread),
3368 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003369 mCblk(NULL),
3370 // mBuffer
3371 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 mFrameCount(0),
3373 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003375 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003377 // mChannelCount
3378 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379{
Steve Block3856b092011-10-20 11:56:00 +01003380 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381
Steve Blockb8a80522011-12-20 16:23:08 +00003382 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003383 size_t size = sizeof(audio_track_cblk_t);
3384 uint8_t channelCount = popcount(channelMask);
3385 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3386 if (sharedBuffer == 0) {
3387 size += bufferSize;
3388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003390 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 mCblkMemory = client->heap()->allocate(size);
3392 if (mCblkMemory != 0) {
3393 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003394 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 new(mCblk) audio_track_cblk_t();
3396 // clear all buffers
3397 mCblk->frameCount = frameCount;
3398 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003399// uncomment the following lines to quickly test 32-bit wraparound
3400// mCblk->user = 0xffff0000;
3401// mCblk->server = 0xffff0000;
3402// mCblk->userBase = 0xffff0000;
3403// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003404 mChannelCount = channelCount;
3405 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406 if (sharedBuffer == 0) {
3407 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3408 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3409 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003410 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 mCblk->flags = CBLK_UNDERRUN_ON;
3412 } else {
3413 mBuffer = sharedBuffer->pointer();
3414 }
3415 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3416 }
3417 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003418 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 client->heap()->dump("AudioTrack");
3420 return;
3421 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003422 } else {
3423 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003424 // construct the shared structure in-place.
3425 new(mCblk) audio_track_cblk_t();
3426 // clear all buffers
3427 mCblk->frameCount = frameCount;
3428 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003429// uncomment the following lines to quickly test 32-bit wraparound
3430// mCblk->user = 0xffff0000;
3431// mCblk->server = 0xffff0000;
3432// mCblk->userBase = 0xffff0000;
3433// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003434 mChannelCount = channelCount;
3435 mChannelMask = channelMask;
3436 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3437 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3438 // Force underrun condition to avoid false underrun callback until first data is
3439 // written to buffer (other flags are cleared)
3440 mCblk->flags = CBLK_UNDERRUN_ON;
3441 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443}
3444
3445AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3446{
Glenn Kastena0d68332012-01-27 16:47:15 -08003447 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003448 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003450 } else {
3451 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 }
3453 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003454 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003455 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003456 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003458 // If the client's reference count drops to zero, the associated destructor
3459 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3460 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 mClient.clear();
3462 }
3463}
3464
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003465// AudioBufferProvider interface
3466// getNextBuffer() = 0;
3467// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3469{
Glenn Kastene0feee32011-12-13 11:53:26 -08003470 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003472 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 buffer->frameCount = 0;
3474}
3475
3476bool AudioFlinger::ThreadBase::TrackBase::step() {
3477 bool result;
3478 audio_track_cblk_t* cblk = this->cblk();
3479
3480 result = cblk->stepServer(mFrameCount);
3481 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003482 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003483 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 }
3485 return result;
3486}
3487
3488void AudioFlinger::ThreadBase::TrackBase::reset() {
3489 audio_track_cblk_t* cblk = this->cblk();
3490
3491 cblk->user = 0;
3492 cblk->server = 0;
3493 cblk->userBase = 0;
3494 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003495 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003496 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497}
3498
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3500 return (int)mCblk->sampleRate;
3501}
3502
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3504 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003505 size_t frameSize = cblk->frameSize;
3506 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3507 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508
3509 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003510 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3511 "TrackBase::getBuffer buffer out of range:\n"
3512 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3513 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003515 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516
3517 return bufferStart;
3518}
3519
Eric Laurenta011e352012-03-29 15:51:43 -07003520status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3521{
3522 mSyncEvents.add(event);
3523 return NO_ERROR;
3524}
3525
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526// ----------------------------------------------------------------------------
3527
3528// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3529AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003530 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003532 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003534 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003535 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 int frameCount,
3537 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003538 int sessionId,
3539 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003540 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003541 mMute(false),
3542 // mFillingUpStatus ?
3543 // mRetryCount initialized later when needed
3544 mSharedBuffer(sharedBuffer),
3545 mStreamType(streamType),
3546 mName(-1), // see note below
3547 mMainBuffer(thread->mixBuffer()),
3548 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003549 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003550 mPresentationCompleteFrames(0),
3551 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552{
3553 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3555 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003556 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003557 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003558 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07003559 if (mName < 0) {
3560 ALOGE("no more track names available");
3561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003563 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564}
3565
3566AudioFlinger::PlaybackThread::Track::~Track()
3567{
Steve Block3856b092011-10-20 11:56:00 +01003568 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 sp<ThreadBase> thread = mThread.promote();
3570 if (thread != 0) {
3571 Mutex::Autolock _l(thread->mLock);
3572 mState = TERMINATED;
3573 }
3574}
3575
3576void AudioFlinger::PlaybackThread::Track::destroy()
3577{
3578 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3579 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003580 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 // we must acquire a strong reference on this Track before locking mLock
3582 // here so that the destructor is called only when exiting this function.
3583 // On the other hand, as long as Track::destroy() is only called by
3584 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3585 // this Track with its member mTrack.
3586 sp<Track> keep(this);
3587 { // scope for mLock
3588 sp<ThreadBase> thread = mThread.promote();
3589 if (thread != 0) {
3590 if (!isOutputTrack()) {
3591 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003592 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003593
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003594#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003595 // to track the speaker usage
3596 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003597#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 }
3599 AudioSystem::releaseOutput(thread->id());
3600 }
3601 Mutex::Autolock _l(thread->mLock);
3602 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3603 playbackThread->destroyTrack_l(this);
3604 }
3605 }
3606}
3607
3608void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3609{
Glenn Kasten83d86532012-01-17 14:39:34 -08003610 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003611 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003613 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 mStreamType,
3615 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003616 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 mSessionId,
3618 mFrameCount,
3619 mState,
3620 mMute,
3621 mFillingUpStatus,
3622 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003623 vlr & 0xFFFF,
3624 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 mCblk->server,
3626 mCblk->user,
3627 (int)mMainBuffer,
3628 (int)mAuxBuffer);
3629}
3630
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003631// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003632status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003633 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003635 audio_track_cblk_t* cblk = this->cblk();
3636 uint32_t framesReady;
3637 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003639 // Check if last stepServer failed, try to step now
3640 if (mStepServerFailed) {
3641 if (!step()) goto getNextBuffer_exit;
3642 ALOGV("stepServer recovered");
3643 mStepServerFailed = false;
3644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003646 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003648 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649 uint32_t s = cblk->server;
3650 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3651
3652 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3653 if (framesReq > framesReady) {
3654 framesReq = framesReady;
3655 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003656 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657 framesReq = bufferEnd - s;
3658 }
3659
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003660 buffer->raw = getBuffer(s, framesReq);
3661 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003662
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003663 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003665 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666
3667getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003668 buffer->raw = NULL;
3669 buffer->frameCount = 0;
3670 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3671 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672}
3673
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003674uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003675 return mCblk->framesReady();
3676}
3677
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003679 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680
John Grossman4ff14ba2012-02-08 16:37:41 -08003681 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3683 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003684 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 return true;
3686 }
3687 return false;
3688}
3689
Eric Laurenta011e352012-03-29 15:51:43 -07003690status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid,
3691 AudioSystem::sync_event_t event,
3692 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693{
3694 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003695 ALOGV("start(%d), calling pid %d session %d tid %d",
3696 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Glenn Kasten73d22752012-03-19 13:38:30 -07003697 // check for use case 2 with missing callback
3698 if (isFastTrack() && (mSharedBuffer == 0) && (tid == 0)) {
Eric Laurent0ca3cf92012-04-18 09:24:29 -07003699 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied");
Glenn Kasten73d22752012-03-19 13:38:30 -07003700 mFlags &= ~IAudioFlinger::TRACK_FAST;
3701 // FIXME the track must be invalidated and moved to another thread or
3702 // attached directly to the normal mixer now
3703 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704 sp<ThreadBase> thread = mThread.promote();
3705 if (thread != 0) {
3706 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003707 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 // here the track could be either new, or restarted
3709 // in both cases "unstop" the track
3710 if (mState == PAUSED) {
3711 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003712 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 } else {
3714 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003715 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 }
3717
3718 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3719 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003720 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003722
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003723#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003724 // to track the speaker usage
3725 if (status == NO_ERROR) {
3726 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3727 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003728#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 }
3730 if (status == NO_ERROR) {
3731 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3732 playbackThread->addTrack_l(this);
3733 } else {
3734 mState = state;
3735 }
3736 } else {
3737 status = BAD_VALUE;
3738 }
3739 return status;
3740}
3741
3742void AudioFlinger::PlaybackThread::Track::stop()
3743{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003744 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745 sp<ThreadBase> thread = mThread.promote();
3746 if (thread != 0) {
3747 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003748 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749 if (mState > STOPPED) {
3750 mState = STOPPED;
3751 // If the track is not active (PAUSED and buffers full), flush buffers
3752 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3753 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3754 reset();
3755 }
Steve Block3856b092011-10-20 11:56:00 +01003756 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 }
3758 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3759 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003760 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003762
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003763#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003764 // to track the speaker usage
3765 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003766#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 }
3768 }
3769}
3770
3771void AudioFlinger::PlaybackThread::Track::pause()
3772{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003773 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 sp<ThreadBase> thread = mThread.promote();
3775 if (thread != 0) {
3776 Mutex::Autolock _l(thread->mLock);
3777 if (mState == ACTIVE || mState == RESUMING) {
3778 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003779 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 if (!isOutputTrack()) {
3781 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003782 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003784
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003785#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003786 // to track the speaker usage
3787 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003788#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 }
3790 }
3791 }
3792}
3793
3794void AudioFlinger::PlaybackThread::Track::flush()
3795{
Steve Block3856b092011-10-20 11:56:00 +01003796 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 sp<ThreadBase> thread = mThread.promote();
3798 if (thread != 0) {
3799 Mutex::Autolock _l(thread->mLock);
3800 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3801 return;
3802 }
3803 // No point remaining in PAUSED state after a flush => go to
3804 // STOPPED state
3805 mState = STOPPED;
3806
Eric Laurent38ccae22011-03-28 18:37:07 -07003807 // do not reset the track if it is still in the process of being stopped or paused.
3808 // this will be done by prepareTracks_l() when the track is stopped.
3809 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3810 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3811 reset();
3812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003813 }
3814}
3815
3816void AudioFlinger::PlaybackThread::Track::reset()
3817{
3818 // Do not reset twice to avoid discarding data written just after a flush and before
3819 // the audioflinger thread detects the track is stopped.
3820 if (!mResetDone) {
3821 TrackBase::reset();
3822 // Force underrun condition to avoid false underrun callback until first data is
3823 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003824 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3825 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 mFillingUpStatus = FS_FILLING;
3827 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07003828 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 }
3830}
3831
3832void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3833{
3834 mMute = muted;
3835}
3836
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3838{
3839 status_t status = DEAD_OBJECT;
3840 sp<ThreadBase> thread = mThread.promote();
3841 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003842 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3843 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 }
3845 return status;
3846}
3847
3848void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3849{
3850 mAuxEffectId = EffectId;
3851 mAuxBuffer = buffer;
3852}
3853
Eric Laurenta011e352012-03-29 15:51:43 -07003854bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
3855 size_t audioHalFrames)
3856{
3857 // a track is considered presented when the total number of frames written to audio HAL
3858 // corresponds to the number of frames written when presentationComplete() is called for the
3859 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
3860 if (mPresentationCompleteFrames == 0) {
3861 mPresentationCompleteFrames = framesWritten + audioHalFrames;
3862 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
3863 mPresentationCompleteFrames, audioHalFrames);
3864 }
3865 if (framesWritten >= mPresentationCompleteFrames) {
3866 ALOGV("presentationComplete() session %d complete: framesWritten %d",
3867 mSessionId, framesWritten);
3868 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
3869 mPresentationCompleteFrames = 0;
3870 return true;
3871 }
3872 return false;
3873}
3874
3875void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
3876{
3877 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
3878 if (mSyncEvents[i]->type() == type) {
3879 mSyncEvents[i]->trigger();
3880 mSyncEvents.removeAt(i);
3881 i--;
3882 }
3883 }
3884}
3885
3886
John Grossman4ff14ba2012-02-08 16:37:41 -08003887// timed audio tracks
3888
3889sp<AudioFlinger::PlaybackThread::TimedTrack>
3890AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003891 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003892 const sp<Client>& client,
3893 audio_stream_type_t streamType,
3894 uint32_t sampleRate,
3895 audio_format_t format,
3896 uint32_t channelMask,
3897 int frameCount,
3898 const sp<IMemory>& sharedBuffer,
3899 int sessionId) {
3900 if (!client->reserveTimedTrack())
3901 return NULL;
3902
Glenn Kastena0356762012-03-19 10:38:51 -07003903 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08003904 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3905 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08003906}
3907
3908AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003909 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08003910 const sp<Client>& client,
3911 audio_stream_type_t streamType,
3912 uint32_t sampleRate,
3913 audio_format_t format,
3914 uint32_t channelMask,
3915 int frameCount,
3916 const sp<IMemory>& sharedBuffer,
3917 int sessionId)
3918 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07003919 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07003920 mQueueHeadInFlight(false),
3921 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07003922 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08003923 mTimedSilenceBuffer(NULL),
3924 mTimedSilenceBufferSize(0),
3925 mTimedAudioOutputOnTime(false),
3926 mMediaTimeTransformValid(false)
3927{
3928 LocalClock lc;
3929 mLocalTimeFreq = lc.getLocalFreq();
3930
3931 mLocalTimeToSampleTransform.a_zero = 0;
3932 mLocalTimeToSampleTransform.b_zero = 0;
3933 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3934 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3935 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3936 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07003937
3938 mMediaTimeToSampleTransform.a_zero = 0;
3939 mMediaTimeToSampleTransform.b_zero = 0;
3940 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
3941 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
3942 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
3943 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08003944}
3945
3946AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3947 mClient->releaseTimedTrack();
3948 delete [] mTimedSilenceBuffer;
3949}
3950
3951status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3952 size_t size, sp<IMemory>* buffer) {
3953
3954 Mutex::Autolock _l(mTimedBufferQueueLock);
3955
3956 trimTimedBufferQueue_l();
3957
3958 // lazily initialize the shared memory heap for timed buffers
3959 if (mTimedMemoryDealer == NULL) {
3960 const int kTimedBufferHeapSize = 512 << 10;
3961
3962 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3963 "AudioFlingerTimed");
3964 if (mTimedMemoryDealer == NULL)
3965 return NO_MEMORY;
3966 }
3967
3968 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3969 if (newBuffer == NULL) {
3970 newBuffer = mTimedMemoryDealer->allocate(size);
3971 if (newBuffer == NULL)
3972 return NO_MEMORY;
3973 }
3974
3975 *buffer = newBuffer;
3976 return NO_ERROR;
3977}
3978
3979// caller must hold mTimedBufferQueueLock
3980void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3981 int64_t mediaTimeNow;
3982 {
3983 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3984 if (!mMediaTimeTransformValid)
3985 return;
3986
3987 int64_t targetTimeNow;
3988 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3989 ? mCCHelper.getCommonTime(&targetTimeNow)
3990 : mCCHelper.getLocalTime(&targetTimeNow);
3991
3992 if (OK != res)
3993 return;
3994
3995 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3996 &mediaTimeNow)) {
3997 return;
3998 }
3999 }
4000
John Grossman1c345192012-03-27 14:00:17 -07004001 size_t trimEnd;
4002 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
4003 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
John Grossman9fbdee12012-03-26 17:51:46 -07004004 / mCblk->frameSize;
4005 int64_t bufEnd;
4006
4007 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4008 &bufEnd)) {
4009 ALOGE("Failed to convert frame count of %lld to media time duration"
4010 " (scale factor %d/%u) in %s", frameCount,
4011 mMediaTimeToSampleTransform.a_to_b_numer,
4012 mMediaTimeToSampleTransform.a_to_b_denom,
4013 __PRETTY_FUNCTION__);
John Grossman4ff14ba2012-02-08 16:37:41 -08004014 break;
John Grossman9fbdee12012-03-26 17:51:46 -07004015 }
John Grossman1c345192012-03-27 14:00:17 -07004016 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004017
4018 if (bufEnd > mediaTimeNow)
4019 break;
4020
4021 // Is the buffer we want to use in the middle of a mix operation right
4022 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4023 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004024 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004025 mTrimQueueHeadOnRelease = true;
4026 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004027 }
4028
John Grossman9fbdee12012-03-26 17:51:46 -07004029 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004030 if (trimStart < trimEnd) {
4031 // Update the bookkeeping for framesReady()
4032 for (size_t i = trimStart; i < trimEnd; ++i) {
4033 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4034 }
4035
4036 // Now actually remove the buffers from the queue.
4037 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004038 }
4039}
4040
John Grossman1c345192012-03-27 14:00:17 -07004041void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4042 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004043 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4044 "%s called (reason \"%s\"), but timed buffer queue has no"
4045 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004046
4047 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4048 mTimedBufferQueue.removeAt(0);
4049}
4050
4051void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4052 const TimedBuffer& buf,
4053 const char* logTag) {
4054 uint32_t bufBytes = buf.buffer()->size();
4055 uint32_t consumedAlready = buf.position();
4056
Eric Laurentb388e532012-04-14 13:32:48 -07004057 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004058 "Bad bookkeeping while updating frames pending. Timed buffer is"
4059 " only %u bytes long, but claims to have consumed %u"
4060 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004061 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004062
4063 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004064 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4065 "Bad bookkeeping while updating frames pending. Should have at"
4066 " least %u queued frames, but we think we have only %u. (update"
4067 " reason: \"%s\")",
4068 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004069
4070 mFramesPendingInQueue -= bufFrames;
4071}
4072
John Grossman4ff14ba2012-02-08 16:37:41 -08004073status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4074 const sp<IMemory>& buffer, int64_t pts) {
4075
4076 {
4077 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4078 if (!mMediaTimeTransformValid)
4079 return INVALID_OPERATION;
4080 }
4081
4082 Mutex::Autolock _l(mTimedBufferQueueLock);
4083
John Grossman1c345192012-03-27 14:00:17 -07004084 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4085 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004086 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4087
4088 return NO_ERROR;
4089}
4090
4091status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4092 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4093
John Grossman1c345192012-03-27 14:00:17 -07004094 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4095 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4096 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004097
4098 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4099 target == TimedAudioTrack::COMMON_TIME)) {
4100 return BAD_VALUE;
4101 }
4102
4103 Mutex::Autolock lock(mMediaTimeTransformLock);
4104 mMediaTimeTransform = xform;
4105 mMediaTimeTransformTarget = target;
4106 mMediaTimeTransformValid = true;
4107
4108 return NO_ERROR;
4109}
4110
4111#define min(a, b) ((a) < (b) ? (a) : (b))
4112
4113// implementation of getNextBuffer for tracks whose buffers have timestamps
4114status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4115 AudioBufferProvider::Buffer* buffer, int64_t pts)
4116{
4117 if (pts == AudioBufferProvider::kInvalidPTS) {
4118 buffer->raw = 0;
4119 buffer->frameCount = 0;
4120 return INVALID_OPERATION;
4121 }
4122
John Grossman4ff14ba2012-02-08 16:37:41 -08004123 Mutex::Autolock _l(mTimedBufferQueueLock);
4124
John Grossman9fbdee12012-03-26 17:51:46 -07004125 ALOG_ASSERT(!mQueueHeadInFlight,
4126 "getNextBuffer called without releaseBuffer!");
4127
John Grossman4ff14ba2012-02-08 16:37:41 -08004128 while (true) {
4129
4130 // if we have no timed buffers, then fail
4131 if (mTimedBufferQueue.isEmpty()) {
4132 buffer->raw = 0;
4133 buffer->frameCount = 0;
4134 return NOT_ENOUGH_DATA;
4135 }
4136
4137 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4138
4139 // calculate the PTS of the head of the timed buffer queue expressed in
4140 // local time
4141 int64_t headLocalPTS;
4142 {
4143 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4144
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004145 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004146
4147 if (mMediaTimeTransform.a_to_b_denom == 0) {
4148 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004149 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004150 return NO_ERROR;
4151 }
4152
4153 int64_t transformedPTS;
4154 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4155 &transformedPTS)) {
4156 // the transform failed. this shouldn't happen, but if it does
4157 // then just drop this buffer
4158 ALOGW("timedGetNextBuffer transform failed");
4159 buffer->raw = 0;
4160 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004161 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004162 return NO_ERROR;
4163 }
4164
4165 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4166 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4167 &headLocalPTS)) {
4168 buffer->raw = 0;
4169 buffer->frameCount = 0;
4170 return INVALID_OPERATION;
4171 }
4172 } else {
4173 headLocalPTS = transformedPTS;
4174 }
4175 }
4176
4177 // adjust the head buffer's PTS to reflect the portion of the head buffer
4178 // that has already been consumed
4179 int64_t effectivePTS = headLocalPTS +
4180 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4181
4182 // Calculate the delta in samples between the head of the input buffer
4183 // queue and the start of the next output buffer that will be written.
4184 // If the transformation fails because of over or underflow, it means
4185 // that the sample's position in the output stream is so far out of
4186 // whack that it should just be dropped.
4187 int64_t sampleDelta;
4188 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4189 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004190 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4191 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004192 continue;
4193 }
4194 if (!mLocalTimeToSampleTransform.doForwardTransform(
4195 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004196 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004197 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004198 continue;
4199 }
4200
John Grossman1c345192012-03-27 14:00:17 -07004201 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4202 " sampleDelta=[%d.%08x]",
4203 head.pts(), head.position(), pts,
4204 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4205 + (sampleDelta >> 32)),
4206 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004207
4208 // if the delta between the ideal placement for the next input sample and
4209 // the current output position is within this threshold, then we will
4210 // concatenate the next input samples to the previous output
4211 const int64_t kSampleContinuityThreshold =
4212 (static_cast<int64_t>(sampleRate()) << 32) / 10;
4213
4214 // if this is the first buffer of audio that we're emitting from this track
4215 // then it should be almost exactly on time.
4216 const int64_t kSampleStartupThreshold = 1LL << 32;
4217
4218 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
4219 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
4220 // the next input is close enough to being on time, so concatenate it
4221 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004222 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004223
John Grossman1c345192012-03-27 14:00:17 -07004224 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4225 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004226 return NO_ERROR;
4227 } else if (sampleDelta > 0) {
4228 // the gap between the current output position and the proper start of
4229 // the next input sample is too big, so fill it with silence
4230 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4231
John Grossman9fbdee12012-03-26 17:51:46 -07004232 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004233 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4234 return NO_ERROR;
4235 } else {
4236 // the next input sample is late
4237 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4238 size_t onTimeSamplePosition =
4239 head.position() + lateFrames * mCblk->frameSize;
4240
4241 if (onTimeSamplePosition > head.buffer()->size()) {
4242 // all the remaining samples in the head are too late, so
4243 // drop it and move on
4244 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004245 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004246 continue;
4247 } else {
4248 // skip over the late samples
4249 head.setPosition(onTimeSamplePosition);
4250
4251 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004252 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004253
4254 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4255 return NO_ERROR;
4256 }
4257 }
4258 }
4259}
4260
4261// Yield samples from the timed buffer queue head up to the given output
4262// buffer's capacity.
4263//
4264// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004265void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004266 AudioBufferProvider::Buffer* buffer) {
4267
4268 const TimedBuffer& head = mTimedBufferQueue[0];
4269
4270 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4271 head.position());
4272
4273 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4274 mCblk->frameSize);
4275 size_t framesRequested = buffer->frameCount;
4276 buffer->frameCount = min(framesLeftInHead, framesRequested);
4277
John Grossman9fbdee12012-03-26 17:51:46 -07004278 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004279 mTimedAudioOutputOnTime = true;
4280}
4281
4282// Yield samples of silence up to the given output buffer's capacity
4283//
4284// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004285void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004286 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4287
4288 // lazily allocate a buffer filled with silence
4289 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4290 delete [] mTimedSilenceBuffer;
4291 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4292 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4293 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4294 }
4295
4296 buffer->raw = mTimedSilenceBuffer;
4297 size_t framesRequested = buffer->frameCount;
4298 buffer->frameCount = min(numFrames, framesRequested);
4299
4300 mTimedAudioOutputOnTime = false;
4301}
4302
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004303// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004304void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4305 AudioBufferProvider::Buffer* buffer) {
4306
4307 Mutex::Autolock _l(mTimedBufferQueueLock);
4308
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004309 // If the buffer which was just released is part of the buffer at the head
4310 // of the queue, be sure to update the amt of the buffer which has been
4311 // consumed. If the buffer being returned is not part of the head of the
4312 // queue, its either because the buffer is part of the silence buffer, or
4313 // because the head of the timed queue was trimmed after the mixer called
4314 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004315 if (buffer->raw == mTimedSilenceBuffer) {
4316 ALOG_ASSERT(!mQueueHeadInFlight,
4317 "Queue head in flight during release of silence buffer!");
4318 goto done;
4319 }
4320
4321 ALOG_ASSERT(mQueueHeadInFlight,
4322 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4323 " head in flight.");
4324
4325 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004326 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004327
4328 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004329 void* end = reinterpret_cast<void*>(
4330 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4331 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004332
John Grossman9fbdee12012-03-26 17:51:46 -07004333 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4334 "released buffer not within the head of the timed buffer"
4335 " queue; qHead = [%p, %p], released buffer = %p",
4336 start, end, buffer->raw);
4337
4338 head.setPosition(head.position() +
4339 (buffer->frameCount * mCblk->frameSize));
4340 mQueueHeadInFlight = false;
4341
John Grossman1c345192012-03-27 14:00:17 -07004342 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4343 "Bad bookkeeping during releaseBuffer! Should have at"
4344 " least %u queued frames, but we think we have only %u",
4345 buffer->frameCount, mFramesPendingInQueue);
4346
4347 mFramesPendingInQueue -= buffer->frameCount;
4348
John Grossman9fbdee12012-03-26 17:51:46 -07004349 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4350 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004351 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004352 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004353 }
John Grossman9fbdee12012-03-26 17:51:46 -07004354 } else {
4355 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4356 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004357 }
4358
John Grossman9fbdee12012-03-26 17:51:46 -07004359done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004360 buffer->raw = 0;
4361 buffer->frameCount = 0;
4362}
4363
4364uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4365 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004366 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004367}
4368
4369AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4370 : mPTS(0), mPosition(0) {}
4371
4372AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4373 const sp<IMemory>& buffer, int64_t pts)
4374 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4375
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376// ----------------------------------------------------------------------------
4377
4378// RecordTrack constructor must be called with AudioFlinger::mLock held
4379AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004380 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 const sp<Client>& client,
4382 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004383 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004384 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386 int sessionId)
4387 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004388 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 mOverflow(false)
4390{
4391 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004392 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4393 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4394 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4395 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4396 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4397 } else {
4398 mCblk->frameSize = sizeof(int8_t);
4399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 }
4401}
4402
4403AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4404{
4405 sp<ThreadBase> thread = mThread.promote();
4406 if (thread != 0) {
4407 AudioSystem::releaseInput(thread->id());
4408 }
4409}
4410
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004411// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004412status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413{
4414 audio_track_cblk_t* cblk = this->cblk();
4415 uint32_t framesAvail;
4416 uint32_t framesReq = buffer->frameCount;
4417
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004418 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004419 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004421 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004422 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424
4425 framesAvail = cblk->framesAvailable_l();
4426
Glenn Kastenf6b16782011-12-15 09:51:17 -08004427 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 uint32_t s = cblk->server;
4429 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4430
4431 if (framesReq > framesAvail) {
4432 framesReq = framesAvail;
4433 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004434 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 framesReq = bufferEnd - s;
4436 }
4437
4438 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004439 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440
4441 buffer->frameCount = framesReq;
4442 return NO_ERROR;
4443 }
4444
4445getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004446 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 buffer->frameCount = 0;
4448 return NOT_ENOUGH_DATA;
4449}
4450
Eric Laurenta011e352012-03-29 15:51:43 -07004451status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid,
4452 AudioSystem::sync_event_t event,
4453 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454{
4455 sp<ThreadBase> thread = mThread.promote();
4456 if (thread != 0) {
4457 RecordThread *recordThread = (RecordThread *)thread.get();
Eric Laurenta011e352012-03-29 15:51:43 -07004458 return recordThread->start(this, tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 } else {
4460 return BAD_VALUE;
4461 }
4462}
4463
4464void AudioFlinger::RecordThread::RecordTrack::stop()
4465{
4466 sp<ThreadBase> thread = mThread.promote();
4467 if (thread != 0) {
4468 RecordThread *recordThread = (RecordThread *)thread.get();
4469 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004470 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004471 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004472 // read from buffer
4473 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 }
4475}
4476
4477void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4478{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004479 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004480 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004482 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 mSessionId,
4484 mFrameCount,
4485 mState,
4486 mCblk->sampleRate,
4487 mCblk->server,
4488 mCblk->user);
4489}
4490
4491
4492// ----------------------------------------------------------------------------
4493
4494AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004495 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 DuplicatingThread *sourceThread,
4497 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004498 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004499 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004501 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4502 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 mActive(false), mSourceThread(sourceThread)
4504{
4505
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 if (mCblk != NULL) {
4507 mCblk->flags |= CBLK_DIRECTION_OUT;
4508 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 mOutBuffer.frameCount = 0;
4510 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004511 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004512 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4513 mCblk, mBuffer, mCblk->buffers,
4514 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004516 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 }
4518}
4519
4520AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4521{
4522 clearBufferQueue();
4523}
4524
Eric Laurenta011e352012-03-29 15:51:43 -07004525status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid,
4526 AudioSystem::sync_event_t event,
4527 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528{
Eric Laurenta011e352012-03-29 15:51:43 -07004529 status_t status = Track::start(tid, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 if (status != NO_ERROR) {
4531 return status;
4532 }
4533
4534 mActive = true;
4535 mRetryCount = 127;
4536 return status;
4537}
4538
4539void AudioFlinger::PlaybackThread::OutputTrack::stop()
4540{
4541 Track::stop();
4542 clearBufferQueue();
4543 mOutBuffer.frameCount = 0;
4544 mActive = false;
4545}
4546
4547bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4548{
4549 Buffer *pInBuffer;
4550 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004551 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 bool outputBufferFull = false;
4553 inBuffer.frameCount = frames;
4554 inBuffer.i16 = data;
4555
4556 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4557
4558 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004559 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 sp<ThreadBase> thread = mThread.promote();
4561 if (thread != 0) {
4562 MixerThread *mixerThread = (MixerThread *)thread.get();
4563 if (mCblk->frameCount > frames){
4564 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4565 uint32_t startFrames = (mCblk->frameCount - frames);
4566 pInBuffer = new Buffer;
4567 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4568 pInBuffer->frameCount = startFrames;
4569 pInBuffer->i16 = pInBuffer->mBuffer;
4570 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4571 mBufferQueue.add(pInBuffer);
4572 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004573 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 }
4575 }
4576 }
4577 }
4578
4579 while (waitTimeLeftMs) {
4580 // First write pending buffers, then new data
4581 if (mBufferQueue.size()) {
4582 pInBuffer = mBufferQueue.itemAt(0);
4583 } else {
4584 pInBuffer = &inBuffer;
4585 }
4586
4587 if (pInBuffer->frameCount == 0) {
4588 break;
4589 }
4590
4591 if (mOutBuffer.frameCount == 0) {
4592 mOutBuffer.frameCount = pInBuffer->frameCount;
4593 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004594 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004595 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 outputBufferFull = true;
4597 break;
4598 }
4599 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4600 if (waitTimeLeftMs >= waitTimeMs) {
4601 waitTimeLeftMs -= waitTimeMs;
4602 } else {
4603 waitTimeLeftMs = 0;
4604 }
4605 }
4606
4607 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4608 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4609 mCblk->stepUser(outFrames);
4610 pInBuffer->frameCount -= outFrames;
4611 pInBuffer->i16 += outFrames * channelCount;
4612 mOutBuffer.frameCount -= outFrames;
4613 mOutBuffer.i16 += outFrames * channelCount;
4614
4615 if (pInBuffer->frameCount == 0) {
4616 if (mBufferQueue.size()) {
4617 mBufferQueue.removeAt(0);
4618 delete [] pInBuffer->mBuffer;
4619 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004620 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 } else {
4622 break;
4623 }
4624 }
4625 }
4626
4627 // If we could not write all frames, allocate a buffer and queue it for next time.
4628 if (inBuffer.frameCount) {
4629 sp<ThreadBase> thread = mThread.promote();
4630 if (thread != 0 && !thread->standby()) {
4631 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4632 pInBuffer = new Buffer;
4633 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4634 pInBuffer->frameCount = inBuffer.frameCount;
4635 pInBuffer->i16 = pInBuffer->mBuffer;
4636 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4637 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004638 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004640 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 }
4642 }
4643 }
4644
4645 // Calling write() with a 0 length buffer, means that no more data will be written:
4646 // If no more buffers are pending, fill output track buffer to make sure it is started
4647 // by output mixer.
4648 if (frames == 0 && mBufferQueue.size() == 0) {
4649 if (mCblk->user < mCblk->frameCount) {
4650 frames = mCblk->frameCount - mCblk->user;
4651 pInBuffer = new Buffer;
4652 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4653 pInBuffer->frameCount = frames;
4654 pInBuffer->i16 = pInBuffer->mBuffer;
4655 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4656 mBufferQueue.add(pInBuffer);
4657 } else if (mActive) {
4658 stop();
4659 }
4660 }
4661
4662 return outputBufferFull;
4663}
4664
4665status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4666{
4667 int active;
4668 status_t result;
4669 audio_track_cblk_t* cblk = mCblk;
4670 uint32_t framesReq = buffer->frameCount;
4671
Steve Block3856b092011-10-20 11:56:00 +01004672// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 buffer->frameCount = 0;
4674
4675 uint32_t framesAvail = cblk->framesAvailable();
4676
4677
4678 if (framesAvail == 0) {
4679 Mutex::Autolock _l(cblk->lock);
4680 goto start_loop_here;
4681 while (framesAvail == 0) {
4682 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004683 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004684 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004685 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 }
4687 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4688 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004689 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690 }
4691 // read the server count again
4692 start_loop_here:
4693 framesAvail = cblk->framesAvailable_l();
4694 }
4695 }
4696
4697// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004698// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699// }
4700
4701 if (framesReq > framesAvail) {
4702 framesReq = framesAvail;
4703 }
4704
4705 uint32_t u = cblk->user;
4706 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4707
Marco Nelissena1472d92012-03-30 14:36:54 -07004708 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 framesReq = bufferEnd - u;
4710 }
4711
4712 buffer->frameCount = framesReq;
4713 buffer->raw = (void *)cblk->buffer(u);
4714 return NO_ERROR;
4715}
4716
4717
4718void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4719{
4720 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721
4722 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004723 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 delete [] pBuffer->mBuffer;
4725 delete pBuffer;
4726 }
4727 mBufferQueue.clear();
4728}
4729
4730// ----------------------------------------------------------------------------
4731
4732AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4733 : RefBase(),
4734 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004735 // 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 -07004736 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004737 mPid(pid),
4738 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739{
4740 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4741}
4742
4743// Client destructor must be called with AudioFlinger::mLock held
4744AudioFlinger::Client::~Client()
4745{
4746 mAudioFlinger->removeClient_l(mPid);
4747}
4748
Glenn Kasten435dbe62012-01-30 10:15:48 -08004749sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750{
4751 return mMemoryDealer;
4752}
4753
John Grossman4ff14ba2012-02-08 16:37:41 -08004754// Reserve one of the limited slots for a timed audio track associated
4755// with this client
4756bool AudioFlinger::Client::reserveTimedTrack()
4757{
4758 const int kMaxTimedTracksPerClient = 4;
4759
4760 Mutex::Autolock _l(mTimedTrackLock);
4761
4762 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4763 ALOGW("can not create timed track - pid %d has exceeded the limit",
4764 mPid);
4765 return false;
4766 }
4767
4768 mTimedTrackCount++;
4769 return true;
4770}
4771
4772// Release a slot for a timed audio track
4773void AudioFlinger::Client::releaseTimedTrack()
4774{
4775 Mutex::Autolock _l(mTimedTrackLock);
4776 mTimedTrackCount--;
4777}
4778
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779// ----------------------------------------------------------------------------
4780
4781AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4782 const sp<IAudioFlingerClient>& client,
4783 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004784 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785{
4786}
4787
4788AudioFlinger::NotificationClient::~NotificationClient()
4789{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004790}
4791
4792void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4793{
4794 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004795 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004796}
4797
4798// ----------------------------------------------------------------------------
4799
4800AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4801 : BnAudioTrack(),
4802 mTrack(track)
4803{
4804}
4805
4806AudioFlinger::TrackHandle::~TrackHandle() {
4807 // just stop the track on deletion, associated resources
4808 // will be freed from the main thread once all pending buffers have
4809 // been played. Unless it's not in the active track list, in which
4810 // case we free everything now...
4811 mTrack->destroy();
4812}
4813
Glenn Kasten90716c52012-01-26 13:40:12 -08004814sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4815 return mTrack->getCblk();
4816}
4817
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004818status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4819 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004820}
4821
4822void AudioFlinger::TrackHandle::stop() {
4823 mTrack->stop();
4824}
4825
4826void AudioFlinger::TrackHandle::flush() {
4827 mTrack->flush();
4828}
4829
4830void AudioFlinger::TrackHandle::mute(bool e) {
4831 mTrack->mute(e);
4832}
4833
4834void AudioFlinger::TrackHandle::pause() {
4835 mTrack->pause();
4836}
4837
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4839{
4840 return mTrack->attachAuxEffect(EffectId);
4841}
4842
John Grossman4ff14ba2012-02-08 16:37:41 -08004843status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4844 sp<IMemory>* buffer) {
4845 if (!mTrack->isTimedTrack())
4846 return INVALID_OPERATION;
4847
4848 PlaybackThread::TimedTrack* tt =
4849 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4850 return tt->allocateTimedBuffer(size, buffer);
4851}
4852
4853status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4854 int64_t pts) {
4855 if (!mTrack->isTimedTrack())
4856 return INVALID_OPERATION;
4857
4858 PlaybackThread::TimedTrack* tt =
4859 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4860 return tt->queueTimedBuffer(buffer, pts);
4861}
4862
4863status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4864 const LinearTransform& xform, int target) {
4865
4866 if (!mTrack->isTimedTrack())
4867 return INVALID_OPERATION;
4868
4869 PlaybackThread::TimedTrack* tt =
4870 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4871 return tt->setMediaTimeTransform(
4872 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4873}
4874
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875status_t AudioFlinger::TrackHandle::onTransact(
4876 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4877{
4878 return BnAudioTrack::onTransact(code, data, reply, flags);
4879}
4880
4881// ----------------------------------------------------------------------------
4882
4883sp<IAudioRecord> AudioFlinger::openRecord(
4884 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004885 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004886 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004887 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004888 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004890 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004891 int *sessionId,
4892 status_t *status)
4893{
4894 sp<RecordThread::RecordTrack> recordTrack;
4895 sp<RecordHandle> recordHandle;
4896 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 status_t lStatus;
4898 RecordThread *thread;
4899 size_t inFrameCount;
4900 int lSessionId;
4901
4902 // check calling permissions
4903 if (!recordingAllowed()) {
4904 lStatus = PERMISSION_DENIED;
4905 goto Exit;
4906 }
4907
4908 // add client to list
4909 { // scope for mLock
4910 Mutex::Autolock _l(mLock);
4911 thread = checkRecordThread_l(input);
4912 if (thread == NULL) {
4913 lStatus = BAD_VALUE;
4914 goto Exit;
4915 }
4916
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004917 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918
4919 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004920 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 lSessionId = *sessionId;
4922 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004923 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 if (sessionId != NULL) {
4925 *sessionId = lSessionId;
4926 }
4927 }
4928 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004929 recordTrack = thread->createRecordTrack_l(client,
4930 sampleRate,
4931 format,
4932 channelMask,
4933 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004934 lSessionId,
4935 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004937 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4939 // destructor is called by the TrackBase destructor with mLock held
4940 client.clear();
4941 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 goto Exit;
4943 }
4944
4945 // return to handle to client
4946 recordHandle = new RecordHandle(recordTrack);
4947 lStatus = NO_ERROR;
4948
4949Exit:
4950 if (status) {
4951 *status = lStatus;
4952 }
4953 return recordHandle;
4954}
4955
4956// ----------------------------------------------------------------------------
4957
4958AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4959 : BnAudioRecord(),
4960 mRecordTrack(recordTrack)
4961{
4962}
4963
4964AudioFlinger::RecordHandle::~RecordHandle() {
4965 stop();
4966}
4967
Glenn Kasten90716c52012-01-26 13:40:12 -08004968sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4969 return mRecordTrack->getCblk();
4970}
4971
Eric Laurenta011e352012-03-29 15:51:43 -07004972status_t AudioFlinger::RecordHandle::start(pid_t tid, int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004973 ALOGV("RecordHandle::start()");
Eric Laurenta011e352012-03-29 15:51:43 -07004974 return mRecordTrack->start(tid, (AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975}
4976
4977void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004978 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 mRecordTrack->stop();
4980}
4981
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982status_t AudioFlinger::RecordHandle::onTransact(
4983 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4984{
4985 return BnAudioRecord::onTransact(code, data, reply, flags);
4986}
4987
4988// ----------------------------------------------------------------------------
4989
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4991 AudioStreamIn *input,
4992 uint32_t sampleRate,
4993 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004994 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004995 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004996 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004997 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4998 // mRsmpInIndex and mInputBytes set by readInputParameters()
4999 mReqChannelCount(popcount(channels)),
5000 mReqSampleRate(sampleRate)
5001 // mBytesRead is only meaningful while active, and so is cleared in start()
5002 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003{
Glenn Kasten480b4682012-02-28 12:30:08 -08005004 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005005
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 readInputParameters();
5007}
5008
5009
5010AudioFlinger::RecordThread::~RecordThread()
5011{
5012 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005013 delete mResampler;
5014 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015}
5016
5017void AudioFlinger::RecordThread::onFirstRef()
5018{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005019 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020}
5021
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005022status_t AudioFlinger::RecordThread::readyToRun()
5023{
5024 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005025 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005026 return status;
5027}
5028
Mathias Agopian65ab4712010-07-14 17:59:35 -07005029bool AudioFlinger::RecordThread::threadLoop()
5030{
5031 AudioBufferProvider::Buffer buffer;
5032 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005033 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034
Eric Laurent44d98482010-09-30 16:12:31 -07005035 nsecs_t lastWarning = 0;
5036
Eric Laurentfeb0db62011-07-22 09:04:31 -07005037 acquireWakeLock();
5038
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 // start recording
5040 while (!exitPending()) {
5041
5042 processConfigEvents();
5043
5044 { // scope for mLock
5045 Mutex::Autolock _l(mLock);
5046 checkForNewParameters_l();
5047 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5048 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005049 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 mStandby = true;
5051 }
5052
5053 if (exitPending()) break;
5054
Eric Laurentfeb0db62011-07-22 09:04:31 -07005055 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005056 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005057 // go to sleep
5058 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005059 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005060 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 continue;
5062 }
5063 if (mActiveTrack != 0) {
5064 if (mActiveTrack->mState == TrackBase::PAUSING) {
5065 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005066 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 mStandby = true;
5068 }
5069 mActiveTrack.clear();
5070 mStartStopCond.broadcast();
5071 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5072 if (mReqChannelCount != mActiveTrack->channelCount()) {
5073 mActiveTrack.clear();
5074 mStartStopCond.broadcast();
5075 } else if (mBytesRead != 0) {
5076 // record start succeeds only if first read from audio input
5077 // succeeds
5078 if (mBytesRead > 0) {
5079 mActiveTrack->mState = TrackBase::ACTIVE;
5080 } else {
5081 mActiveTrack.clear();
5082 }
5083 mStartStopCond.broadcast();
5084 }
5085 mStandby = false;
5086 }
5087 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005088 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089 }
5090
5091 if (mActiveTrack != 0) {
5092 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5093 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005094 unlockEffectChains(effectChains);
5095 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005096 continue;
5097 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005098 for (size_t i = 0; i < effectChains.size(); i ++) {
5099 effectChains[i]->process_l();
5100 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005101
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005103 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005105 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 // no resampling
5107 while (framesOut) {
5108 size_t framesIn = mFrameCount - mRsmpInIndex;
5109 if (framesIn) {
5110 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5111 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5112 if (framesIn > framesOut)
5113 framesIn = framesOut;
5114 mRsmpInIndex += framesIn;
5115 framesOut -= framesIn;
5116 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005117 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 memcpy(dst, src, framesIn * mFrameSize);
5119 } else {
5120 int16_t *src16 = (int16_t *)src;
5121 int16_t *dst16 = (int16_t *)dst;
5122 if (mChannelCount == 1) {
5123 while (framesIn--) {
5124 *dst16++ = *src16;
5125 *dst16++ = *src16++;
5126 }
5127 } else {
5128 while (framesIn--) {
5129 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5130 src16 += 2;
5131 }
5132 }
5133 }
5134 }
5135 if (framesOut && mFrameCount == mRsmpInIndex) {
5136 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005137 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005138 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005139 framesOut = 0;
5140 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005141 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142 mRsmpInIndex = 0;
5143 }
5144 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005145 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5147 // Force input into standby so that it tries to
5148 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005149 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005150 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 }
5152 mRsmpInIndex = mFrameCount;
5153 framesOut = 0;
5154 buffer.frameCount = 0;
5155 }
5156 }
5157 }
5158 } else {
5159 // resampling
5160
5161 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5162 // alter output frame count as if we were expecting stereo samples
5163 if (mChannelCount == 1 && mReqChannelCount == 1) {
5164 framesOut >>= 1;
5165 }
5166 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5167 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5168 // are 32 bit aligned which should be always true.
5169 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005170 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 // the resampler always outputs stereo samples: do post stereo to mono conversion
5172 int16_t *src = (int16_t *)mRsmpOutBuffer;
5173 int16_t *dst = buffer.i16;
5174 while (framesOut--) {
5175 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5176 src += 2;
5177 }
5178 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005179 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 }
5181
5182 }
Eric Laurenta011e352012-03-29 15:51:43 -07005183 if (mFramestoDrop == 0) {
5184 mActiveTrack->releaseBuffer(&buffer);
5185 } else {
5186 if (mFramestoDrop > 0) {
5187 mFramestoDrop -= buffer.frameCount;
5188 if (mFramestoDrop < 0) {
5189 mFramestoDrop = 0;
5190 }
5191 }
5192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005193 mActiveTrack->overflow();
5194 }
5195 // client isn't retrieving buffers fast enough
5196 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005197 if (!mActiveTrack->setOverflow()) {
5198 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005199 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005200 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005201 lastWarning = now;
5202 }
5203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005204 // Release the processor for a while before asking for a new buffer.
5205 // This will give the application more chance to read from the buffer and
5206 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005207 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005208 }
5209 }
Eric Laurentec437d82011-07-26 20:54:46 -07005210 // enable changes in effect chain
5211 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005212 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005213 }
5214
5215 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005216 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 }
5218 mActiveTrack.clear();
5219
5220 mStartStopCond.broadcast();
5221
Eric Laurentfeb0db62011-07-22 09:04:31 -07005222 releaseWakeLock();
5223
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 return false;
5226}
5227
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005228
5229sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5230 const sp<AudioFlinger::Client>& client,
5231 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005232 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005233 int channelMask,
5234 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005235 int sessionId,
5236 status_t *status)
5237{
5238 sp<RecordTrack> track;
5239 status_t lStatus;
5240
5241 lStatus = initCheck();
5242 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005243 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005244 goto Exit;
5245 }
5246
5247 { // scope for mLock
5248 Mutex::Autolock _l(mLock);
5249
5250 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005251 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005252
Glenn Kasten7378ca52012-01-20 13:44:40 -08005253 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005254 lStatus = NO_MEMORY;
5255 goto Exit;
5256 }
5257
5258 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005259 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5260 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005261 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005262 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5263 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005264 }
5265 lStatus = NO_ERROR;
5266
5267Exit:
5268 if (status) {
5269 *status = lStatus;
5270 }
5271 return track;
5272}
5273
Eric Laurenta011e352012-03-29 15:51:43 -07005274status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5275 pid_t tid, AudioSystem::sync_event_t event,
5276 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005277{
Eric Laurenta011e352012-03-29 15:51:43 -07005278 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005279 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005281
5282 if (event == AudioSystem::SYNC_EVENT_NONE) {
5283 mSyncStartEvent.clear();
5284 mFramestoDrop = 0;
5285 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5286 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5287 triggerSession,
5288 recordTrack->sessionId(),
5289 syncStartEventCallback,
5290 this);
5291 mFramestoDrop = -1;
5292 }
5293
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005295 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296 if (mActiveTrack != 0) {
5297 if (recordTrack != mActiveTrack.get()) {
5298 status = -EBUSY;
5299 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5300 mActiveTrack->mState = TrackBase::ACTIVE;
5301 }
5302 return status;
5303 }
5304
5305 recordTrack->mState = TrackBase::IDLE;
5306 mActiveTrack = recordTrack;
5307 mLock.unlock();
5308 status_t status = AudioSystem::startInput(mId);
5309 mLock.lock();
5310 if (status != NO_ERROR) {
5311 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005312 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313 return status;
5314 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315 mRsmpInIndex = mFrameCount;
5316 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005317 if (mResampler != NULL) {
5318 mResampler->reset();
5319 }
5320 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005322 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323 mWaitWorkCV.signal();
5324 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005325 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 mActiveTrack.clear();
5327 status = INVALID_OPERATION;
5328 goto startError;
5329 }
5330 mStartStopCond.wait(mLock);
5331 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005332 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 status = BAD_VALUE;
5334 goto startError;
5335 }
Steve Block3856b092011-10-20 11:56:00 +01005336 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 return status;
5338 }
5339startError:
5340 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005341 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 return status;
5343}
5344
Eric Laurenta011e352012-03-29 15:51:43 -07005345void AudioFlinger::RecordThread::clearSyncStartEvent()
5346{
5347 if (mSyncStartEvent != 0) {
5348 mSyncStartEvent->cancel();
5349 }
5350 mSyncStartEvent.clear();
5351}
5352
5353void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5354{
5355 sp<SyncEvent> strongEvent = event.promote();
5356
5357 if (strongEvent != 0) {
5358 RecordThread *me = (RecordThread *)strongEvent->cookie();
5359 me->handleSyncStartEvent(strongEvent);
5360 }
5361}
5362
5363void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5364{
5365 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5366 mActiveTrack.get(),
5367 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5368 event->listenerSession());
5369
5370 if (mActiveTrack != 0 &&
5371 event == mSyncStartEvent) {
5372 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5373 // from audio HAL
5374 mFramestoDrop = mFrameCount * 2;
5375 mSyncStartEvent.clear();
5376 }
5377}
5378
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005380 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005381 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005383 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5385 mActiveTrack->mState = TrackBase::PAUSING;
5386 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005387 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 return;
5389 }
5390 mStartStopCond.wait(mLock);
5391 // if we have been restarted, recordTrack == mActiveTrack.get() here
5392 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5393 mLock.unlock();
5394 AudioSystem::stopInput(mId);
5395 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005396 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 }
5398 }
5399 }
5400}
5401
Eric Laurenta011e352012-03-29 15:51:43 -07005402bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5403{
5404 return false;
5405}
5406
5407status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5408{
5409 if (!isValidSyncEvent(event)) {
5410 return BAD_VALUE;
5411 }
5412
5413 Mutex::Autolock _l(mLock);
5414
5415 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5416 mTrack->setSyncEvent(event);
5417 return NO_ERROR;
5418 }
5419 return NAME_NOT_FOUND;
5420}
5421
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5423{
5424 const size_t SIZE = 256;
5425 char buffer[SIZE];
5426 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427
5428 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5429 result.append(buffer);
5430
5431 if (mActiveTrack != 0) {
5432 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005433 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 mActiveTrack->dump(buffer, SIZE);
5435 result.append(buffer);
5436
5437 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5438 result.append(buffer);
5439 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5440 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005441 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 result.append(buffer);
5443 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5444 result.append(buffer);
5445 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5446 result.append(buffer);
5447
5448
5449 } else {
5450 result.append("No record client\n");
5451 }
5452 write(fd, result.string(), result.size());
5453
5454 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005455 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456
5457 return NO_ERROR;
5458}
5459
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005460// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005461status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462{
5463 size_t framesReq = buffer->frameCount;
5464 size_t framesReady = mFrameCount - mRsmpInIndex;
5465 int channelCount;
5466
5467 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005468 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005470 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5472 // Force input into standby so that it tries to
5473 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005474 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005475 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005477 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 buffer->frameCount = 0;
5479 return NOT_ENOUGH_DATA;
5480 }
5481 mRsmpInIndex = 0;
5482 framesReady = mFrameCount;
5483 }
5484
5485 if (framesReq > framesReady) {
5486 framesReq = framesReady;
5487 }
5488
5489 if (mChannelCount == 1 && mReqChannelCount == 2) {
5490 channelCount = 1;
5491 } else {
5492 channelCount = 2;
5493 }
5494 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5495 buffer->frameCount = framesReq;
5496 return NO_ERROR;
5497}
5498
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005499// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5501{
5502 mRsmpInIndex += buffer->frameCount;
5503 buffer->frameCount = 0;
5504}
5505
5506bool AudioFlinger::RecordThread::checkForNewParameters_l()
5507{
5508 bool reconfig = false;
5509
5510 while (!mNewParameters.isEmpty()) {
5511 status_t status = NO_ERROR;
5512 String8 keyValuePair = mNewParameters[0];
5513 AudioParameter param = AudioParameter(keyValuePair);
5514 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005515 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 int reqSamplingRate = mReqSampleRate;
5517 int reqChannelCount = mReqChannelCount;
5518
5519 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5520 reqSamplingRate = value;
5521 reconfig = true;
5522 }
5523 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005524 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 reconfig = true;
5526 }
5527 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005528 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 reconfig = true;
5530 }
5531 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5532 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005533 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 // if frame count is changed after track creation
5535 if (mActiveTrack != 0) {
5536 status = INVALID_OPERATION;
5537 } else {
5538 reconfig = true;
5539 }
5540 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005541 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5542 // forward device change to effects that have requested to be
5543 // aware of attached audio device.
5544 for (size_t i = 0; i < mEffectChains.size(); i++) {
5545 mEffectChains[i]->setDevice_l(value);
5546 }
5547 // store input device and output device but do not forward output device to audio HAL.
5548 // Note that status is ignored by the caller for output device
5549 // (see AudioFlinger::setParameters()
5550 if (value & AUDIO_DEVICE_OUT_ALL) {
5551 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5552 status = BAD_VALUE;
5553 } else {
5554 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005555 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5556 if (mTrack != NULL) {
5557 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005558 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005559 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5560 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5561 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005562 }
5563 mDevice |= (uint32_t)value;
5564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005566 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005568 mInput->stream->common.standby(&mInput->stream->common);
5569 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5570 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 }
5572 if (reconfig) {
5573 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005574 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005575 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005576 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005577 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5578 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 status = NO_ERROR;
5580 }
5581 if (status == NO_ERROR) {
5582 readInputParameters();
5583 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5584 }
5585 }
5586 }
5587
5588 mNewParameters.removeAt(0);
5589
5590 mParamStatus = status;
5591 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005592 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5593 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005594 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 return reconfig;
5597}
5598
5599String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5600{
Dima Zavinfce7a472011-04-19 22:30:36 -07005601 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005602 String8 out_s8 = String8();
5603
5604 Mutex::Autolock _l(mLock);
5605 if (initCheck() != NO_ERROR) {
5606 return out_s8;
5607 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005608
Dima Zavin799a70e2011-04-18 16:57:27 -07005609 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005610 out_s8 = String8(s);
5611 free(s);
5612 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613}
5614
5615void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5616 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005617 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618
5619 switch (event) {
5620 case AudioSystem::INPUT_OPENED:
5621 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005622 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 desc.samplingRate = mSampleRate;
5624 desc.format = mFormat;
5625 desc.frameCount = mFrameCount;
5626 desc.latency = 0;
5627 param2 = &desc;
5628 break;
5629
5630 case AudioSystem::INPUT_CLOSED:
5631 default:
5632 break;
5633 }
5634 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5635}
5636
5637void AudioFlinger::RecordThread::readInputParameters()
5638{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005639 delete mRsmpInBuffer;
5640 // mRsmpInBuffer is always assigned a new[] below
5641 delete mRsmpOutBuffer;
5642 mRsmpOutBuffer = NULL;
5643 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005644 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645
Dima Zavin799a70e2011-04-18 16:57:27 -07005646 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005647 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5648 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005649 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005650 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005651 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 mFrameCount = mInputBytes / mFrameSize;
5653 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5654
Glenn Kasten53d76db2012-03-08 12:32:47 -08005655 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 {
5657 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005658 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5659 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 if (mChannelCount == 1 && mReqChannelCount == 2) {
5661 channelCount = 1;
5662 } else {
5663 channelCount = 2;
5664 }
5665 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5666 mResampler->setSampleRate(mSampleRate);
5667 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5668 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5669
5670 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5671 if (mChannelCount == 1 && mReqChannelCount == 1) {
5672 mFrameCount >>= 1;
5673 }
5674
5675 }
5676 mRsmpInIndex = mFrameCount;
5677}
5678
5679unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5680{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005681 Mutex::Autolock _l(mLock);
5682 if (initCheck() != NO_ERROR) {
5683 return 0;
5684 }
5685
Dima Zavin799a70e2011-04-18 16:57:27 -07005686 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687}
5688
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005689uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5690{
5691 Mutex::Autolock _l(mLock);
5692 uint32_t result = 0;
5693 if (getEffectChain_l(sessionId) != 0) {
5694 result = EFFECT_SESSION;
5695 }
5696
5697 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5698 result |= TRACK_SESSION;
5699 }
5700
5701 return result;
5702}
5703
Eric Laurent59bd0da2011-08-01 09:52:20 -07005704AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5705{
5706 Mutex::Autolock _l(mLock);
5707 return mTrack;
5708}
5709
Glenn Kastenaed850d2012-01-26 09:46:34 -08005710AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005711{
5712 Mutex::Autolock _l(mLock);
5713 return mInput;
5714}
5715
5716AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5717{
5718 Mutex::Autolock _l(mLock);
5719 AudioStreamIn *input = mInput;
5720 mInput = NULL;
5721 return input;
5722}
5723
5724// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005725audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005726{
5727 if (mInput == NULL) {
5728 return NULL;
5729 }
5730 return &mInput->stream->common;
5731}
5732
5733
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734// ----------------------------------------------------------------------------
5735
Eric Laurenta4c5a552012-03-29 10:12:40 -07005736audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5737{
5738 if (!settingsAllowed()) {
5739 return 0;
5740 }
5741 Mutex::Autolock _l(mLock);
5742 return loadHwModule_l(name);
5743}
5744
5745// loadHwModule_l() must be called with AudioFlinger::mLock held
5746audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5747{
5748 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5749 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5750 ALOGW("loadHwModule() module %s already loaded", name);
5751 return mAudioHwDevs.keyAt(i);
5752 }
5753 }
5754
Eric Laurenta4c5a552012-03-29 10:12:40 -07005755 audio_hw_device_t *dev;
5756
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005757 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005758 if (rc) {
5759 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5760 return 0;
5761 }
5762
5763 mHardwareStatus = AUDIO_HW_INIT;
5764 rc = dev->init_check(dev);
5765 mHardwareStatus = AUDIO_HW_IDLE;
5766 if (rc) {
5767 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5768 return 0;
5769 }
5770
5771 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5772 (NULL != dev->set_master_volume)) {
5773 AutoMutex lock(mHardwareLock);
5774 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5775 dev->set_master_volume(dev, mMasterVolume);
5776 mHardwareStatus = AUDIO_HW_IDLE;
5777 }
5778
5779 audio_module_handle_t handle = nextUniqueId();
5780 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5781
5782 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005783 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005784
5785 return handle;
5786
5787}
5788
5789audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5790 audio_devices_t *pDevices,
5791 uint32_t *pSamplingRate,
5792 audio_format_t *pFormat,
5793 audio_channel_mask_t *pChannelMask,
5794 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005795 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796{
5797 status_t status;
5798 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005799 struct audio_config config = {
5800 sample_rate: pSamplingRate ? *pSamplingRate : 0,
5801 channel_mask: pChannelMask ? *pChannelMask : 0,
5802 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
5803 };
5804 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07005805 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806
Eric Laurenta4c5a552012-03-29 10:12:40 -07005807 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5808 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07005809 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005810 config.sample_rate,
5811 config.format,
5812 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005813 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814
5815 if (pDevices == NULL || *pDevices == 0) {
5816 return 0;
5817 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005818
Mathias Agopian65ab4712010-07-14 17:59:35 -07005819 Mutex::Autolock _l(mLock);
5820
Eric Laurenta4c5a552012-03-29 10:12:40 -07005821 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005822 if (outHwDev == NULL)
5823 return 0;
5824
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005825 audio_io_handle_t id = nextUniqueId();
5826
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005827 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005828
5829 status = outHwDev->open_output_stream(outHwDev,
5830 id,
5831 *pDevices,
5832 (audio_output_flags_t)flags,
5833 &config,
5834 &outStream);
5835
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005836 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005837 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005838 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005839 config.sample_rate,
5840 config.format,
5841 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 status);
5843
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005844 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005845 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07005846
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005847 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005848 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
5849 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005851 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852 } else {
5853 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005854 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855 }
5856 mPlaybackThreads.add(id, thread);
5857
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005858 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
5859 if (pFormat != NULL) *pFormat = config.format;
5860 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08005861 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862
5863 // notify client processes of the new output creation
5864 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005865
5866 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005867 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07005868 ALOGI("Using module %d has the primary audio interface", module);
5869 mPrimaryHardwareDev = outHwDev;
5870
5871 AutoMutex lock(mHardwareLock);
5872 mHardwareStatus = AUDIO_HW_SET_MODE;
5873 outHwDev->set_mode(outHwDev, mMode);
5874
5875 // Determine the level of master volume support the primary audio HAL has,
5876 // and set the initial master volume at the same time.
5877 float initialVolume = 1.0;
5878 mMasterVolumeSupportLvl = MVS_NONE;
5879
5880 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5881 if ((NULL != outHwDev->get_master_volume) &&
5882 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5883 mMasterVolumeSupportLvl = MVS_FULL;
5884 } else {
5885 mMasterVolumeSupportLvl = MVS_SETONLY;
5886 initialVolume = 1.0;
5887 }
5888
5889 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5890 if ((NULL == outHwDev->set_master_volume) ||
5891 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5892 mMasterVolumeSupportLvl = MVS_NONE;
5893 }
5894 // now that we have a primary device, initialize master volume on other devices
5895 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5896 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5897
5898 if ((dev != mPrimaryHardwareDev) &&
5899 (NULL != dev->set_master_volume)) {
5900 dev->set_master_volume(dev, initialVolume);
5901 }
5902 }
5903 mHardwareStatus = AUDIO_HW_IDLE;
5904 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5905 ? initialVolume
5906 : 1.0;
5907 mMasterVolume = initialVolume;
5908 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909 return id;
5910 }
5911
5912 return 0;
5913}
5914
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005915audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5916 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917{
5918 Mutex::Autolock _l(mLock);
5919 MixerThread *thread1 = checkMixerThread_l(output1);
5920 MixerThread *thread2 = checkMixerThread_l(output2);
5921
5922 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005923 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 return 0;
5925 }
5926
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005927 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5929 thread->addOutputTrack(thread2);
5930 mPlaybackThreads.add(id, thread);
5931 // notify client processes of the new output creation
5932 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5933 return id;
5934}
5935
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005936status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937{
5938 // keep strong reference on the playback thread so that
5939 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005940 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941 {
5942 Mutex::Autolock _l(mLock);
5943 thread = checkPlaybackThread_l(output);
5944 if (thread == NULL) {
5945 return BAD_VALUE;
5946 }
5947
Steve Block3856b092011-10-20 11:56:00 +01005948 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005950 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005952 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5954 dupThread->removeOutputTrack((MixerThread *)thread.get());
5955 }
5956 }
5957 }
Glenn Kastena1117922012-01-26 10:53:32 -08005958 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 mPlaybackThreads.removeItem(output);
5960 }
5961 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005962 // The thread entity (active unit of execution) is no longer running here,
5963 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005965 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005966 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005967 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005968 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005969 out->hwDev->close_output_stream(out->hwDev, out->stream);
5970 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 }
5972 return NO_ERROR;
5973}
5974
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005975status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976{
5977 Mutex::Autolock _l(mLock);
5978 PlaybackThread *thread = checkPlaybackThread_l(output);
5979
5980 if (thread == NULL) {
5981 return BAD_VALUE;
5982 }
5983
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 thread->suspend();
5986
5987 return NO_ERROR;
5988}
5989
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005990status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991{
5992 Mutex::Autolock _l(mLock);
5993 PlaybackThread *thread = checkPlaybackThread_l(output);
5994
5995 if (thread == NULL) {
5996 return BAD_VALUE;
5997 }
5998
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000
6001 thread->restore();
6002
6003 return NO_ERROR;
6004}
6005
Eric Laurenta4c5a552012-03-29 10:12:40 -07006006audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6007 audio_devices_t *pDevices,
6008 uint32_t *pSamplingRate,
6009 audio_format_t *pFormat,
6010 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011{
6012 status_t status;
6013 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006014 struct audio_config config = {
6015 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6016 channel_mask: pChannelMask ? *pChannelMask : 0,
6017 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6018 };
6019 uint32_t reqSamplingRate = config.sample_rate;
6020 audio_format_t reqFormat = config.format;
6021 audio_channel_mask_t reqChannels = config.channel_mask;
6022 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006023 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024
6025 if (pDevices == NULL || *pDevices == 0) {
6026 return 0;
6027 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006028
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 Mutex::Autolock _l(mLock);
6030
Eric Laurenta4c5a552012-03-29 10:12:40 -07006031 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006032 if (inHwDev == NULL)
6033 return 0;
6034
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006035 audio_io_handle_t id = nextUniqueId();
6036
6037 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006038 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006039 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006040 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006041 config.sample_rate,
6042 config.format,
6043 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 status);
6045
6046 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6047 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6048 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006049 if (status == BAD_VALUE &&
6050 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6051 (config.sample_rate <= 2 * reqSamplingRate) &&
6052 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006053 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006054 inStream = NULL;
6055 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 }
6057
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006058 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006059 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6060
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 // Start record thread
6062 // RecorThread require both input and output device indication to forward to audio
6063 // pre processing modules
6064 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6065 thread = new RecordThread(this,
6066 input,
6067 reqSamplingRate,
6068 reqChannels,
6069 id,
6070 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006072 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006073 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006074 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006075 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076
Dima Zavin799a70e2011-04-18 16:57:27 -07006077 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078
6079 // notify client processes of the new input creation
6080 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6081 return id;
6082 }
6083
6084 return 0;
6085}
6086
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006087status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088{
6089 // keep strong reference on the record thread so that
6090 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006091 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 {
6093 Mutex::Autolock _l(mLock);
6094 thread = checkRecordThread_l(input);
6095 if (thread == NULL) {
6096 return BAD_VALUE;
6097 }
6098
Steve Block3856b092011-10-20 11:56:00 +01006099 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006100 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006101 mRecordThreads.removeItem(input);
6102 }
6103 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006104 // The thread entity (active unit of execution) is no longer running here,
6105 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006107 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006108 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006109 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006110 in->hwDev->close_input_stream(in->hwDev, in->stream);
6111 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112
6113 return NO_ERROR;
6114}
6115
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006116status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117{
6118 Mutex::Autolock _l(mLock);
6119 MixerThread *dstThread = checkMixerThread_l(output);
6120 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006121 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 return BAD_VALUE;
6123 }
6124
Steve Block3856b092011-10-20 11:56:00 +01006125 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6127
6128 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6129 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006130 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 MixerThread *srcThread = (MixerThread *)thread;
6132 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 }
Eric Laurentde070132010-07-13 04:45:46 -07006134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135
6136 return NO_ERROR;
6137}
6138
6139
6140int AudioFlinger::newAudioSessionId()
6141{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143}
6144
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006145void AudioFlinger::acquireAudioSessionId(int audioSession)
6146{
6147 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006148 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006149 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006150 size_t num = mAudioSessionRefs.size();
6151 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006152 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006153 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6154 ref->mCnt++;
6155 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006156 return;
6157 }
6158 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006159 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6160 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006161}
6162
6163void AudioFlinger::releaseAudioSessionId(int audioSession)
6164{
6165 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006166 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006168 size_t num = mAudioSessionRefs.size();
6169 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006170 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006171 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6172 ref->mCnt--;
6173 ALOGV(" decremented refcount to %d", ref->mCnt);
6174 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006175 mAudioSessionRefs.removeAt(i);
6176 delete ref;
6177 purgeStaleEffects_l();
6178 }
6179 return;
6180 }
6181 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006182 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006183}
6184
6185void AudioFlinger::purgeStaleEffects_l() {
6186
Steve Block3856b092011-10-20 11:56:00 +01006187 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006188
6189 Vector< sp<EffectChain> > chains;
6190
6191 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6192 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6193 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6194 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006195 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6196 chains.push(ec);
6197 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006198 }
6199 }
6200 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6201 sp<RecordThread> t = mRecordThreads.valueAt(i);
6202 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6203 sp<EffectChain> ec = t->mEffectChains[j];
6204 chains.push(ec);
6205 }
6206 }
6207
6208 for (size_t i = 0; i < chains.size(); i++) {
6209 sp<EffectChain> ec = chains[i];
6210 int sessionid = ec->sessionId();
6211 sp<ThreadBase> t = ec->mThread.promote();
6212 if (t == 0) {
6213 continue;
6214 }
6215 size_t numsessionrefs = mAudioSessionRefs.size();
6216 bool found = false;
6217 for (size_t k = 0; k < numsessionrefs; k++) {
6218 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006219 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006220 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006221 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006222 found = true;
6223 break;
6224 }
6225 }
6226 if (!found) {
6227 // remove all effects from the chain
6228 while (ec->mEffects.size()) {
6229 sp<EffectModule> effect = ec->mEffects[0];
6230 effect->unPin();
6231 Mutex::Autolock _l (t->mLock);
6232 t->removeEffect_l(effect);
6233 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6234 sp<EffectHandle> handle = effect->mHandles[j].promote();
6235 if (handle != 0) {
6236 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006237 if (handle->mHasControl && handle->mEnabled) {
6238 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6239 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006240 }
6241 }
6242 AudioSystem::unregisterEffect(effect->id());
6243 }
6244 }
6245 }
6246 return;
6247}
6248
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006250AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251{
Glenn Kastena1117922012-01-26 10:53:32 -08006252 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253}
6254
6255// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006256AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257{
6258 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006259 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260}
6261
6262// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006263AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264{
Glenn Kastena1117922012-01-26 10:53:32 -08006265 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266}
6267
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006268uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006270 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271}
6272
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006273AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006274{
6275 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6276 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006277 AudioStreamOut *output = thread->getOutput();
6278 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006279 return thread;
6280 }
6281 }
6282 return NULL;
6283}
6284
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006285uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006286{
6287 PlaybackThread *thread = primaryPlaybackThread_l();
6288
6289 if (thread == NULL) {
6290 return 0;
6291 }
6292
6293 return thread->device();
6294}
6295
Eric Laurenta011e352012-03-29 15:51:43 -07006296sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6297 int triggerSession,
6298 int listenerSession,
6299 sync_event_callback_t callBack,
6300 void *cookie)
6301{
6302 Mutex::Autolock _l(mLock);
6303
6304 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6305 status_t playStatus = NAME_NOT_FOUND;
6306 status_t recStatus = NAME_NOT_FOUND;
6307 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6308 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6309 if (playStatus == NO_ERROR) {
6310 return event;
6311 }
6312 }
6313 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6314 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6315 if (recStatus == NO_ERROR) {
6316 return event;
6317 }
6318 }
6319 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6320 mPendingSyncEvents.add(event);
6321 } else {
6322 ALOGV("createSyncEvent() invalid event %d", event->type());
6323 event.clear();
6324 }
6325 return event;
6326}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006327
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328// ----------------------------------------------------------------------------
6329// Effect management
6330// ----------------------------------------------------------------------------
6331
6332
Glenn Kastenf587ba52012-01-26 16:25:10 -08006333status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334{
6335 Mutex::Autolock _l(mLock);
6336 return EffectQueryNumberEffects(numEffects);
6337}
6338
Glenn Kastenf587ba52012-01-26 16:25:10 -08006339status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340{
6341 Mutex::Autolock _l(mLock);
6342 return EffectQueryEffect(index, descriptor);
6343}
6344
Glenn Kasten5e92a782012-01-30 07:40:52 -08006345status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006346 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347{
6348 Mutex::Autolock _l(mLock);
6349 return EffectGetDescriptor(pUuid, descriptor);
6350}
6351
6352
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6354 effect_descriptor_t *pDesc,
6355 const sp<IEffectClient>& effectClient,
6356 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006357 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 int sessionId,
6359 status_t *status,
6360 int *id,
6361 int *enabled)
6362{
6363 status_t lStatus = NO_ERROR;
6364 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006367 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006368 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369
6370 if (pDesc == NULL) {
6371 lStatus = BAD_VALUE;
6372 goto Exit;
6373 }
6374
Eric Laurent84e9a102010-09-23 16:10:16 -07006375 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006376 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006377 lStatus = PERMISSION_DENIED;
6378 goto Exit;
6379 }
6380
Dima Zavinfce7a472011-04-19 22:30:36 -07006381 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006382 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006383 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006384 lStatus = PERMISSION_DENIED;
6385 goto Exit;
6386 }
6387
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006388 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006389 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006390 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006391 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006392 lStatus = BAD_VALUE;
6393 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006394 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006395 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006396 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006397 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006398 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006399 }
6400 }
6401
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 {
6403 Mutex::Autolock _l(mLock);
6404
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405
6406 if (!EffectIsNullUuid(&pDesc->uuid)) {
6407 // if uuid is specified, request effect descriptor
6408 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6409 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006410 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411 goto Exit;
6412 }
6413 } else {
6414 // if uuid is not specified, look for an available implementation
6415 // of the required type in effect factory
6416 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006417 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 lStatus = BAD_VALUE;
6419 goto Exit;
6420 }
6421 uint32_t numEffects = 0;
6422 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006423 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 bool found = false;
6425
6426 lStatus = EffectQueryNumberEffects(&numEffects);
6427 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006428 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 goto Exit;
6430 }
6431 for (uint32_t i = 0; i < numEffects; i++) {
6432 lStatus = EffectQueryEffect(i, &desc);
6433 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006434 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 continue;
6436 }
6437 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6438 // If matching type found save effect descriptor. If the session is
6439 // 0 and the effect is not auxiliary, continue enumeration in case
6440 // an auxiliary version of this effect type is available
6441 found = true;
6442 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006443 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6445 break;
6446 }
6447 }
6448 }
6449 if (!found) {
6450 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006451 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 goto Exit;
6453 }
6454 // For same effect type, chose auxiliary version over insert version if
6455 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006456 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6458 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6459 }
6460 }
6461
6462 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006463 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6465 lStatus = INVALID_OPERATION;
6466 goto Exit;
6467 }
6468
Eric Laurent59255e42011-07-27 19:49:51 -07006469 // check recording permission for visualizer
6470 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6471 !recordingAllowed()) {
6472 lStatus = PERMISSION_DENIED;
6473 goto Exit;
6474 }
6475
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 // return effect descriptor
6477 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6478
6479 // If output is not specified try to find a matching audio session ID in one of the
6480 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006481 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6482 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006483 // Note: io is never 0 when creating an effect on an input
6484 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006485 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006486 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6487 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006488 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006489 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006492 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006493 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6494 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6495 io = mRecordThreads.keyAt(i);
6496 break;
6497 }
6498 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006499 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006500 // If no output thread contains the requested session ID, default to
6501 // first output. The effect chain will be moved to the correct output
6502 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006503 if (io == 0 && mPlaybackThreads.size()) {
6504 io = mPlaybackThreads.keyAt(0);
6505 }
Steve Block3856b092011-10-20 11:56:00 +01006506 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006507 }
6508 ThreadBase *thread = checkRecordThread_l(io);
6509 if (thread == NULL) {
6510 thread = checkPlaybackThread_l(io);
6511 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006512 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006513 lStatus = BAD_VALUE;
6514 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006517
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006518 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006520 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006521 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6522 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 if (handle != 0 && id != NULL) {
6524 *id = handle->id();
6525 }
6526 }
6527
6528Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006529 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 *status = lStatus;
6531 }
6532 return handle;
6533}
6534
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006535status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6536 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006537{
Steve Block3856b092011-10-20 11:56:00 +01006538 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006539 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006540 Mutex::Autolock _l(mLock);
6541 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006542 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006543 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544 }
Eric Laurentde070132010-07-13 04:45:46 -07006545 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6546 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006547 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006548 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 }
Eric Laurentde070132010-07-13 04:45:46 -07006550 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6551 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006552 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006553 return BAD_VALUE;
6554 }
6555
6556 Mutex::Autolock _dl(dstThread->mLock);
6557 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006558 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006559
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 return NO_ERROR;
6561}
6562
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006563// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006564status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006565 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006566 AudioFlinger::PlaybackThread *dstThread,
6567 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006568{
Steve Block3856b092011-10-20 11:56:00 +01006569 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006570 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006571
Eric Laurent59255e42011-07-27 19:49:51 -07006572 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006573 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006574 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006575 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006576 return INVALID_OPERATION;
6577 }
6578
Eric Laurent39e94f82010-07-28 01:32:47 -07006579 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006580 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006581 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006582 // removed.
6583 srcThread->removeEffectChain_l(chain);
6584
6585 // transfer all effects one by one so that new effect chain is created on new thread with
6586 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006587 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006588 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006589 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006590 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6591 while (effect != 0) {
6592 srcThread->removeEffect_l(effect);
6593 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006594 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6595 if (effect->state() == EffectModule::ACTIVE ||
6596 effect->state() == EffectModule::STOPPING) {
6597 effect->start();
6598 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006599 // if the move request is not received from audio policy manager, the effect must be
6600 // re-registered with the new strategy and output
6601 if (dstChain == 0) {
6602 dstChain = effect->chain().promote();
6603 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006604 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006605 srcThread->addEffect_l(effect);
6606 return NO_INIT;
6607 }
6608 strategy = dstChain->strategy();
6609 }
6610 if (reRegister) {
6611 AudioSystem::unregisterEffect(effect->id());
6612 AudioSystem::registerEffect(&effect->desc(),
6613 dstOutput,
6614 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006615 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006616 effect->id());
6617 }
Eric Laurentde070132010-07-13 04:45:46 -07006618 effect = chain->getEffectFromId_l(0);
6619 }
6620
6621 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622}
6623
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006624
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006626sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627 const sp<AudioFlinger::Client>& client,
6628 const sp<IEffectClient>& effectClient,
6629 int32_t priority,
6630 int sessionId,
6631 effect_descriptor_t *desc,
6632 int *enabled,
6633 status_t *status
6634 )
6635{
6636 sp<EffectModule> effect;
6637 sp<EffectHandle> handle;
6638 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006640 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641 bool effectCreated = false;
6642 bool effectRegistered = false;
6643
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006644 lStatus = initCheck();
6645 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006646 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006647 goto Exit;
6648 }
6649
6650 // Do not allow effects with session ID 0 on direct output or duplicating threads
6651 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006652 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006653 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006654 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 lStatus = BAD_VALUE;
6656 goto Exit;
6657 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006658 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006659 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006660 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006661 desc->name, desc->flags, mType);
6662 lStatus = BAD_VALUE;
6663 goto Exit;
6664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665
Steve Block3856b092011-10-20 11:56:00 +01006666 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667
6668 { // scope for mLock
6669 Mutex::Autolock _l(mLock);
6670
6671 // check for existing effect chain with the requested audio session
6672 chain = getEffectChain_l(sessionId);
6673 if (chain == 0) {
6674 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006675 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006676 chain = new EffectChain(this, sessionId);
6677 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006678 chain->setStrategy(getStrategyForSession_l(sessionId));
6679 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006681 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682 }
6683
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006684 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685
6686 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006687 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006689 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 if (lStatus != NO_ERROR) {
6691 goto Exit;
6692 }
6693 effectRegistered = true;
6694 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006695 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 lStatus = effect->status();
6697 if (lStatus != NO_ERROR) {
6698 goto Exit;
6699 }
Eric Laurentcab11242010-07-15 12:50:15 -07006700 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701 if (lStatus != NO_ERROR) {
6702 goto Exit;
6703 }
6704 effectCreated = true;
6705
6706 effect->setDevice(mDevice);
6707 effect->setMode(mAudioFlinger->getMode());
6708 }
6709 // create effect handle and connect it to effect module
6710 handle = new EffectHandle(effect, client, effectClient, priority);
6711 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006712 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 *enabled = (int)effect->isEnabled();
6714 }
6715 }
6716
6717Exit:
6718 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006719 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006721 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722 }
6723 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006724 AudioSystem::unregisterEffect(effect->id());
6725 }
6726 if (chainCreated) {
6727 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728 }
6729 handle.clear();
6730 }
6731
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006732 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733 *status = lStatus;
6734 }
6735 return handle;
6736}
6737
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006738sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6739{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006740 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006741 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006742}
6743
Eric Laurentde070132010-07-13 04:45:46 -07006744// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6745// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006746status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006747{
6748 // check for existing effect chain with the requested audio session
6749 int sessionId = effect->sessionId();
6750 sp<EffectChain> chain = getEffectChain_l(sessionId);
6751 bool chainCreated = false;
6752
6753 if (chain == 0) {
6754 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006755 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006756 chain = new EffectChain(this, sessionId);
6757 addEffectChain_l(chain);
6758 chain->setStrategy(getStrategyForSession_l(sessionId));
6759 chainCreated = true;
6760 }
Steve Block3856b092011-10-20 11:56:00 +01006761 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006762
6763 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006764 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006765 this, effect->desc().name, chain.get());
6766 return BAD_VALUE;
6767 }
6768
6769 status_t status = chain->addEffect_l(effect);
6770 if (status != NO_ERROR) {
6771 if (chainCreated) {
6772 removeEffectChain_l(chain);
6773 }
6774 return status;
6775 }
6776
6777 effect->setDevice(mDevice);
6778 effect->setMode(mAudioFlinger->getMode());
6779 return NO_ERROR;
6780}
6781
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006782void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006783
Steve Block3856b092011-10-20 11:56:00 +01006784 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006786 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6787 detachAuxEffect_l(effect->id());
6788 }
6789
6790 sp<EffectChain> chain = effect->chain().promote();
6791 if (chain != 0) {
6792 // remove effect chain if removing last effect
6793 if (chain->removeEffect_l(effect) == 0) {
6794 removeEffectChain_l(chain);
6795 }
6796 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006797 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006798 }
6799}
6800
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006801void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006802 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006803{
6804 effectChains = mEffectChains;
6805 for (size_t i = 0; i < mEffectChains.size(); i++) {
6806 mEffectChains[i]->lock();
6807 }
6808}
6809
6810void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006811 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006812{
6813 for (size_t i = 0; i < effectChains.size(); i++) {
6814 effectChains[i]->unlock();
6815 }
6816}
6817
6818sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6819{
6820 Mutex::Autolock _l(mLock);
6821 return getEffectChain_l(sessionId);
6822}
6823
6824sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6825{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006826 size_t size = mEffectChains.size();
6827 for (size_t i = 0; i < size; i++) {
6828 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006829 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006830 }
6831 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006832 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006833}
6834
Glenn Kastenf78aee72012-01-04 11:00:47 -08006835void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006836{
6837 Mutex::Autolock _l(mLock);
6838 size_t size = mEffectChains.size();
6839 for (size_t i = 0; i < size; i++) {
6840 mEffectChains[i]->setMode_l(mode);
6841 }
6842}
6843
6844void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006845 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006846 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006847
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006849 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 // delete the effect module if removing last handle on it
6851 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006852 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006853 removeEffect_l(effect);
6854 AudioSystem::unregisterEffect(effect->id());
6855 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856 }
6857}
6858
6859status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6860{
6861 int session = chain->sessionId();
6862 int16_t *buffer = mMixBuffer;
6863 bool ownsBuffer = false;
6864
Steve Block3856b092011-10-20 11:56:00 +01006865 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 if (session > 0) {
6867 // Only one effect chain can be present in direct output thread and it uses
6868 // the mix buffer as input
6869 if (mType != DIRECT) {
6870 size_t numSamples = mFrameCount * mChannelCount;
6871 buffer = new int16_t[numSamples];
6872 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006873 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874 ownsBuffer = true;
6875 }
6876
6877 // Attach all tracks with same session ID to this chain.
6878 for (size_t i = 0; i < mTracks.size(); ++i) {
6879 sp<Track> track = mTracks[i];
6880 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006881 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006883 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884 }
6885 }
6886
6887 // indicate all active tracks in the chain
6888 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6889 sp<Track> track = mActiveTracks[i].promote();
6890 if (track == 0) continue;
6891 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006892 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006893 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 }
6895 }
6896 }
6897
6898 chain->setInBuffer(buffer, ownsBuffer);
6899 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006900 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006901 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006902 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6903 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006905 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6906 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006907 // Effect chain for other sessions are inserted at beginning of effect
6908 // chains list to be processed before output mix effects. Relative order between other
6909 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 size_t size = mEffectChains.size();
6911 size_t i = 0;
6912 for (i = 0; i < size; i++) {
6913 if (mEffectChains[i]->sessionId() < session) break;
6914 }
6915 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006916 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917
6918 return NO_ERROR;
6919}
6920
6921size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6922{
6923 int session = chain->sessionId();
6924
Steve Block3856b092011-10-20 11:56:00 +01006925 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926
6927 for (size_t i = 0; i < mEffectChains.size(); i++) {
6928 if (chain == mEffectChains[i]) {
6929 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006930 // detach all active tracks from the chain
6931 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6932 sp<Track> track = mActiveTracks[i].promote();
6933 if (track == 0) continue;
6934 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006935 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006936 chain.get(), session);
6937 chain->decActiveTrackCnt();
6938 }
6939 }
6940
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 // detach all tracks with same session ID from this chain
6942 for (size_t i = 0; i < mTracks.size(); ++i) {
6943 sp<Track> track = mTracks[i];
6944 if (session == track->sessionId()) {
6945 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006946 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947 }
6948 }
Eric Laurentde070132010-07-13 04:45:46 -07006949 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 }
6951 }
6952 return mEffectChains.size();
6953}
6954
Eric Laurentde070132010-07-13 04:45:46 -07006955status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6956 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957{
6958 Mutex::Autolock _l(mLock);
6959 return attachAuxEffect_l(track, EffectId);
6960}
6961
Eric Laurentde070132010-07-13 04:45:46 -07006962status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6963 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964{
6965 status_t status = NO_ERROR;
6966
6967 if (EffectId == 0) {
6968 track->setAuxBuffer(0, NULL);
6969 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006970 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6971 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 if (effect != 0) {
6973 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6974 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6975 } else {
6976 status = INVALID_OPERATION;
6977 }
6978 } else {
6979 status = BAD_VALUE;
6980 }
6981 }
6982 return status;
6983}
6984
6985void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6986{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006987 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 sp<Track> track = mTracks[i];
6989 if (track->auxEffectId() == effectId) {
6990 attachAuxEffect_l(track, 0);
6991 }
6992 }
6993}
6994
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006995status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6996{
6997 // only one chain per input thread
6998 if (mEffectChains.size() != 0) {
6999 return INVALID_OPERATION;
7000 }
Steve Block3856b092011-10-20 11:56:00 +01007001 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007002
7003 chain->setInBuffer(NULL);
7004 chain->setOutBuffer(NULL);
7005
Eric Laurent59255e42011-07-27 19:49:51 -07007006 checkSuspendOnAddEffectChain_l(chain);
7007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007008 mEffectChains.add(chain);
7009
7010 return NO_ERROR;
7011}
7012
7013size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7014{
Steve Block3856b092011-10-20 11:56:00 +01007015 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007016 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007017 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7018 chain.get(), mEffectChains.size(), this);
7019 if (mEffectChains.size() == 1) {
7020 mEffectChains.removeAt(0);
7021 }
7022 return 0;
7023}
7024
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025// ----------------------------------------------------------------------------
7026// EffectModule implementation
7027// ----------------------------------------------------------------------------
7028
7029#undef LOG_TAG
7030#define LOG_TAG "AudioFlinger::EffectModule"
7031
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007032AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033 const wp<AudioFlinger::EffectChain>& chain,
7034 effect_descriptor_t *desc,
7035 int id,
7036 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007037 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007038 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039{
Steve Block3856b092011-10-20 11:56:00 +01007040 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007042 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 return;
7044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045
7046 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7047
7048 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007049 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050
7051 if (mStatus != NO_ERROR) {
7052 return;
7053 }
7054 lStatus = init();
7055 if (lStatus < 0) {
7056 mStatus = lStatus;
7057 goto Error;
7058 }
7059
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007060 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7061 mPinned = true;
7062 }
Steve Block3856b092011-10-20 11:56:00 +01007063 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064 return;
7065Error:
7066 EffectRelease(mEffectInterface);
7067 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007068 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069}
7070
7071AudioFlinger::EffectModule::~EffectModule()
7072{
Steve Block3856b092011-10-20 11:56:00 +01007073 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007075 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7076 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7077 sp<ThreadBase> thread = mThread.promote();
7078 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007079 audio_stream_t *stream = thread->stream();
7080 if (stream != NULL) {
7081 stream->remove_audio_effect(stream, mEffectInterface);
7082 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007083 }
7084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 // release effect engine
7086 EffectRelease(mEffectInterface);
7087 }
7088}
7089
Glenn Kasten435dbe62012-01-30 10:15:48 -08007090status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007091{
7092 status_t status;
7093
7094 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 int priority = handle->priority();
7096 size_t size = mHandles.size();
7097 sp<EffectHandle> h;
7098 size_t i;
7099 for (i = 0; i < size; i++) {
7100 h = mHandles[i].promote();
7101 if (h == 0) continue;
7102 if (h->priority() <= priority) break;
7103 }
7104 // if inserted in first place, move effect control from previous owner to this handle
7105 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007106 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007108 enabled = h->enabled();
7109 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110 }
Eric Laurent59255e42011-07-27 19:49:51 -07007111 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 status = NO_ERROR;
7113 } else {
7114 status = ALREADY_EXISTS;
7115 }
Steve Block3856b092011-10-20 11:56:00 +01007116 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 mHandles.insertAt(handle, i);
7118 return status;
7119}
7120
7121size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7122{
7123 Mutex::Autolock _l(mLock);
7124 size_t size = mHandles.size();
7125 size_t i;
7126 for (i = 0; i < size; i++) {
7127 if (mHandles[i] == handle) break;
7128 }
7129 if (i == size) {
7130 return size;
7131 }
Steve Block3856b092011-10-20 11:56:00 +01007132 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007133
7134 bool enabled = false;
7135 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007136 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007137 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007138 enabled = hdl->enabled();
7139 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 mHandles.removeAt(i);
7141 size = mHandles.size();
7142 // if removed from first place, move effect control from this handle to next in line
7143 if (i == 0 && size != 0) {
7144 sp<EffectHandle> h = mHandles[0].promote();
7145 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007146 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147 }
7148 }
7149
Eric Laurentec437d82011-07-26 20:54:46 -07007150 // Prevent calls to process() and other functions on effect interface from now on.
7151 // The effect engine will be released by the destructor when the last strong reference on
7152 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007153 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007154 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007155 }
7156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 return size;
7158}
7159
Eric Laurent59255e42011-07-27 19:49:51 -07007160sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7161{
7162 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007163 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007164}
7165
Glenn Kasten58123c32012-02-03 10:32:24 -08007166void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007168 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 // keep a strong reference on this EffectModule to avoid calling the
7170 // destructor before we exit
7171 sp<EffectModule> keep(this);
7172 {
7173 sp<ThreadBase> thread = mThread.promote();
7174 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007175 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176 }
7177 }
7178}
7179
7180void AudioFlinger::EffectModule::updateState() {
7181 Mutex::Autolock _l(mLock);
7182
7183 switch (mState) {
7184 case RESTART:
7185 reset_l();
7186 // FALL THROUGH
7187
7188 case STARTING:
7189 // clear auxiliary effect input buffer for next accumulation
7190 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7191 memset(mConfig.inputCfg.buffer.raw,
7192 0,
7193 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7194 }
7195 start_l();
7196 mState = ACTIVE;
7197 break;
7198 case STOPPING:
7199 stop_l();
7200 mDisableWaitCnt = mMaxDisableWaitCnt;
7201 mState = STOPPED;
7202 break;
7203 case STOPPED:
7204 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7205 // turn off sequence.
7206 if (--mDisableWaitCnt == 0) {
7207 reset_l();
7208 mState = IDLE;
7209 }
7210 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007211 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212 break;
7213 }
7214}
7215
7216void AudioFlinger::EffectModule::process()
7217{
7218 Mutex::Autolock _l(mLock);
7219
Eric Laurentec437d82011-07-26 20:54:46 -07007220 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 mConfig.inputCfg.buffer.raw == NULL ||
7222 mConfig.outputCfg.buffer.raw == NULL) {
7223 return;
7224 }
7225
Eric Laurent8f45bd72010-08-31 13:50:07 -07007226 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7228 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007229 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007230 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007231 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232 }
7233
7234 // do the actual processing in the effect engine
7235 int ret = (*mEffectInterface)->process(mEffectInterface,
7236 &mConfig.inputCfg.buffer,
7237 &mConfig.outputCfg.buffer);
7238
7239 // force transition to IDLE state when engine is ready
7240 if (mState == STOPPED && ret == -ENODATA) {
7241 mDisableWaitCnt = 1;
7242 }
7243
7244 // clear auxiliary effect input buffer for next accumulation
7245 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007246 memset(mConfig.inputCfg.buffer.raw, 0,
7247 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248 }
7249 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007250 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7251 // If an insert effect is idle and input buffer is different from output buffer,
7252 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007253 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007254 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007255 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7256 int16_t *in = mConfig.inputCfg.buffer.s16;
7257 int16_t *out = mConfig.outputCfg.buffer.s16;
7258 for (size_t i = 0; i < frameCnt; i++) {
7259 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 }
7262 }
7263}
7264
7265void AudioFlinger::EffectModule::reset_l()
7266{
7267 if (mEffectInterface == NULL) {
7268 return;
7269 }
7270 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7271}
7272
7273status_t AudioFlinger::EffectModule::configure()
7274{
7275 uint32_t channels;
7276 if (mEffectInterface == NULL) {
7277 return NO_INIT;
7278 }
7279
7280 sp<ThreadBase> thread = mThread.promote();
7281 if (thread == 0) {
7282 return DEAD_OBJECT;
7283 }
7284
7285 // TODO: handle configuration of effects replacing track process
7286 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007287 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007289 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290 }
7291
7292 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007293 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 } else {
7295 mConfig.inputCfg.channels = channels;
7296 }
7297 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007298 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7299 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300 mConfig.inputCfg.samplingRate = thread->sampleRate();
7301 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7302 mConfig.inputCfg.bufferProvider.cookie = NULL;
7303 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7304 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7305 mConfig.outputCfg.bufferProvider.cookie = NULL;
7306 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7307 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7308 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7309 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007310 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007311 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312 // - in other sessions:
7313 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7314 // other effect: overwrites output buffer: input buffer == output buffer
7315 // Auxiliary effect:
7316 // accumulates in output buffer: input buffer != output buffer
7317 // Therefore: accumulate <=> input buffer != output buffer
7318 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7319 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7320 } else {
7321 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7322 }
7323 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7324 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7325 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7326 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7327
Steve Block3856b092011-10-20 11:56:00 +01007328 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007329 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7330
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007332 uint32_t size = sizeof(int);
7333 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007334 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007335 sizeof(effect_config_t),
7336 &mConfig,
7337 &size,
7338 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 if (status == 0) {
7340 status = cmdStatus;
7341 }
7342
7343 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7344 (1000 * mConfig.outputCfg.buffer.frameCount);
7345
7346 return status;
7347}
7348
7349status_t AudioFlinger::EffectModule::init()
7350{
7351 Mutex::Autolock _l(mLock);
7352 if (mEffectInterface == NULL) {
7353 return NO_INIT;
7354 }
7355 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007356 uint32_t size = sizeof(status_t);
7357 status_t status = (*mEffectInterface)->command(mEffectInterface,
7358 EFFECT_CMD_INIT,
7359 0,
7360 NULL,
7361 &size,
7362 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 if (status == 0) {
7364 status = cmdStatus;
7365 }
7366 return status;
7367}
7368
Eric Laurentec35a142011-10-05 17:42:25 -07007369status_t AudioFlinger::EffectModule::start()
7370{
7371 Mutex::Autolock _l(mLock);
7372 return start_l();
7373}
7374
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375status_t AudioFlinger::EffectModule::start_l()
7376{
7377 if (mEffectInterface == NULL) {
7378 return NO_INIT;
7379 }
7380 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007381 uint32_t size = sizeof(status_t);
7382 status_t status = (*mEffectInterface)->command(mEffectInterface,
7383 EFFECT_CMD_ENABLE,
7384 0,
7385 NULL,
7386 &size,
7387 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 if (status == 0) {
7389 status = cmdStatus;
7390 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007391 if (status == 0 &&
7392 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7393 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7394 sp<ThreadBase> thread = mThread.promote();
7395 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007396 audio_stream_t *stream = thread->stream();
7397 if (stream != NULL) {
7398 stream->add_audio_effect(stream, mEffectInterface);
7399 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007400 }
7401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 return status;
7403}
7404
Eric Laurentec437d82011-07-26 20:54:46 -07007405status_t AudioFlinger::EffectModule::stop()
7406{
7407 Mutex::Autolock _l(mLock);
7408 return stop_l();
7409}
7410
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411status_t AudioFlinger::EffectModule::stop_l()
7412{
7413 if (mEffectInterface == NULL) {
7414 return NO_INIT;
7415 }
7416 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007417 uint32_t size = sizeof(status_t);
7418 status_t status = (*mEffectInterface)->command(mEffectInterface,
7419 EFFECT_CMD_DISABLE,
7420 0,
7421 NULL,
7422 &size,
7423 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 if (status == 0) {
7425 status = cmdStatus;
7426 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007427 if (status == 0 &&
7428 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7429 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7430 sp<ThreadBase> thread = mThread.promote();
7431 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007432 audio_stream_t *stream = thread->stream();
7433 if (stream != NULL) {
7434 stream->remove_audio_effect(stream, mEffectInterface);
7435 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007436 }
7437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007438 return status;
7439}
7440
Eric Laurent25f43952010-07-28 05:40:18 -07007441status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7442 uint32_t cmdSize,
7443 void *pCmdData,
7444 uint32_t *replySize,
7445 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446{
7447 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007448// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449
Eric Laurentec437d82011-07-26 20:54:46 -07007450 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451 return NO_INIT;
7452 }
Eric Laurent25f43952010-07-28 05:40:18 -07007453 status_t status = (*mEffectInterface)->command(mEffectInterface,
7454 cmdCode,
7455 cmdSize,
7456 pCmdData,
7457 replySize,
7458 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007460 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 for (size_t i = 1; i < mHandles.size(); i++) {
7462 sp<EffectHandle> h = mHandles[i].promote();
7463 if (h != 0) {
7464 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7465 }
7466 }
7467 }
7468 return status;
7469}
7470
7471status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7472{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007473
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007476
7477 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007478 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7479 if (enabled && status != NO_ERROR) {
7480 return status;
7481 }
7482
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 switch (mState) {
7484 // going from disabled to enabled
7485 case IDLE:
7486 mState = STARTING;
7487 break;
7488 case STOPPED:
7489 mState = RESTART;
7490 break;
7491 case STOPPING:
7492 mState = ACTIVE;
7493 break;
7494
7495 // going from enabled to disabled
7496 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007497 mState = STOPPED;
7498 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007499 case STARTING:
7500 mState = IDLE;
7501 break;
7502 case ACTIVE:
7503 mState = STOPPING;
7504 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007505 case DESTROYED:
7506 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 }
7508 for (size_t i = 1; i < mHandles.size(); i++) {
7509 sp<EffectHandle> h = mHandles[i].promote();
7510 if (h != 0) {
7511 h->setEnabled(enabled);
7512 }
7513 }
7514 }
7515 return NO_ERROR;
7516}
7517
Glenn Kastenc59c0042012-02-02 14:06:11 -08007518bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519{
7520 switch (mState) {
7521 case RESTART:
7522 case STARTING:
7523 case ACTIVE:
7524 return true;
7525 case IDLE:
7526 case STOPPING:
7527 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007528 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007529 default:
7530 return false;
7531 }
7532}
7533
Glenn Kastenc59c0042012-02-02 14:06:11 -08007534bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007535{
7536 switch (mState) {
7537 case RESTART:
7538 case ACTIVE:
7539 case STOPPING:
7540 case STOPPED:
7541 return true;
7542 case IDLE:
7543 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007544 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007545 default:
7546 return false;
7547 }
7548}
7549
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7551{
7552 Mutex::Autolock _l(mLock);
7553 status_t status = NO_ERROR;
7554
7555 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7556 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007557 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007558 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7559 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 status_t cmdStatus;
7561 uint32_t volume[2];
7562 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007563 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007564 volume[0] = *left;
7565 volume[1] = *right;
7566 if (controller) {
7567 pVolume = volume;
7568 }
Eric Laurent25f43952010-07-28 05:40:18 -07007569 status = (*mEffectInterface)->command(mEffectInterface,
7570 EFFECT_CMD_SET_VOLUME,
7571 size,
7572 volume,
7573 &size,
7574 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7576 *left = volume[0];
7577 *right = volume[1];
7578 }
7579 }
7580 return status;
7581}
7582
7583status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7584{
7585 Mutex::Autolock _l(mLock);
7586 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007587 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7588 // audio pre processing modules on RecordThread can receive both output and
7589 // input device indication in the same call
7590 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7591 if (dev) {
7592 status_t cmdStatus;
7593 uint32_t size = sizeof(status_t);
7594
7595 status = (*mEffectInterface)->command(mEffectInterface,
7596 EFFECT_CMD_SET_DEVICE,
7597 sizeof(uint32_t),
7598 &dev,
7599 &size,
7600 &cmdStatus);
7601 if (status == NO_ERROR) {
7602 status = cmdStatus;
7603 }
7604 }
7605 dev = device & AUDIO_DEVICE_IN_ALL;
7606 if (dev) {
7607 status_t cmdStatus;
7608 uint32_t size = sizeof(status_t);
7609
7610 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7611 EFFECT_CMD_SET_INPUT_DEVICE,
7612 sizeof(uint32_t),
7613 &dev,
7614 &size,
7615 &cmdStatus);
7616 if (status2 == NO_ERROR) {
7617 status2 = cmdStatus;
7618 }
7619 if (status == NO_ERROR) {
7620 status = status2;
7621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622 }
7623 }
7624 return status;
7625}
7626
Glenn Kastenf78aee72012-01-04 11:00:47 -08007627status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628{
7629 Mutex::Autolock _l(mLock);
7630 status_t status = NO_ERROR;
7631 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007633 uint32_t size = sizeof(status_t);
7634 status = (*mEffectInterface)->command(mEffectInterface,
7635 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007636 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007637 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007638 &size,
7639 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 if (status == NO_ERROR) {
7641 status = cmdStatus;
7642 }
7643 }
7644 return status;
7645}
7646
Eric Laurent59255e42011-07-27 19:49:51 -07007647void AudioFlinger::EffectModule::setSuspended(bool suspended)
7648{
7649 Mutex::Autolock _l(mLock);
7650 mSuspended = suspended;
7651}
Glenn Kastena3a85482012-01-04 11:01:11 -08007652
7653bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007654{
7655 Mutex::Autolock _l(mLock);
7656 return mSuspended;
7657}
7658
Mathias Agopian65ab4712010-07-14 17:59:35 -07007659status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7660{
7661 const size_t SIZE = 256;
7662 char buffer[SIZE];
7663 String8 result;
7664
7665 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7666 result.append(buffer);
7667
7668 bool locked = tryLock(mLock);
7669 // failed to lock - AudioFlinger is probably deadlocked
7670 if (!locked) {
7671 result.append("\t\tCould not lock Fx mutex:\n");
7672 }
7673
7674 result.append("\t\tSession Status State Engine:\n");
7675 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7676 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7677 result.append(buffer);
7678
7679 result.append("\t\tDescriptor:\n");
7680 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7681 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7682 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7683 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7684 result.append(buffer);
7685 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7686 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7687 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7688 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7689 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007690 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 mDescriptor.apiVersion,
7692 mDescriptor.flags);
7693 result.append(buffer);
7694 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7695 mDescriptor.name);
7696 result.append(buffer);
7697 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7698 mDescriptor.implementor);
7699 result.append(buffer);
7700
7701 result.append("\t\t- Input configuration:\n");
7702 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7703 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7704 (uint32_t)mConfig.inputCfg.buffer.raw,
7705 mConfig.inputCfg.buffer.frameCount,
7706 mConfig.inputCfg.samplingRate,
7707 mConfig.inputCfg.channels,
7708 mConfig.inputCfg.format);
7709 result.append(buffer);
7710
7711 result.append("\t\t- Output configuration:\n");
7712 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7713 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7714 (uint32_t)mConfig.outputCfg.buffer.raw,
7715 mConfig.outputCfg.buffer.frameCount,
7716 mConfig.outputCfg.samplingRate,
7717 mConfig.outputCfg.channels,
7718 mConfig.outputCfg.format);
7719 result.append(buffer);
7720
7721 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7722 result.append(buffer);
7723 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7724 for (size_t i = 0; i < mHandles.size(); ++i) {
7725 sp<EffectHandle> handle = mHandles[i].promote();
7726 if (handle != 0) {
7727 handle->dump(buffer, SIZE);
7728 result.append(buffer);
7729 }
7730 }
7731
7732 result.append("\n");
7733
7734 write(fd, result.string(), result.length());
7735
7736 if (locked) {
7737 mLock.unlock();
7738 }
7739
7740 return NO_ERROR;
7741}
7742
7743// ----------------------------------------------------------------------------
7744// EffectHandle implementation
7745// ----------------------------------------------------------------------------
7746
7747#undef LOG_TAG
7748#define LOG_TAG "AudioFlinger::EffectHandle"
7749
7750AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7751 const sp<AudioFlinger::Client>& client,
7752 const sp<IEffectClient>& effectClient,
7753 int32_t priority)
7754 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007755 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007756 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757{
Steve Block3856b092011-10-20 11:56:00 +01007758 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007760 if (client == 0) {
7761 return;
7762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7764 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7765 if (mCblkMemory != 0) {
7766 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7767
Glenn Kastena0d68332012-01-27 16:47:15 -08007768 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 new(mCblk) effect_param_cblk_t();
7770 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007773 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 return;
7775 }
7776}
7777
7778AudioFlinger::EffectHandle::~EffectHandle()
7779{
Steve Block3856b092011-10-20 11:56:00 +01007780 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007781 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007782 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783}
7784
7785status_t AudioFlinger::EffectHandle::enable()
7786{
Steve Block3856b092011-10-20 11:56:00 +01007787 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 if (!mHasControl) return INVALID_OPERATION;
7789 if (mEffect == 0) return DEAD_OBJECT;
7790
Eric Laurentdb7c0792011-08-10 10:37:50 -07007791 if (mEnabled) {
7792 return NO_ERROR;
7793 }
7794
Eric Laurent59255e42011-07-27 19:49:51 -07007795 mEnabled = true;
7796
7797 sp<ThreadBase> thread = mEffect->thread().promote();
7798 if (thread != 0) {
7799 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7800 }
7801
7802 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7803 if (mEffect->suspended()) {
7804 return NO_ERROR;
7805 }
7806
Eric Laurentdb7c0792011-08-10 10:37:50 -07007807 status_t status = mEffect->setEnabled(true);
7808 if (status != NO_ERROR) {
7809 if (thread != 0) {
7810 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7811 }
7812 mEnabled = false;
7813 }
7814 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815}
7816
7817status_t AudioFlinger::EffectHandle::disable()
7818{
Steve Block3856b092011-10-20 11:56:00 +01007819 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007821 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822
Eric Laurentdb7c0792011-08-10 10:37:50 -07007823 if (!mEnabled) {
7824 return NO_ERROR;
7825 }
Eric Laurent59255e42011-07-27 19:49:51 -07007826 mEnabled = false;
7827
7828 if (mEffect->suspended()) {
7829 return NO_ERROR;
7830 }
7831
7832 status_t status = mEffect->setEnabled(false);
7833
7834 sp<ThreadBase> thread = mEffect->thread().promote();
7835 if (thread != 0) {
7836 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7837 }
7838
7839 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007840}
7841
7842void AudioFlinger::EffectHandle::disconnect()
7843{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007844 disconnect(true);
7845}
7846
Glenn Kasten58123c32012-02-03 10:32:24 -08007847void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007848{
Glenn Kasten58123c32012-02-03 10:32:24 -08007849 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007850 if (mEffect == 0) {
7851 return;
7852 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007853 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007854
Eric Laurenta85a74a2011-10-19 11:44:54 -07007855 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007856 sp<ThreadBase> thread = mEffect->thread().promote();
7857 if (thread != 0) {
7858 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7859 }
Eric Laurent59255e42011-07-27 19:49:51 -07007860 }
7861
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 // release sp on module => module destructor can be called now
7863 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007865 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007866 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007867 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7868 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007869 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007870 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7872 mClient.clear();
7873 }
7874}
7875
Eric Laurent25f43952010-07-28 05:40:18 -07007876status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7877 uint32_t cmdSize,
7878 void *pCmdData,
7879 uint32_t *replySize,
7880 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881{
Steve Block3856b092011-10-20 11:56:00 +01007882// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007883// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884
7885 // only get parameter command is permitted for applications not controlling the effect
7886 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7887 return INVALID_OPERATION;
7888 }
7889 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007890 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891
7892 // handle commands that are not forwarded transparently to effect engine
7893 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7894 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7895 // no risk to block the whole media server process or mixer threads is we are stuck here
7896 Mutex::Autolock _l(mCblk->lock);
7897 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7898 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7899 mCblk->serverIndex = 0;
7900 mCblk->clientIndex = 0;
7901 return BAD_VALUE;
7902 }
7903 status_t status = NO_ERROR;
7904 while (mCblk->serverIndex < mCblk->clientIndex) {
7905 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007906 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007907 int *p = (int *)(mBuffer + mCblk->serverIndex);
7908 int size = *p++;
7909 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007910 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911 break;
7912 }
7913 effect_param_t *param = (effect_param_t *)p;
7914 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007915 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 mCblk->serverIndex += size;
7917 continue;
7918 }
Eric Laurent25f43952010-07-28 05:40:18 -07007919 uint32_t psize = sizeof(effect_param_t) +
7920 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7921 param->vsize;
7922 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7923 psize,
7924 p,
7925 &rsize,
7926 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007927 // stop at first error encountered
7928 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007929 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007930 *(int *)pReplyData = reply;
7931 break;
7932 } else if (reply != NO_ERROR) {
7933 *(int *)pReplyData = reply;
7934 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 }
7936 mCblk->serverIndex += size;
7937 }
7938 mCblk->serverIndex = 0;
7939 mCblk->clientIndex = 0;
7940 return status;
7941 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007942 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943 return enable();
7944 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007945 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007946 return disable();
7947 }
7948
7949 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7950}
7951
Eric Laurent59255e42011-07-27 19:49:51 -07007952void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007953{
Steve Block3856b092011-10-20 11:56:00 +01007954 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955
7956 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007957 mEnabled = enabled;
7958
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 if (signal && mEffectClient != 0) {
7960 mEffectClient->controlStatusChanged(hasControl);
7961 }
7962}
7963
Eric Laurent25f43952010-07-28 05:40:18 -07007964void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7965 uint32_t cmdSize,
7966 void *pCmdData,
7967 uint32_t replySize,
7968 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969{
7970 if (mEffectClient != 0) {
7971 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7972 }
7973}
7974
7975
7976
7977void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7978{
7979 if (mEffectClient != 0) {
7980 mEffectClient->enableStatusChanged(enabled);
7981 }
7982}
7983
7984status_t AudioFlinger::EffectHandle::onTransact(
7985 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7986{
7987 return BnEffect::onTransact(code, data, reply, flags);
7988}
7989
7990
7991void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7992{
Glenn Kastena0d68332012-01-27 16:47:15 -08007993 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994
7995 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007996 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007997 mPriority,
7998 mHasControl,
7999 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008000 mCblk ? mCblk->clientIndex : 0,
8001 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008002 );
8003
8004 if (locked) {
8005 mCblk->lock.unlock();
8006 }
8007}
8008
8009#undef LOG_TAG
8010#define LOG_TAG "AudioFlinger::EffectChain"
8011
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008012AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008014 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008015 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8016 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008017{
Dima Zavinfce7a472011-04-19 22:30:36 -07008018 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008019 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008020 return;
8021 }
8022 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8023 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024}
8025
8026AudioFlinger::EffectChain::~EffectChain()
8027{
8028 if (mOwnInBuffer) {
8029 delete mInBuffer;
8030 }
8031
8032}
8033
Eric Laurent59255e42011-07-27 19:49:51 -07008034// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008035sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 size_t size = mEffects.size();
8038
8039 for (size_t i = 0; i < size; i++) {
8040 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008041 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 }
8043 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008044 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008045}
8046
Eric Laurent59255e42011-07-27 19:49:51 -07008047// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008048sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008050 size_t size = mEffects.size();
8051
8052 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008053 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8054 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008055 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 }
8057 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008058 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008059}
8060
Eric Laurent59255e42011-07-27 19:49:51 -07008061// getEffectFromType_l() must be called with ThreadBase::mLock held
8062sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8063 const effect_uuid_t *type)
8064{
Eric Laurent59255e42011-07-27 19:49:51 -07008065 size_t size = mEffects.size();
8066
8067 for (size_t i = 0; i < size; i++) {
8068 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008069 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008070 }
8071 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008072 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008073}
8074
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075// Must be called with EffectChain::mLock locked
8076void AudioFlinger::EffectChain::process_l()
8077{
Eric Laurentdac69112010-09-28 14:09:57 -07008078 sp<ThreadBase> thread = mThread.promote();
8079 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008080 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008081 return;
8082 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008083 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8084 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008085 // always process effects unless no more tracks are on the session and the effect tail
8086 // has been rendered
8087 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008088 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008089 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008090
Eric Laurent544fe9b2011-11-11 15:42:52 -08008091 if (!tracksOnSession && mTailBufferCount == 0) {
8092 doProcess = false;
8093 }
8094
8095 if (activeTrackCnt() == 0) {
8096 // if no track is active and the effect tail has not been rendered,
8097 // the input buffer must be cleared here as the mixer process will not do it
8098 if (tracksOnSession || mTailBufferCount > 0) {
8099 size_t numSamples = thread->frameCount() * thread->channelCount();
8100 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8101 if (mTailBufferCount > 0) {
8102 mTailBufferCount--;
8103 }
8104 }
8105 }
Eric Laurentdac69112010-09-28 14:09:57 -07008106 }
8107
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008109 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008110 for (size_t i = 0; i < size; i++) {
8111 mEffects[i]->process();
8112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008113 }
8114 for (size_t i = 0; i < size; i++) {
8115 mEffects[i]->updateState();
8116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008117}
8118
Eric Laurentcab11242010-07-15 12:50:15 -07008119// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008120status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121{
8122 effect_descriptor_t desc = effect->desc();
8123 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8124
8125 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008126 effect->setChain(this);
8127 sp<ThreadBase> thread = mThread.promote();
8128 if (thread == 0) {
8129 return NO_INIT;
8130 }
8131 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132
8133 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8134 // Auxiliary effects are inserted at the beginning of mEffects vector as
8135 // they are processed first and accumulated in chain input buffer
8136 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008137
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 // the input buffer for auxiliary effect contains mono samples in
8139 // 32 bit format. This is to avoid saturation in AudoMixer
8140 // accumulation stage. Saturation is done in EffectModule::process() before
8141 // calling the process in effect engine
8142 size_t numSamples = thread->frameCount();
8143 int32_t *buffer = new int32_t[numSamples];
8144 memset(buffer, 0, numSamples * sizeof(int32_t));
8145 effect->setInBuffer((int16_t *)buffer);
8146 // auxiliary effects output samples to chain input buffer for further processing
8147 // by insert effects
8148 effect->setOutBuffer(mInBuffer);
8149 } else {
8150 // Insert effects are inserted at the end of mEffects vector as they are processed
8151 // after track and auxiliary effects.
8152 // Insert effect order as a function of indicated preference:
8153 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8154 // another effect is present
8155 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8156 // last effect claiming first position
8157 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8158 // first effect claiming last position
8159 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8160 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8161 // already present
8162
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008163 size_t size = mEffects.size();
8164 size_t idx_insert = size;
8165 ssize_t idx_insert_first = -1;
8166 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008168 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169 effect_descriptor_t d = mEffects[i]->desc();
8170 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8171 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8172 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8173 // check invalid effect chaining combinations
8174 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8175 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008176 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177 return INVALID_OPERATION;
8178 }
8179 // remember position of first insert effect and by default
8180 // select this as insert position for new effect
8181 if (idx_insert == size) {
8182 idx_insert = i;
8183 }
8184 // remember position of last insert effect claiming
8185 // first position
8186 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8187 idx_insert_first = i;
8188 }
8189 // remember position of first insert effect claiming
8190 // last position
8191 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8192 idx_insert_last == -1) {
8193 idx_insert_last = i;
8194 }
8195 }
8196 }
8197
8198 // modify idx_insert from first position if needed
8199 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8200 if (idx_insert_last != -1) {
8201 idx_insert = idx_insert_last;
8202 } else {
8203 idx_insert = size;
8204 }
8205 } else {
8206 if (idx_insert_first != -1) {
8207 idx_insert = idx_insert_first + 1;
8208 }
8209 }
8210
8211 // always read samples from chain input buffer
8212 effect->setInBuffer(mInBuffer);
8213
8214 // if last effect in the chain, output samples to chain
8215 // output buffer, otherwise to chain input buffer
8216 if (idx_insert == size) {
8217 if (idx_insert != 0) {
8218 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8219 mEffects[idx_insert-1]->configure();
8220 }
8221 effect->setOutBuffer(mOutBuffer);
8222 } else {
8223 effect->setOutBuffer(mInBuffer);
8224 }
8225 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008226
Steve Block3856b092011-10-20 11:56:00 +01008227 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228 }
8229 effect->configure();
8230 return NO_ERROR;
8231}
8232
Eric Laurentcab11242010-07-15 12:50:15 -07008233// removeEffect_l() must be called with PlaybackThread::mLock held
8234size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235{
8236 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008237 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008238 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8239
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008240 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008241 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008242 // calling stop here will remove pre-processing effect from the audio HAL.
8243 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8244 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008245 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8246 mEffects[i]->state() == EffectModule::STOPPING) {
8247 mEffects[i]->stop();
8248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008249 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8250 delete[] effect->inBuffer();
8251 } else {
8252 if (i == size - 1 && i != 0) {
8253 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8254 mEffects[i - 1]->configure();
8255 }
8256 }
8257 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008258 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 break;
8260 }
8261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262
8263 return mEffects.size();
8264}
8265
Eric Laurentcab11242010-07-15 12:50:15 -07008266// setDevice_l() must be called with PlaybackThread::mLock held
8267void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268{
8269 size_t size = mEffects.size();
8270 for (size_t i = 0; i < size; i++) {
8271 mEffects[i]->setDevice(device);
8272 }
8273}
8274
Eric Laurentcab11242010-07-15 12:50:15 -07008275// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008276void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277{
8278 size_t size = mEffects.size();
8279 for (size_t i = 0; i < size; i++) {
8280 mEffects[i]->setMode(mode);
8281 }
8282}
8283
Eric Laurentcab11242010-07-15 12:50:15 -07008284// setVolume_l() must be called with PlaybackThread::mLock held
8285bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286{
8287 uint32_t newLeft = *left;
8288 uint32_t newRight = *right;
8289 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008290 int ctrlIdx = -1;
8291 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292
Eric Laurentcab11242010-07-15 12:50:15 -07008293 // first update volume controller
8294 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008295 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008296 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8297 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008298 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008299 break;
8300 }
8301 }
8302
8303 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008304 if (hasControl) {
8305 *left = mNewLeftVolume;
8306 *right = mNewRightVolume;
8307 }
8308 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008309 }
8310
8311 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008312 mLeftVolume = newLeft;
8313 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008314
8315 // second get volume update from volume controller
8316 if (ctrlIdx >= 0) {
8317 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008318 mNewLeftVolume = newLeft;
8319 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008320 }
8321 // then indicate volume to all other effects in chain.
8322 // Pass altered volume to effects before volume controller
8323 // and requested volume to effects after controller
8324 uint32_t lVol = newLeft;
8325 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008326
Mathias Agopian65ab4712010-07-14 17:59:35 -07008327 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008328 if ((int)i == ctrlIdx) continue;
8329 // this also works for ctrlIdx == -1 when there is no volume controller
8330 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 lVol = *left;
8332 rVol = *right;
8333 }
8334 mEffects[i]->setVolume(&lVol, &rVol, false);
8335 }
8336 *left = newLeft;
8337 *right = newRight;
8338
8339 return hasControl;
8340}
8341
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8343{
8344 const size_t SIZE = 256;
8345 char buffer[SIZE];
8346 String8 result;
8347
8348 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8349 result.append(buffer);
8350
8351 bool locked = tryLock(mLock);
8352 // failed to lock - AudioFlinger is probably deadlocked
8353 if (!locked) {
8354 result.append("\tCould not lock mutex:\n");
8355 }
8356
Eric Laurentcab11242010-07-15 12:50:15 -07008357 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8358 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 mEffects.size(),
8360 (uint32_t)mInBuffer,
8361 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008362 mActiveTrackCnt);
8363 result.append(buffer);
8364 write(fd, result.string(), result.size());
8365
8366 for (size_t i = 0; i < mEffects.size(); ++i) {
8367 sp<EffectModule> effect = mEffects[i];
8368 if (effect != 0) {
8369 effect->dump(fd, args);
8370 }
8371 }
8372
8373 if (locked) {
8374 mLock.unlock();
8375 }
8376
8377 return NO_ERROR;
8378}
8379
Eric Laurent59255e42011-07-27 19:49:51 -07008380// must be called with ThreadBase::mLock held
8381void AudioFlinger::EffectChain::setEffectSuspended_l(
8382 const effect_uuid_t *type, bool suspend)
8383{
8384 sp<SuspendedEffectDesc> desc;
8385 // use effect type UUID timelow as key as there is no real risk of identical
8386 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008387 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008388 if (suspend) {
8389 if (index >= 0) {
8390 desc = mSuspendedEffects.valueAt(index);
8391 } else {
8392 desc = new SuspendedEffectDesc();
8393 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8394 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008395 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008396 }
8397 if (desc->mRefCount++ == 0) {
8398 sp<EffectModule> effect = getEffectIfEnabled(type);
8399 if (effect != 0) {
8400 desc->mEffect = effect;
8401 effect->setSuspended(true);
8402 effect->setEnabled(false);
8403 }
8404 }
8405 } else {
8406 if (index < 0) {
8407 return;
8408 }
8409 desc = mSuspendedEffects.valueAt(index);
8410 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008411 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008412 desc->mRefCount = 1;
8413 }
8414 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008415 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008416 if (desc->mEffect != 0) {
8417 sp<EffectModule> effect = desc->mEffect.promote();
8418 if (effect != 0) {
8419 effect->setSuspended(false);
8420 sp<EffectHandle> handle = effect->controlHandle();
8421 if (handle != 0) {
8422 effect->setEnabled(handle->enabled());
8423 }
8424 }
8425 desc->mEffect.clear();
8426 }
8427 mSuspendedEffects.removeItemsAt(index);
8428 }
8429 }
8430}
8431
8432// must be called with ThreadBase::mLock held
8433void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8434{
8435 sp<SuspendedEffectDesc> desc;
8436
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008437 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008438 if (suspend) {
8439 if (index >= 0) {
8440 desc = mSuspendedEffects.valueAt(index);
8441 } else {
8442 desc = new SuspendedEffectDesc();
8443 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008444 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008445 }
8446 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008447 Vector< sp<EffectModule> > effects;
8448 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008449 for (size_t i = 0; i < effects.size(); i++) {
8450 setEffectSuspended_l(&effects[i]->desc().type, true);
8451 }
8452 }
8453 } else {
8454 if (index < 0) {
8455 return;
8456 }
8457 desc = mSuspendedEffects.valueAt(index);
8458 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008459 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008460 desc->mRefCount = 1;
8461 }
8462 if (--desc->mRefCount == 0) {
8463 Vector<const effect_uuid_t *> types;
8464 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8465 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8466 continue;
8467 }
8468 types.add(&mSuspendedEffects.valueAt(i)->mType);
8469 }
8470 for (size_t i = 0; i < types.size(); i++) {
8471 setEffectSuspended_l(types[i], false);
8472 }
Steve Block3856b092011-10-20 11:56:00 +01008473 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008474 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8475 }
8476 }
8477}
8478
Eric Laurent6bffdb82011-09-23 08:40:41 -07008479
8480// The volume effect is used for automated tests only
8481#ifndef OPENSL_ES_H_
8482static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8483 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8484const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8485#endif //OPENSL_ES_H_
8486
Eric Laurentdb7c0792011-08-10 10:37:50 -07008487bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8488{
8489 // auxiliary effects and visualizer are never suspended on output mix
8490 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8491 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008492 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8493 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008494 return false;
8495 }
8496 return true;
8497}
8498
Glenn Kastend0539712012-01-30 12:56:03 -08008499void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008500{
Glenn Kastend0539712012-01-30 12:56:03 -08008501 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008502 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008503 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8504 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008505 }
Eric Laurent59255e42011-07-27 19:49:51 -07008506 }
Eric Laurent59255e42011-07-27 19:49:51 -07008507}
8508
8509sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8510 const effect_uuid_t *type)
8511{
Glenn Kasten090f0192012-01-30 13:00:02 -08008512 sp<EffectModule> effect = getEffectFromType_l(type);
8513 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008514}
8515
8516void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8517 bool enabled)
8518{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008519 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008520 if (enabled) {
8521 if (index < 0) {
8522 // if the effect is not suspend check if all effects are suspended
8523 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8524 if (index < 0) {
8525 return;
8526 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008527 if (!isEffectEligibleForSuspend(effect->desc())) {
8528 return;
8529 }
Eric Laurent59255e42011-07-27 19:49:51 -07008530 setEffectSuspended_l(&effect->desc().type, enabled);
8531 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008532 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008533 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008534 return;
8535 }
Eric Laurent59255e42011-07-27 19:49:51 -07008536 }
Steve Block3856b092011-10-20 11:56:00 +01008537 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008538 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008539 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8540 // if effect is requested to suspended but was not yet enabled, supend it now.
8541 if (desc->mEffect == 0) {
8542 desc->mEffect = effect;
8543 effect->setEnabled(false);
8544 effect->setSuspended(true);
8545 }
8546 } else {
8547 if (index < 0) {
8548 return;
8549 }
Steve Block3856b092011-10-20 11:56:00 +01008550 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008551 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008552 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8553 desc->mEffect.clear();
8554 effect->setSuspended(false);
8555 }
8556}
8557
Mathias Agopian65ab4712010-07-14 17:59:35 -07008558#undef LOG_TAG
8559#define LOG_TAG "AudioFlinger"
8560
8561// ----------------------------------------------------------------------------
8562
8563status_t AudioFlinger::onTransact(
8564 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8565{
8566 return BnAudioFlinger::onTransact(code, data, reply, flags);
8567}
8568
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569}; // namespace android