blob: 865051fd1111eaf8f4e5e76a52a43cbfcfd2bf62 [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,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800404 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 int *sessionId,
406 status_t *status)
407{
408 sp<PlaybackThread::Track> track;
409 sp<TrackHandle> trackHandle;
410 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 status_t lStatus;
412 int lSessionId;
413
Glenn Kasten263709e2012-01-06 08:40:01 -0800414 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
415 // but if someone uses binder directly they could bypass that and cause us to crash
416 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000417 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418 lStatus = BAD_VALUE;
419 goto Exit;
420 }
421
422 {
423 Mutex::Autolock _l(mLock);
424 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700425 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000427 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428 lStatus = BAD_VALUE;
429 goto Exit;
430 }
431
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800432 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433
Steve Block3856b092011-10-20 11:56:00 +0100434 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700435 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700436 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700437 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
438 if (mPlaybackThreads.keyAt(i) != output) {
439 // prevent same audio session on different output threads
440 uint32_t sessions = t->hasAudioSession(*sessionId);
441 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000442 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700443 lStatus = BAD_VALUE;
444 goto Exit;
445 }
446 // check if an effect with same session ID is waiting for a track to be created
447 if (sessions & PlaybackThread::EFFECT_SESSION) {
448 effectThread = t.get();
449 }
Eric Laurentde070132010-07-13 04:45:46 -0700450 }
451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 lSessionId = *sessionId;
453 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700454 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700455 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456 if (sessionId != NULL) {
457 *sessionId = lSessionId;
458 }
459 }
Steve Block3856b092011-10-20 11:56:00 +0100460 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461
462 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800463 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &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,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001572 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 status_t *status)
1574{
1575 sp<Track> track;
1576 status_t lStatus;
1577
Glenn Kasten73d22752012-03-19 13:38:30 -07001578 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1579
1580 // client expresses a preference for FAST, but we get the final say
1581 if ((flags & IAudioFlinger::TRACK_FAST) &&
1582 !(
1583 // not timed
1584 (!isTimed) &&
1585 // either of these use cases:
1586 (
1587 // use case 1: shared buffer with any frame count
1588 (
1589 (sharedBuffer != 0)
1590 ) ||
1591 // use case 2: callback handler and small power-of-2 frame count
1592 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001593 (tid != -1) &&
Glenn Kasten73d22752012-03-19 13:38:30 -07001594 // FIXME supported frame counts should not be hard-coded
1595 (
1596 (frameCount == 128) ||
1597 (frameCount == 256) ||
1598 (frameCount == 512)
1599 )
1600 )
1601 ) &&
1602 // PCM data
1603 audio_is_linear_pcm(format) &&
1604 // mono or stereo
1605 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1606 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1607 // hardware sample rate
1608 (sampleRate == mSampleRate)
1609 // FIXME test that MixerThread for this fast track has a capable output HAL
1610 // FIXME add a permission test also?
1611 ) ) {
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001612 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied");
Glenn Kasten73d22752012-03-19 13:38:30 -07001613 flags &= ~IAudioFlinger::TRACK_FAST;
1614 }
1615
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001617 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1618 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001619 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001620 "for output %p with format %d",
1621 sampleRate, format, channelMask, mOutput, mFormat);
1622 lStatus = BAD_VALUE;
1623 goto Exit;
1624 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 }
1626 } else {
1627 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1628 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001629 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 lStatus = BAD_VALUE;
1631 goto Exit;
1632 }
1633 }
1634
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001635 lStatus = initCheck();
1636 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001637 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 goto Exit;
1639 }
1640
1641 { // scope for mLock
1642 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001643
1644 // all tracks in same audio session must share the same routing strategy otherwise
1645 // conflicts will happen when tracks are moved from one output to another by audio policy
1646 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001647 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001648 for (size_t i = 0; i < mTracks.size(); ++i) {
1649 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001650 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001651 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001652 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001653 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001654 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001655 lStatus = BAD_VALUE;
1656 goto Exit;
1657 }
1658 }
1659 }
1660
John Grossman4ff14ba2012-02-08 16:37:41 -08001661 if (!isTimed) {
1662 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001663 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001664 } else {
1665 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1666 channelMask, frameCount, sharedBuffer, sessionId);
1667 }
1668 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 lStatus = NO_MEMORY;
1670 goto Exit;
1671 }
1672 mTracks.add(track);
1673
1674 sp<EffectChain> chain = getEffectChain_l(sessionId);
1675 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001676 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001678 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001679 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 }
1681 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001682
1683#ifdef HAVE_REQUEST_PRIORITY
1684 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1685 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1686 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1687 // so ask activity manager to do this on our behalf
1688 int err = requestPriority(callingPid, tid, 1);
1689 if (err != 0) {
1690 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1691 1, callingPid, tid, err);
1692 }
1693 }
1694#endif
1695
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 lStatus = NO_ERROR;
1697
1698Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001699 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 *status = lStatus;
1701 }
1702 return track;
1703}
1704
1705uint32_t AudioFlinger::PlaybackThread::latency() const
1706{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001707 Mutex::Autolock _l(mLock);
1708 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001709 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001710 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 return 0;
1712 }
1713}
1714
Glenn Kasten6637baa2012-01-09 09:40:36 -08001715void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001717 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719}
1720
Glenn Kasten6637baa2012-01-09 09:40:36 -08001721void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001723 Mutex::Autolock _l(mLock);
1724 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725}
1726
Glenn Kasten6637baa2012-01-09 09:40:36 -08001727void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001729 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731}
1732
Glenn Kasten6637baa2012-01-09 09:40:36 -08001733void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001735 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737}
1738
Glenn Kastenfff6d712012-01-12 16:38:12 -08001739float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001741 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 return mStreamTypes[stream].volume;
1743}
1744
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745// addTrack_l() must be called with ThreadBase::mLock held
1746status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1747{
1748 status_t status = ALREADY_EXISTS;
1749
1750 // set retry count for buffer fill
1751 track->mRetryCount = kMaxTrackStartupRetries;
1752 if (mActiveTracks.indexOf(track) < 0) {
1753 // the track is newly added, make sure it fills up all its
1754 // buffers before playing. This is to ensure the client will
1755 // effectively get the latency it requested.
1756 track->mFillingUpStatus = Track::FS_FILLING;
1757 track->mResetDone = false;
1758 mActiveTracks.add(track);
1759 if (track->mainBuffer() != mMixBuffer) {
1760 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1761 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001762 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001763 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765 }
1766
1767 status = NO_ERROR;
1768 }
1769
Steve Block3856b092011-10-20 11:56:00 +01001770 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 mWaitWorkCV.broadcast();
1772
1773 return status;
1774}
1775
1776// destroyTrack_l() must be called with ThreadBase::mLock held
1777void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1778{
1779 track->mState = TrackBase::TERMINATED;
1780 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001781 removeTrack_l(track);
1782 }
1783}
1784
1785void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1786{
1787 mTracks.remove(track);
1788 deleteTrackName_l(track->name());
1789 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1790 if (chain != 0) {
1791 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 }
1793}
1794
1795String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1796{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001797 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001798 char *s;
1799
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001800 Mutex::Autolock _l(mLock);
1801 if (initCheck() != NO_ERROR) {
1802 return out_s8;
1803 }
1804
Dima Zavin799a70e2011-04-18 16:57:27 -07001805 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001806 out_s8 = String8(s);
1807 free(s);
1808 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809}
1810
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001811// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1813 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001814 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815
Steve Block3856b092011-10-20 11:56:00 +01001816 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
1818 switch (event) {
1819 case AudioSystem::OUTPUT_OPENED:
1820 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001821 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 desc.samplingRate = mSampleRate;
1823 desc.format = mFormat;
1824 desc.frameCount = mFrameCount;
1825 desc.latency = latency();
1826 param2 = &desc;
1827 break;
1828
1829 case AudioSystem::STREAM_CONFIG_CHANGED:
1830 param2 = &param;
1831 case AudioSystem::OUTPUT_CLOSED:
1832 default:
1833 break;
1834 }
1835 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1836}
1837
1838void AudioFlinger::PlaybackThread::readOutputParameters()
1839{
Dima Zavin799a70e2011-04-18 16:57:27 -07001840 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001841 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1842 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001843 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001844 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001845 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846
1847 // FIXME - Current mixer implementation only supports stereo output: Always
1848 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001849 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 mMixBuffer = new int16_t[mFrameCount * 2];
1851 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1852
Eric Laurentde070132010-07-13 04:45:46 -07001853 // force reconfiguration of effect chains and engines to take new buffer size and audio
1854 // parameters into account
1855 // Note that mLock is not held when readOutputParameters() is called from the constructor
1856 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1857 // matter.
1858 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1859 Vector< sp<EffectChain> > effectChains = mEffectChains;
1860 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001861 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001862 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863}
1864
1865status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1866{
Glenn Kastena0d68332012-01-27 16:47:15 -08001867 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 return BAD_VALUE;
1869 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001870 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001871 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 return INVALID_OPERATION;
1873 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001874 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875
Dima Zavin799a70e2011-04-18 16:57:27 -07001876 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877}
1878
Eric Laurent39e94f82010-07-28 01:32:47 -07001879uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880{
1881 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001882 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001884 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 }
1886
1887 for (size_t i = 0; i < mTracks.size(); ++i) {
1888 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001889 if (sessionId == track->sessionId() &&
1890 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001891 result |= TRACK_SESSION;
1892 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894 }
1895
Eric Laurent39e94f82010-07-28 01:32:47 -07001896 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897}
1898
Eric Laurentde070132010-07-13 04:45:46 -07001899uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1900{
Dima Zavinfce7a472011-04-19 22:30:36 -07001901 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001902 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001903 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1904 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001905 }
1906 for (size_t i = 0; i < mTracks.size(); i++) {
1907 sp<Track> track = mTracks[i];
1908 if (sessionId == track->sessionId() &&
1909 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001910 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001911 }
1912 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001913 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001914}
1915
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
Glenn Kastenaed850d2012-01-26 09:46:34 -08001917AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001918{
1919 Mutex::Autolock _l(mLock);
1920 return mOutput;
1921}
1922
1923AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1924{
1925 Mutex::Autolock _l(mLock);
1926 AudioStreamOut *output = mOutput;
1927 mOutput = NULL;
1928 return output;
1929}
1930
1931// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001932audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001933{
1934 if (mOutput == NULL) {
1935 return NULL;
1936 }
1937 return &mOutput->stream->common;
1938}
1939
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08001940uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08001941{
1942 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1943 // decoding and transfer time. So sleeping for half of the latency would likely cause
1944 // underruns
1945 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1946 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1947 } else {
1948 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1949 }
1950}
1951
Eric Laurenta011e352012-03-29 15:51:43 -07001952status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1953{
1954 if (!isValidSyncEvent(event)) {
1955 return BAD_VALUE;
1956 }
1957
1958 Mutex::Autolock _l(mLock);
1959
1960 for (size_t i = 0; i < mTracks.size(); ++i) {
1961 sp<Track> track = mTracks[i];
1962 if (event->triggerSession() == track->sessionId()) {
1963 track->setSyncEvent(event);
1964 return NO_ERROR;
1965 }
1966 }
1967
1968 return NAME_NOT_FOUND;
1969}
1970
1971bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
1972{
1973 switch (event->type()) {
1974 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
1975 return true;
1976 default:
1977 break;
1978 }
1979 return false;
1980}
1981
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982// ----------------------------------------------------------------------------
1983
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001984AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001985 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten000f0e32012-03-01 17:10:56 -08001986 : PlaybackThread(audioFlinger, output, id, device, type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987{
Glenn Kasten000f0e32012-03-01 17:10:56 -08001988 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 // FIXME - Current mixer implementation only supports stereo output
1990 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001991 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 }
1993}
1994
1995AudioFlinger::MixerThread::~MixerThread()
1996{
1997 delete mAudioMixer;
1998}
1999
Glenn Kasten83efdd02012-02-24 07:21:32 -08002000class CpuStats {
2001public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002002 CpuStats();
2003 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002004#ifdef DEBUG_CPU_USAGE
2005private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002006 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2007 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2008
2009 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2010
2011 int mCpuNum; // thread's current CPU number
2012 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002013#endif
2014};
2015
Glenn Kasten190a46f2012-03-06 11:27:10 -08002016CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002017#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002018 : mCpuNum(-1), mCpukHz(-1)
2019#endif
2020{
2021}
2022
2023void CpuStats::sample(const String8 &title) {
2024#ifdef DEBUG_CPU_USAGE
2025 // get current thread's delta CPU time in wall clock ns
2026 double wcNs;
2027 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2028
2029 // record sample for wall clock statistics
2030 if (valid) {
2031 mWcStats.sample(wcNs);
2032 }
2033
2034 // get the current CPU number
2035 int cpuNum = sched_getcpu();
2036
2037 // get the current CPU frequency in kHz
2038 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2039
2040 // check if either CPU number or frequency changed
2041 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2042 mCpuNum = cpuNum;
2043 mCpukHz = cpukHz;
2044 // ignore sample for purposes of cycles
2045 valid = false;
2046 }
2047
2048 // if no change in CPU number or frequency, then record sample for cycle statistics
2049 if (valid && mCpukHz > 0) {
2050 double cycles = wcNs * cpukHz * 0.000001;
2051 mHzStats.sample(cycles);
2052 }
2053
2054 unsigned n = mWcStats.n();
2055 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002056 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002057 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002058 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2059 double perLoop = elapsed / (double) n;
2060 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002061 double perLoop1k = perLoop * 0.001;
2062 double mean = mWcStats.mean();
2063 double stddev = mWcStats.stddev();
2064 double minimum = mWcStats.minimum();
2065 double maximum = mWcStats.maximum();
2066 double meanCycles = mHzStats.mean();
2067 double stddevCycles = mHzStats.stddev();
2068 double minCycles = mHzStats.minimum();
2069 double maxCycles = mHzStats.maximum();
2070 mCpuUsage.resetElapsed();
2071 mWcStats.reset();
2072 mHzStats.reset();
2073 ALOGD("CPU usage for %s over past %.1f secs\n"
2074 " (%u mixer loops at %.1f mean ms per loop):\n"
2075 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2076 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2077 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2078 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002079 elapsed * .000000001, n, perLoop * .000001,
2080 mean * .001,
2081 stddev * .001,
2082 minimum * .001,
2083 maximum * .001,
2084 mean / perLoop100,
2085 stddev / perLoop100,
2086 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002087 maximum / perLoop100,
2088 meanCycles / perLoop1k,
2089 stddevCycles / perLoop1k,
2090 minCycles / perLoop1k,
2091 maxCycles / perLoop1k);
2092
Glenn Kasten83efdd02012-02-24 07:21:32 -08002093 }
2094 }
2095#endif
2096};
2097
Glenn Kasten37d825e2012-02-24 07:21:48 -08002098void AudioFlinger::PlaybackThread::checkSilentMode_l()
2099{
2100 if (!mMasterMute) {
2101 char value[PROPERTY_VALUE_MAX];
2102 if (property_get("ro.audio.silent", value, "0") > 0) {
2103 char *endptr;
2104 unsigned long ul = strtoul(value, &endptr, 0);
2105 if (*endptr == '\0' && ul != 0) {
2106 ALOGD("Silence is golden");
2107 // The setprop command will not allow a property to be changed after
2108 // the first time it is set, so we don't have to worry about un-muting.
2109 setMasterMute_l(true);
2110 }
2111 }
2112 }
2113}
2114
Glenn Kasten000f0e32012-03-01 17:10:56 -08002115bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116{
2117 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002118
Glenn Kasten000f0e32012-03-01 17:10:56 -08002119 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002120
2121 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002123if (mType == MIXER) {
2124 longStandbyExit = false;
2125}
Glenn Kasten688a6402012-02-29 07:57:06 -08002126
Glenn Kasten000f0e32012-03-01 17:10:56 -08002127 // DUPLICATING
2128 // FIXME could this be made local to while loop?
2129 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002130
Glenn Kasten66fcab92012-02-24 14:59:21 -08002131 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002132 sleepTime = idleSleepTime;
2133
2134if (mType == MIXER) {
2135 sleepTimeShift = 0;
2136}
2137
Glenn Kasten83efdd02012-02-24 07:21:32 -08002138 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002139 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140
Eric Laurentfeb0db62011-07-22 09:04:31 -07002141 acquireWakeLock();
2142
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 while (!exitPending())
2144 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002145 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002146
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002147 Vector< sp<EffectChain> > effectChains;
2148
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 processConfigEvents();
2150
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151 { // scope for mLock
2152
2153 Mutex::Autolock _l(mLock);
2154
2155 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002156 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 }
2158
Glenn Kastenfa26a852012-03-06 11:28:04 -08002159 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002160
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002162 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002163 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002165
2166 threadLoop_standby();
2167
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 mStandby = true;
2169 mBytesWritten = 0;
2170 }
2171
Glenn Kasten3e074702012-02-28 18:40:35 -08002172 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 // we're about to wait, flush the binder command buffer
2174 IPCThreadState::self()->flushCommands();
2175
Glenn Kastenfa26a852012-03-06 11:28:04 -08002176 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002177
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 if (exitPending()) break;
2179
Eric Laurentfeb0db62011-07-22 09:04:31 -07002180 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002182 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002184 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002185 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186
Eric Laurent27741442012-01-17 19:20:12 -08002187 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002188
Glenn Kasten37d825e2012-02-24 07:21:48 -08002189 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190
Glenn Kasten000f0e32012-03-01 17:10:56 -08002191 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002193 if (mType == MIXER) {
2194 sleepTimeShift = 0;
2195 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002196
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 continue;
2198 }
2199 }
2200
Glenn Kastenfec279f2012-03-08 07:47:15 -08002201 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2202 // Shift in the new status; this could be a queue if it's
2203 // useful to filter the mixer status over several cycles.
2204 mPrevMixerStatus = mMixerStatus;
2205 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206
2207 // prevent any changes in effect chain list and in each effect chain
2208 // during mixing and effect process as the audio buffers could be deleted
2209 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002210 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212
Glenn Kastenfec279f2012-03-08 07:47:15 -08002213 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002214 threadLoop_mix();
2215 } else {
2216 threadLoop_sleepTime();
2217 }
2218
2219 if (mSuspended > 0) {
2220 sleepTime = suspendSleepTimeUs();
2221 }
2222
2223 // only process effects if we're going to write
2224 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002225 for (size_t i = 0; i < effectChains.size(); i ++) {
2226 effectChains[i]->process_l();
2227 }
2228 }
2229
2230 // enable changes in effect chain
2231 unlockEffectChains(effectChains);
2232
2233 // sleepTime == 0 means we must write to audio hardware
2234 if (sleepTime == 0) {
2235
2236 threadLoop_write();
2237
2238if (mType == MIXER) {
2239 // write blocked detection
2240 nsecs_t now = systemTime();
2241 nsecs_t delta = now - mLastWriteTime;
2242 if (!mStandby && delta > maxPeriod) {
2243 mNumDelayedWrites++;
2244 if ((now - lastWarning) > kWarningThrottleNs) {
2245 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2246 ns2ms(delta), mNumDelayedWrites, this);
2247 lastWarning = now;
2248 }
2249 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2250 // a different threshold. Or completely removed for what it is worth anyway...
2251 if (mStandby) {
2252 longStandbyExit = true;
2253 }
2254 }
2255}
2256
2257 mStandby = false;
2258 } else {
2259 usleep(sleepTime);
2260 }
2261
2262 // finally let go of removed track(s), without the lock held
2263 // since we can't guarantee the destructors won't acquire that
2264 // same lock.
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002265 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002266
Glenn Kastenfa26a852012-03-06 11:28:04 -08002267 // FIXME I don't understand the need for this here;
2268 // it was in the original code but maybe the
2269 // assignment in saveOutputTracks() makes this unnecessary?
2270 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002271
2272 // Effect chains will be actually deleted here if they were removed from
2273 // mEffectChains list during mixing or effects processing
2274 effectChains.clear();
2275
2276 // FIXME Note that the above .clear() is no longer necessary since effectChains
2277 // is now local to this block, but will keep it for now (at least until merge done).
2278 }
2279
2280if (mType == MIXER || mType == DIRECT) {
2281 // put output stream into standby mode
2282 if (!mStandby) {
2283 mOutput->stream->common.standby(&mOutput->stream->common);
2284 }
2285}
2286if (mType == DUPLICATING) {
2287 // for DuplicatingThread, standby mode is handled by the outputTracks
2288}
2289
2290 releaseWakeLock();
2291
2292 ALOGV("Thread %p type %d exiting", this, mType);
2293 return false;
2294}
2295
2296// shared by MIXER and DIRECT, overridden by DUPLICATING
2297void AudioFlinger::PlaybackThread::threadLoop_write()
2298{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002299 // FIXME rewrite to reduce number of system calls
2300 mLastWriteTime = systemTime();
2301 mInWrite = true;
2302 mBytesWritten += mixBufferSize;
2303 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2304 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2305 mNumWrites++;
2306 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002307}
2308
2309// shared by MIXER and DIRECT, overridden by DUPLICATING
2310void AudioFlinger::PlaybackThread::threadLoop_standby()
2311{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002312 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2313 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002314}
2315
2316void AudioFlinger::MixerThread::threadLoop_mix()
2317{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002318 // obtain the presentation timestamp of the next output buffer
2319 int64_t pts;
2320 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002321
Glenn Kasten952eeb22012-03-06 11:30:57 -08002322 if (NULL != mOutput->stream->get_next_write_timestamp) {
2323 status = mOutput->stream->get_next_write_timestamp(
2324 mOutput->stream, &pts);
2325 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002326
Glenn Kasten952eeb22012-03-06 11:30:57 -08002327 if (status != NO_ERROR) {
2328 pts = AudioBufferProvider::kInvalidPTS;
2329 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002330
Glenn Kasten952eeb22012-03-06 11:30:57 -08002331 // mix buffers...
2332 mAudioMixer->process(pts);
2333 // increase sleep time progressively when application underrun condition clears.
2334 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2335 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2336 // such that we would underrun the audio HAL.
2337 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2338 sleepTimeShift--;
2339 }
2340 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002341 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002342 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002343}
2344
2345void AudioFlinger::MixerThread::threadLoop_sleepTime()
2346{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002347 // If no tracks are ready, sleep once for the duration of an output
2348 // buffer size, then write 0s to the output
2349 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002350 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002351 sleepTime = activeSleepTime >> sleepTimeShift;
2352 if (sleepTime < kMinThreadSleepTimeUs) {
2353 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002355 // reduce sleep time in case of consecutive application underruns to avoid
2356 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2357 // duration we would end up writing less data than needed by the audio HAL if
2358 // the condition persists.
2359 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2360 sleepTimeShift++;
2361 }
2362 } else {
2363 sleepTime = idleSleepTime;
2364 }
2365 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002366 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002367 memset (mMixBuffer, 0, mixBufferSize);
2368 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002369 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002370 }
2371 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372}
2373
2374// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002375AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002376 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377{
2378
Glenn Kasten29c23c32012-01-26 13:37:52 -08002379 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002381 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 size_t mixedTracks = 0;
2383 size_t tracksWithEffect = 0;
2384
2385 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002386 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387
Eric Laurent571d49c2010-08-11 05:20:11 -07002388 if (masterMute) {
2389 masterVolume = 0;
2390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002392 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002394 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002395 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 masterVolume = (float)((v + (1 << 23)) >> 24);
2397 chain.clear();
2398 }
2399
2400 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002401 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402 if (t == 0) continue;
2403
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002404 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 Track* const track = t.get();
2406 audio_track_cblk_t* cblk = track->cblk();
2407
2408 // The first time a track is added we wait
2409 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002410 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002411 // make sure that we have enough frames to mix one full buffer.
2412 // enforce this condition only once to enable draining the buffer in case the client
2413 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002414 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002415 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002416 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002417 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002418 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002419 if (t->sampleRate() == (int)mSampleRate) {
2420 minFrames = mFrameCount;
2421 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002422 // +1 for rounding and +1 for additional sample needed for interpolation
2423 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2424 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002425 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002426 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2427 // the minimum track buffer size is normally twice the number of frames necessary
2428 // to fill one buffer and the resampler should not leave more than one buffer worth
2429 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002430 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002431 }
2432 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002433 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 !track->isPaused() && !track->isTerminated())
2435 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002436 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437
2438 mixedTracks++;
2439
2440 // track->mainBuffer() != mMixBuffer means there is an effect chain
2441 // connected to the track
2442 chain.clear();
2443 if (track->mainBuffer() != mMixBuffer) {
2444 chain = getEffectChain_l(track->sessionId());
2445 // Delegate volume control to effect in track effect chain if needed
2446 if (chain != 0) {
2447 tracksWithEffect++;
2448 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002449 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002450 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 }
2452 }
2453
2454
2455 int param = AudioMixer::VOLUME;
2456 if (track->mFillingUpStatus == Track::FS_FILLED) {
2457 // no ramp for the first volume setting
2458 track->mFillingUpStatus = Track::FS_ACTIVE;
2459 if (track->mState == TrackBase::RESUMING) {
2460 track->mState = TrackBase::ACTIVE;
2461 param = AudioMixer::RAMP_VOLUME;
2462 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002463 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464 } else if (cblk->server != 0) {
2465 // If the track is stopped before the first frame was mixed,
2466 // do not apply ramp
2467 param = AudioMixer::RAMP_VOLUME;
2468 }
2469
2470 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002471 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002472 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002473 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002474 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 if (track->isPausing()) {
2476 track->setPaused();
2477 }
2478 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002479
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002481 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002483 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002484 vl = vlr & 0xFFFF;
2485 vr = vlr >> 16;
2486 // track volumes come from shared memory, so can't be trusted and must be clamped
2487 if (vl > MAX_GAIN_INT) {
2488 ALOGV("Track left volume out of range: %04X", vl);
2489 vl = MAX_GAIN_INT;
2490 }
2491 if (vr > MAX_GAIN_INT) {
2492 ALOGV("Track right volume out of range: %04X", vr);
2493 vr = MAX_GAIN_INT;
2494 }
2495 // now apply the master volume and stream type volume
2496 vl = (uint32_t)(v * vl) << 12;
2497 vr = (uint32_t)(v * vr) << 12;
2498 // assuming master volume and stream type volume each go up to 1.0,
2499 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500
Glenn Kasten05632a52012-01-03 14:22:33 -08002501 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2502 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002503 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002504 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002505 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002506 }
2507 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002509 // Delegate volume control to effect in track effect chain if needed
2510 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2511 // Do not ramp volume if volume is controlled by effect
2512 param = AudioMixer::VOLUME;
2513 track->mHasVolumeController = true;
2514 } else {
2515 // force no volume ramp when volume controller was just disabled or removed
2516 // from effect chain to avoid volume spike
2517 if (track->mHasVolumeController) {
2518 param = AudioMixer::VOLUME;
2519 }
2520 track->mHasVolumeController = false;
2521 }
2522
2523 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002524 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002525 vl = (vl + (1 << 11)) >> 12;
2526 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2527 vr = (vr + (1 << 11)) >> 12;
2528 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002529
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002530 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 -07002531
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002533 mAudioMixer->setBufferProvider(name, track);
2534 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002536 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2537 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2538 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002540 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 AudioMixer::TRACK,
2542 AudioMixer::FORMAT, (void *)track->format());
2543 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002544 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002546 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002548 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 AudioMixer::RESAMPLE,
2550 AudioMixer::SAMPLE_RATE,
2551 (void *)(cblk->sampleRate));
2552 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002553 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 AudioMixer::TRACK,
2555 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2556 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002557 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 AudioMixer::TRACK,
2559 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2560
2561 // reset retry count
2562 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002563
Eric Laurent27741442012-01-17 19:20:12 -08002564 // If one track is ready, set the mixer ready if:
2565 // - the mixer was not ready during previous round OR
2566 // - no other track is not ready
2567 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2568 mixerStatus != MIXER_TRACKS_ENABLED) {
2569 mixerStatus = MIXER_TRACKS_READY;
2570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002572 //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 -07002573 if (track->isStopped()) {
2574 track->reset();
2575 }
2576 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2577 // We have consumed all the buffers of this track.
2578 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002579 // TODO: use actual buffer filling status instead of latency when available from
2580 // audio HAL
2581 size_t audioHALFrames =
2582 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2583 size_t framesWritten =
2584 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2585 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2586 tracksToRemove->add(track);
2587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 } else {
2589 // No buffers for this track. Give it a few chances to
2590 // fill a buffer, then remove it from active list.
2591 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002592 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002594 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002595 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002596 // If one track is not ready, mark the mixer also not ready if:
2597 // - the mixer was ready during previous round OR
2598 // - no other track is ready
2599 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2600 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 mixerStatus = MIXER_TRACKS_ENABLED;
2602 }
2603 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002604 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 }
2606 }
2607
2608 // remove all the tracks that need to be...
2609 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002610 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 for (size_t i=0 ; i<count ; i++) {
2612 const sp<Track>& track = tracksToRemove->itemAt(i);
2613 mActiveTracks.remove(track);
2614 if (track->mainBuffer() != mMixBuffer) {
2615 chain = getEffectChain_l(track->sessionId());
2616 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002617 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002618 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 }
2620 }
2621 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002622 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 }
2624 }
2625 }
2626
2627 // mix buffer must be cleared if all tracks are connected to an
2628 // effect chain as in this case the mixer will not write to
2629 // mix buffer and track effects will accumulate into it
2630 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2631 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2632 }
2633
2634 return mixerStatus;
2635}
2636
Glenn Kasten66fcab92012-02-24 14:59:21 -08002637/*
2638The derived values that are cached:
2639 - mixBufferSize from frame count * frame size
2640 - activeSleepTime from activeSleepTimeUs()
2641 - idleSleepTime from idleSleepTimeUs()
2642 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2643 - maxPeriod from frame count and sample rate (MIXER only)
2644
2645The parameters that affect these derived values are:
2646 - frame count
2647 - frame size
2648 - sample rate
2649 - device type: A2DP or not
2650 - device latency
2651 - format: PCM or not
2652 - active sleep time
2653 - idle sleep time
2654*/
2655
2656void AudioFlinger::PlaybackThread::cacheParameters_l()
2657{
2658 mixBufferSize = mFrameCount * mFrameSize;
2659 activeSleepTime = activeSleepTimeUs();
2660 idleSleepTime = idleSleepTimeUs();
2661}
2662
Glenn Kastenfff6d712012-01-12 16:38:12 -08002663void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664{
Steve Block3856b092011-10-20 11:56:00 +01002665 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002666 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002668
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 size_t size = mTracks.size();
2670 for (size_t i = 0; i < size; i++) {
2671 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002672 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002673 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 }
2676 }
2677}
2678
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002680int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07002682 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683}
2684
2685// deleteTrackName_l() must be called with ThreadBase::mLock held
2686void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2687{
Steve Block3856b092011-10-20 11:56:00 +01002688 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 mAudioMixer->deleteTrackName(name);
2690}
2691
2692// checkForNewParameters_l() must be called with ThreadBase::mLock held
2693bool AudioFlinger::MixerThread::checkForNewParameters_l()
2694{
2695 bool reconfig = false;
2696
2697 while (!mNewParameters.isEmpty()) {
2698 status_t status = NO_ERROR;
2699 String8 keyValuePair = mNewParameters[0];
2700 AudioParameter param = AudioParameter(keyValuePair);
2701 int value;
2702
2703 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2704 reconfig = true;
2705 }
2706 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002707 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 status = BAD_VALUE;
2709 } else {
2710 reconfig = true;
2711 }
2712 }
2713 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002714 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 status = BAD_VALUE;
2716 } else {
2717 reconfig = true;
2718 }
2719 }
2720 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2721 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002722 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 // if frame count is changed after track creation
2724 if (!mTracks.isEmpty()) {
2725 status = INVALID_OPERATION;
2726 } else {
2727 reconfig = true;
2728 }
2729 }
2730 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002731#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08002732 // when changing the audio output device, call addBatteryData to notify
2733 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002734 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002735 uint32_t params = 0;
2736 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002737 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002738 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2739 }
2740
2741 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002742 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002743 // check if any other device (except speaker) is on
2744 if (value & deviceWithoutSpeaker ) {
2745 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2746 }
2747
2748 if (params != 0) {
2749 addBatteryData(params);
2750 }
2751 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07002752#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08002753
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 // forward device change to effects that have requested to be
2755 // aware of attached audio device.
2756 mDevice = (uint32_t)value;
2757 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002758 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 }
2760 }
2761
2762 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002763 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002764 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002766 mOutput->stream->common.standby(&mOutput->stream->common);
2767 mStandby = true;
2768 mBytesWritten = 0;
2769 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002770 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 }
2772 if (status == NO_ERROR && reconfig) {
2773 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002774 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2775 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 readOutputParameters();
2777 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2778 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07002779 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 if (name < 0) break;
2781 mTracks[i]->mName = name;
2782 // limit track sample rate to 2 x new output sample rate
2783 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2784 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2785 }
2786 }
2787 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2788 }
2789 }
2790
2791 mNewParameters.removeAt(0);
2792
2793 mParamStatus = status;
2794 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002795 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2796 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002797 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
2799 return reconfig;
2800}
2801
2802status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2803{
2804 const size_t SIZE = 256;
2805 char buffer[SIZE];
2806 String8 result;
2807
2808 PlaybackThread::dumpInternals(fd, args);
2809
2810 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2811 result.append(buffer);
2812 write(fd, result.string(), result.size());
2813 return NO_ERROR;
2814}
2815
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002816uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817{
Eric Laurent60e18242010-07-29 06:50:24 -07002818 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819}
2820
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002821uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002822{
2823 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2824}
2825
Glenn Kasten66fcab92012-02-24 14:59:21 -08002826void AudioFlinger::MixerThread::cacheParameters_l()
2827{
2828 PlaybackThread::cacheParameters_l();
2829
2830 // FIXME: Relaxed timing because of a certain device that can't meet latency
2831 // Should be reduced to 2x after the vendor fixes the driver issue
2832 // increase threshold again due to low power audio mode. The way this warning
2833 // threshold is calculated and its usefulness should be reconsidered anyway.
2834 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
2835}
2836
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002838AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2839 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002840 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002841 // mLeftVolFloat, mRightVolFloat
2842 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844}
2845
2846AudioFlinger::DirectOutputThread::~DirectOutputThread()
2847{
2848}
2849
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002850AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
2851 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08002852)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002854 sp<Track> trackToRemove;
2855
Glenn Kastenfec279f2012-03-08 07:47:15 -08002856 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857
Glenn Kasten952eeb22012-03-06 11:30:57 -08002858 // find out which tracks need to be processed
2859 if (mActiveTracks.size() != 0) {
2860 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08002861 // The track died recently
2862 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 Track* const track = t.get();
2865 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866
Glenn Kasten952eeb22012-03-06 11:30:57 -08002867 // The first time a track is added we wait
2868 // for all its buffers to be filled before processing it
2869 if (cblk->framesReady() && track->isReady() &&
2870 !track->isPaused() && !track->isTerminated())
2871 {
2872 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 if (track->mFillingUpStatus == Track::FS_FILLED) {
2875 track->mFillingUpStatus = Track::FS_ACTIVE;
2876 mLeftVolFloat = mRightVolFloat = 0;
2877 mLeftVolShort = mRightVolShort = 0;
2878 if (track->mState == TrackBase::RESUMING) {
2879 track->mState = TrackBase::ACTIVE;
2880 rampVolume = true;
2881 }
2882 } else if (cblk->server != 0) {
2883 // If the track is stopped before the first frame was mixed,
2884 // do not apply ramp
2885 rampVolume = true;
2886 }
2887 // compute volume for this track
2888 float left, right;
2889 if (track->isMuted() || mMasterMute || track->isPausing() ||
2890 mStreamTypes[track->streamType()].mute) {
2891 left = right = 0;
2892 if (track->isPausing()) {
2893 track->setPaused();
2894 }
2895 } else {
2896 float typeVolume = mStreamTypes[track->streamType()].volume;
2897 float v = mMasterVolume * typeVolume;
2898 uint32_t vlr = cblk->getVolumeLR();
2899 float v_clamped = v * (vlr & 0xFFFF);
2900 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2901 left = v_clamped/MAX_GAIN;
2902 v_clamped = v * (vlr >> 16);
2903 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2904 right = v_clamped/MAX_GAIN;
2905 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906
Glenn Kasten952eeb22012-03-06 11:30:57 -08002907 if (left != mLeftVolFloat || right != mRightVolFloat) {
2908 mLeftVolFloat = left;
2909 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910
Glenn Kasten952eeb22012-03-06 11:30:57 -08002911 // If audio HAL implements volume control,
2912 // force software volume to nominal value
2913 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2914 left = 1.0f;
2915 right = 1.0f;
2916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917
Glenn Kasten952eeb22012-03-06 11:30:57 -08002918 // Convert volumes from float to 8.24
2919 uint32_t vl = (uint32_t)(left * (1 << 24));
2920 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921
Glenn Kasten952eeb22012-03-06 11:30:57 -08002922 // Delegate volume control to effect in track effect chain if needed
2923 // only one effect chain can be present on DirectOutputThread, so if
2924 // there is one, the track is connected to it
2925 if (!mEffectChains.isEmpty()) {
2926 // Do not ramp volume if volume is controlled by effect
2927 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928 rampVolume = false;
2929 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931
Glenn Kasten952eeb22012-03-06 11:30:57 -08002932 // Convert volumes from 8.24 to 4.12 format
2933 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2934 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2935 leftVol = (uint16_t)v_clamped;
2936 v_clamped = (vr + (1 << 11)) >> 12;
2937 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2938 rightVol = (uint16_t)v_clamped;
2939 } else {
2940 leftVol = mLeftVolShort;
2941 rightVol = mRightVolShort;
2942 rampVolume = false;
2943 }
2944
2945 // reset retry count
2946 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08002947 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002948 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002949 } else {
2950 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2951 if (track->isStopped()) {
2952 track->reset();
2953 }
2954 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2955 // We have consumed all the buffers of this track.
2956 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002957 // TODO: implement behavior for compressed audio
2958 size_t audioHALFrames =
2959 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2960 size_t framesWritten =
2961 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2962 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2963 trackToRemove = track;
2964 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002965 } else {
2966 // No buffers for this track. Give it a few chances to
2967 // fill a buffer, then remove it from active list.
2968 if (--(track->mRetryCount) <= 0) {
2969 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2970 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002972 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 }
2974 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002975 }
2976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002978 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08002979 // remove all the tracks that need to be...
2980 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002981 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002982 mActiveTracks.remove(trackToRemove);
2983 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002984 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08002985 trackToRemove->sessionId());
2986 mEffectChains[0]->decActiveTrackCnt();
2987 }
2988 if (trackToRemove->isTerminated()) {
2989 removeTrack_l(trackToRemove);
2990 }
2991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992
Glenn Kastenfec279f2012-03-08 07:47:15 -08002993 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002994}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995
Glenn Kasten000f0e32012-03-01 17:10:56 -08002996void AudioFlinger::DirectOutputThread::threadLoop_mix()
2997{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002998 AudioBufferProvider::Buffer buffer;
2999 size_t frameCount = mFrameCount;
3000 int8_t *curBuf = (int8_t *)mMixBuffer;
3001 // output audio to hardware
3002 while (frameCount) {
3003 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003004 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003005 if (CC_UNLIKELY(buffer.raw == NULL)) {
3006 memset(curBuf, 0, frameCount * mFrameSize);
3007 break;
3008 }
3009 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3010 frameCount -= buffer.frameCount;
3011 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003012 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003013 }
3014 sleepTime = 0;
3015 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003016 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003017
3018 // apply volume
3019
3020 // Do not apply volume on compressed audio
3021 if (!audio_is_linear_pcm(mFormat)) {
3022 return;
3023 }
3024
3025 // convert to signed 16 bit before volume calculation
3026 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3027 size_t count = mFrameCount * mChannelCount;
3028 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3029 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003030 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003031 *dst-- = (int16_t)(*src--^0x80) << 8;
3032 }
3033 }
3034
3035 frameCount = mFrameCount;
3036 int16_t *out = mMixBuffer;
3037 if (rampVolume) {
3038 if (mChannelCount == 1) {
3039 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3040 int32_t vlInc = d / (int32_t)frameCount;
3041 int32_t vl = ((int32_t)mLeftVolShort << 16);
3042 do {
3043 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3044 out++;
3045 vl += vlInc;
3046 } while (--frameCount);
3047
3048 } else {
3049 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3050 int32_t vlInc = d / (int32_t)frameCount;
3051 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3052 int32_t vrInc = d / (int32_t)frameCount;
3053 int32_t vl = ((int32_t)mLeftVolShort << 16);
3054 int32_t vr = ((int32_t)mRightVolShort << 16);
3055 do {
3056 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3057 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3058 out += 2;
3059 vl += vlInc;
3060 vr += vrInc;
3061 } while (--frameCount);
3062 }
3063 } else {
3064 if (mChannelCount == 1) {
3065 do {
3066 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3067 out++;
3068 } while (--frameCount);
3069 } else {
3070 do {
3071 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3072 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3073 out += 2;
3074 } while (--frameCount);
3075 }
3076 }
3077
3078 // convert back to unsigned 8 bit after volume calculation
3079 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3080 size_t count = mFrameCount * mChannelCount;
3081 int16_t *src = mMixBuffer;
3082 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003083 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003084 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3085 }
3086 }
3087
3088 mLeftVolShort = leftVol;
3089 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003090}
3091
3092void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3093{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003094 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003095 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003096 sleepTime = activeSleepTime;
3097 } else {
3098 sleepTime = idleSleepTime;
3099 }
3100 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3101 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
3102 sleepTime = 0;
3103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104}
3105
3106// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003107int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108{
3109 return 0;
3110}
3111
3112// deleteTrackName_l() must be called with ThreadBase::mLock held
3113void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3114{
3115}
3116
3117// checkForNewParameters_l() must be called with ThreadBase::mLock held
3118bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3119{
3120 bool reconfig = false;
3121
3122 while (!mNewParameters.isEmpty()) {
3123 status_t status = NO_ERROR;
3124 String8 keyValuePair = mNewParameters[0];
3125 AudioParameter param = AudioParameter(keyValuePair);
3126 int value;
3127
3128 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3129 // do not accept frame count changes if tracks are open as the track buffer
3130 // size depends on frame count and correct behavior would not be garantied
3131 // if frame count is changed after track creation
3132 if (!mTracks.isEmpty()) {
3133 status = INVALID_OPERATION;
3134 } else {
3135 reconfig = true;
3136 }
3137 }
3138 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003139 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003140 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003142 mOutput->stream->common.standby(&mOutput->stream->common);
3143 mStandby = true;
3144 mBytesWritten = 0;
3145 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003146 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
3148 if (status == NO_ERROR && reconfig) {
3149 readOutputParameters();
3150 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3151 }
3152 }
3153
3154 mNewParameters.removeAt(0);
3155
3156 mParamStatus = status;
3157 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003158 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3159 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003160 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 }
3162 return reconfig;
3163}
3164
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003165uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166{
3167 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003168 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003169 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 } else {
3171 time = 10000;
3172 }
3173 return time;
3174}
3175
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003176uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177{
3178 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003179 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003180 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 } else {
3182 time = 10000;
3183 }
3184 return time;
3185}
3186
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003187uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003188{
3189 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003190 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003191 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3192 } else {
3193 time = 10000;
3194 }
3195 return time;
3196}
3197
Glenn Kasten66fcab92012-02-24 14:59:21 -08003198void AudioFlinger::DirectOutputThread::cacheParameters_l()
3199{
3200 PlaybackThread::cacheParameters_l();
3201
3202 // use shorter standby delay as on normal output to release
3203 // hardware resources as soon as possible
3204 standbyDelay = microseconds(activeSleepTime*2);
3205}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003206
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207// ----------------------------------------------------------------------------
3208
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003209AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003210 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003211 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3212 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 addOutputTrack(mainThread);
3215}
3216
3217AudioFlinger::DuplicatingThread::~DuplicatingThread()
3218{
3219 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3220 mOutputTracks[i]->destroy();
3221 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222}
3223
Glenn Kasten000f0e32012-03-01 17:10:56 -08003224void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003226 // mix buffers...
3227 if (outputsReady(outputTracks)) {
3228 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3229 } else {
3230 memset(mMixBuffer, 0, mixBufferSize);
3231 }
3232 sleepTime = 0;
3233 writeFrames = mFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003234}
3235
3236void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3237{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003238 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003239 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003240 sleepTime = activeSleepTime;
3241 } else {
3242 sleepTime = idleSleepTime;
3243 }
3244 } else if (mBytesWritten != 0) {
3245 // flush remaining overflow buffers in output tracks
3246 for (size_t i = 0; i < outputTracks.size(); i++) {
3247 if (outputTracks[i]->isActive()) {
3248 sleepTime = 0;
3249 writeFrames = 0;
3250 memset(mMixBuffer, 0, mixBufferSize);
3251 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003253 }
3254 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003255}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256
Glenn Kasten000f0e32012-03-01 17:10:56 -08003257void AudioFlinger::DuplicatingThread::threadLoop_write()
3258{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003259 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003260 for (size_t i = 0; i < outputTracks.size(); i++) {
3261 outputTracks[i]->write(mMixBuffer, writeFrames);
3262 }
3263 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003264}
Glenn Kasten688a6402012-02-29 07:57:06 -08003265
Glenn Kasten000f0e32012-03-01 17:10:56 -08003266void AudioFlinger::DuplicatingThread::threadLoop_standby()
3267{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003268 // DuplicatingThread implements standby by stopping all tracks
3269 for (size_t i = 0; i < outputTracks.size(); i++) {
3270 outputTracks[i]->stop();
3271 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272}
3273
Glenn Kastenfa26a852012-03-06 11:28:04 -08003274void AudioFlinger::DuplicatingThread::saveOutputTracks()
3275{
3276 outputTracks = mOutputTracks;
3277}
3278
3279void AudioFlinger::DuplicatingThread::clearOutputTracks()
3280{
3281 outputTracks.clear();
3282}
3283
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3285{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003286 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003287 // FIXME explain this formula
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003289 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 this,
3291 mSampleRate,
3292 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003293 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 frameCount);
3295 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003296 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003298 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003299 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 }
3301}
3302
3303void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3304{
3305 Mutex::Autolock _l(mLock);
3306 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003307 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 mOutputTracks[i]->destroy();
3309 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003310 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 return;
3312 }
3313 }
Steve Block3856b092011-10-20 11:56:00 +01003314 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315}
3316
Glenn Kasten438b0362012-03-06 11:24:48 -08003317// caller must hold mLock
3318void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319{
3320 mWaitTimeMs = UINT_MAX;
3321 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3322 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003323 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003324 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3325 if (waitTimeMs < mWaitTimeMs) {
3326 mWaitTimeMs = waitTimeMs;
3327 }
3328 }
3329 }
3330}
3331
3332
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003333bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334{
3335 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003336 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003338 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 return false;
3340 }
3341 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3342 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003343 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 return false;
3345 }
3346 }
3347 return true;
3348}
3349
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003350uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351{
3352 return (mWaitTimeMs * 1000) / 2;
3353}
3354
Glenn Kasten66fcab92012-02-24 14:59:21 -08003355void AudioFlinger::DuplicatingThread::cacheParameters_l()
3356{
3357 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3358 updateWaitTime_l();
3359
3360 MixerThread::cacheParameters_l();
3361}
3362
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363// ----------------------------------------------------------------------------
3364
3365// TrackBase constructor must be called with AudioFlinger::mLock held
3366AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003367 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 const sp<Client>& client,
3369 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003370 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003371 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 const sp<IMemory>& sharedBuffer,
3374 int sessionId)
3375 : RefBase(),
3376 mThread(thread),
3377 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003378 mCblk(NULL),
3379 // mBuffer
3380 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 mFrameCount(0),
3382 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003384 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003386 // mChannelCount
3387 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388{
Steve Block3856b092011-10-20 11:56:00 +01003389 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390
Steve Blockb8a80522011-12-20 16:23:08 +00003391 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003392 size_t size = sizeof(audio_track_cblk_t);
3393 uint8_t channelCount = popcount(channelMask);
3394 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3395 if (sharedBuffer == 0) {
3396 size += bufferSize;
3397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003399 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 mCblkMemory = client->heap()->allocate(size);
3401 if (mCblkMemory != 0) {
3402 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003403 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 new(mCblk) audio_track_cblk_t();
3405 // clear all buffers
3406 mCblk->frameCount = frameCount;
3407 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003408// uncomment the following lines to quickly test 32-bit wraparound
3409// mCblk->user = 0xffff0000;
3410// mCblk->server = 0xffff0000;
3411// mCblk->userBase = 0xffff0000;
3412// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003413 mChannelCount = channelCount;
3414 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 if (sharedBuffer == 0) {
3416 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3417 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3418 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003419 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 mCblk->flags = CBLK_UNDERRUN_ON;
3421 } else {
3422 mBuffer = sharedBuffer->pointer();
3423 }
3424 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3425 }
3426 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003427 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 client->heap()->dump("AudioTrack");
3429 return;
3430 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003431 } else {
3432 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003433 // construct the shared structure in-place.
3434 new(mCblk) audio_track_cblk_t();
3435 // clear all buffers
3436 mCblk->frameCount = frameCount;
3437 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003438// uncomment the following lines to quickly test 32-bit wraparound
3439// mCblk->user = 0xffff0000;
3440// mCblk->server = 0xffff0000;
3441// mCblk->userBase = 0xffff0000;
3442// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003443 mChannelCount = channelCount;
3444 mChannelMask = channelMask;
3445 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3446 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3447 // Force underrun condition to avoid false underrun callback until first data is
3448 // written to buffer (other flags are cleared)
3449 mCblk->flags = CBLK_UNDERRUN_ON;
3450 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452}
3453
3454AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3455{
Glenn Kastena0d68332012-01-27 16:47:15 -08003456 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003457 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003459 } else {
3460 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 }
3462 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003463 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003464 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003465 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003467 // If the client's reference count drops to zero, the associated destructor
3468 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3469 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 mClient.clear();
3471 }
3472}
3473
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003474// AudioBufferProvider interface
3475// getNextBuffer() = 0;
3476// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3478{
Glenn Kastene0feee32011-12-13 11:53:26 -08003479 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003481 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 buffer->frameCount = 0;
3483}
3484
3485bool AudioFlinger::ThreadBase::TrackBase::step() {
3486 bool result;
3487 audio_track_cblk_t* cblk = this->cblk();
3488
3489 result = cblk->stepServer(mFrameCount);
3490 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003491 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003492 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 }
3494 return result;
3495}
3496
3497void AudioFlinger::ThreadBase::TrackBase::reset() {
3498 audio_track_cblk_t* cblk = this->cblk();
3499
3500 cblk->user = 0;
3501 cblk->server = 0;
3502 cblk->userBase = 0;
3503 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003504 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003505 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506}
3507
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3509 return (int)mCblk->sampleRate;
3510}
3511
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3513 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003514 size_t frameSize = cblk->frameSize;
3515 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3516 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517
3518 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003519 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3520 "TrackBase::getBuffer buffer out of range:\n"
3521 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3522 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003524 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525
3526 return bufferStart;
3527}
3528
Eric Laurenta011e352012-03-29 15:51:43 -07003529status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3530{
3531 mSyncEvents.add(event);
3532 return NO_ERROR;
3533}
3534
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535// ----------------------------------------------------------------------------
3536
3537// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3538AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003539 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003541 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003543 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003544 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 int frameCount,
3546 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003547 int sessionId,
3548 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003549 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003550 mMute(false),
3551 // mFillingUpStatus ?
3552 // mRetryCount initialized later when needed
3553 mSharedBuffer(sharedBuffer),
3554 mStreamType(streamType),
3555 mName(-1), // see note below
3556 mMainBuffer(thread->mixBuffer()),
3557 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003558 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003559 mPresentationCompleteFrames(0),
3560 mFlags(flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561{
3562 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3564 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003565 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kastenf9959012012-03-19 11:14:37 -07003566 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003567 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07003568 if (mName < 0) {
3569 ALOGE("no more track names available");
3570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003572 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573}
3574
3575AudioFlinger::PlaybackThread::Track::~Track()
3576{
Steve Block3856b092011-10-20 11:56:00 +01003577 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 sp<ThreadBase> thread = mThread.promote();
3579 if (thread != 0) {
3580 Mutex::Autolock _l(thread->mLock);
3581 mState = TERMINATED;
3582 }
3583}
3584
3585void AudioFlinger::PlaybackThread::Track::destroy()
3586{
3587 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3588 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08003589 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 // we must acquire a strong reference on this Track before locking mLock
3591 // here so that the destructor is called only when exiting this function.
3592 // On the other hand, as long as Track::destroy() is only called by
3593 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3594 // this Track with its member mTrack.
3595 sp<Track> keep(this);
3596 { // scope for mLock
3597 sp<ThreadBase> thread = mThread.promote();
3598 if (thread != 0) {
3599 if (!isOutputTrack()) {
3600 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003601 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003602
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003603#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003604 // to track the speaker usage
3605 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003606#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 }
3608 AudioSystem::releaseOutput(thread->id());
3609 }
3610 Mutex::Autolock _l(thread->mLock);
3611 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3612 playbackThread->destroyTrack_l(this);
3613 }
3614 }
3615}
3616
3617void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3618{
Glenn Kasten83d86532012-01-17 14:39:34 -08003619 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003620 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 -07003621 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003622 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 mStreamType,
3624 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003625 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626 mSessionId,
3627 mFrameCount,
3628 mState,
3629 mMute,
3630 mFillingUpStatus,
3631 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003632 vlr & 0xFFFF,
3633 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 mCblk->server,
3635 mCblk->user,
3636 (int)mMainBuffer,
3637 (int)mAuxBuffer);
3638}
3639
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003640// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08003641status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003642 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003644 audio_track_cblk_t* cblk = this->cblk();
3645 uint32_t framesReady;
3646 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003648 // Check if last stepServer failed, try to step now
3649 if (mStepServerFailed) {
3650 if (!step()) goto getNextBuffer_exit;
3651 ALOGV("stepServer recovered");
3652 mStepServerFailed = false;
3653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003655 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003657 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658 uint32_t s = cblk->server;
3659 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3660
3661 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3662 if (framesReq > framesReady) {
3663 framesReq = framesReady;
3664 }
Marco Nelissena1472d92012-03-30 14:36:54 -07003665 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 framesReq = bufferEnd - s;
3667 }
3668
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003669 buffer->raw = getBuffer(s, framesReq);
3670 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003672 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675
3676getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003677 buffer->raw = NULL;
3678 buffer->frameCount = 0;
3679 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3680 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681}
3682
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003683uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08003684 return mCblk->framesReady();
3685}
3686
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003688 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689
John Grossman4ff14ba2012-02-08 16:37:41 -08003690 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3692 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003693 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 return true;
3695 }
3696 return false;
3697}
3698
Glenn Kasten3acbd052012-02-28 10:39:56 -08003699status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07003700 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701{
3702 status_t status = NO_ERROR;
Glenn Kasten3acbd052012-02-28 10:39:56 -08003703
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++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004003 int64_t bufEnd;
4004
John Grossmanc95cfbb2012-04-12 11:53:11 -07004005 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4006 // We have a next buffer. Just use its PTS as the PTS of the frame
4007 // following the last frame in this buffer. If the stream is sparse
4008 // (ie, there are deliberate gaps left in the stream which should be
4009 // filled with silence by the TimedAudioTrack), then this can result
4010 // in one extra buffer being left un-trimmed when it could have
4011 // been. In general, this is not typical, and we would rather
4012 // optimized away the TS calculation below for the more common case
4013 // where PTSes are contiguous.
4014 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4015 } else {
4016 // We have no next buffer. Compute the PTS of the frame following
4017 // the last frame in this buffer by computing the duration of of
4018 // this frame in media time units and adding it to the PTS of the
4019 // buffer.
4020 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4021 / mCblk->frameSize;
4022
4023 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4024 &bufEnd)) {
4025 ALOGE("Failed to convert frame count of %lld to media time"
4026 " duration" " (scale factor %d/%u) in %s",
4027 frameCount,
4028 mMediaTimeToSampleTransform.a_to_b_numer,
4029 mMediaTimeToSampleTransform.a_to_b_denom,
4030 __PRETTY_FUNCTION__);
4031 break;
4032 }
4033 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004034 }
John Grossman9fbdee12012-03-26 17:51:46 -07004035
4036 if (bufEnd > mediaTimeNow)
4037 break;
4038
4039 // Is the buffer we want to use in the middle of a mix operation right
4040 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4041 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004042 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004043 mTrimQueueHeadOnRelease = true;
4044 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004045 }
4046
John Grossman9fbdee12012-03-26 17:51:46 -07004047 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004048 if (trimStart < trimEnd) {
4049 // Update the bookkeeping for framesReady()
4050 for (size_t i = trimStart; i < trimEnd; ++i) {
4051 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4052 }
4053
4054 // Now actually remove the buffers from the queue.
4055 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004056 }
4057}
4058
John Grossman1c345192012-03-27 14:00:17 -07004059void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4060 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004061 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4062 "%s called (reason \"%s\"), but timed buffer queue has no"
4063 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004064
4065 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4066 mTimedBufferQueue.removeAt(0);
4067}
4068
4069void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4070 const TimedBuffer& buf,
4071 const char* logTag) {
4072 uint32_t bufBytes = buf.buffer()->size();
4073 uint32_t consumedAlready = buf.position();
4074
Eric Laurentb388e532012-04-14 13:32:48 -07004075 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004076 "Bad bookkeeping while updating frames pending. Timed buffer is"
4077 " only %u bytes long, but claims to have consumed %u"
4078 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004079 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004080
4081 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004082 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4083 "Bad bookkeeping while updating frames pending. Should have at"
4084 " least %u queued frames, but we think we have only %u. (update"
4085 " reason: \"%s\")",
4086 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004087
4088 mFramesPendingInQueue -= bufFrames;
4089}
4090
John Grossman4ff14ba2012-02-08 16:37:41 -08004091status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4092 const sp<IMemory>& buffer, int64_t pts) {
4093
4094 {
4095 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4096 if (!mMediaTimeTransformValid)
4097 return INVALID_OPERATION;
4098 }
4099
4100 Mutex::Autolock _l(mTimedBufferQueueLock);
4101
John Grossman1c345192012-03-27 14:00:17 -07004102 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4103 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004104 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4105
4106 return NO_ERROR;
4107}
4108
4109status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4110 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4111
John Grossman1c345192012-03-27 14:00:17 -07004112 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4113 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4114 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004115
4116 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4117 target == TimedAudioTrack::COMMON_TIME)) {
4118 return BAD_VALUE;
4119 }
4120
4121 Mutex::Autolock lock(mMediaTimeTransformLock);
4122 mMediaTimeTransform = xform;
4123 mMediaTimeTransformTarget = target;
4124 mMediaTimeTransformValid = true;
4125
4126 return NO_ERROR;
4127}
4128
4129#define min(a, b) ((a) < (b) ? (a) : (b))
4130
4131// implementation of getNextBuffer for tracks whose buffers have timestamps
4132status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4133 AudioBufferProvider::Buffer* buffer, int64_t pts)
4134{
4135 if (pts == AudioBufferProvider::kInvalidPTS) {
4136 buffer->raw = 0;
4137 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004138 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004139 return INVALID_OPERATION;
4140 }
4141
John Grossman4ff14ba2012-02-08 16:37:41 -08004142 Mutex::Autolock _l(mTimedBufferQueueLock);
4143
John Grossman9fbdee12012-03-26 17:51:46 -07004144 ALOG_ASSERT(!mQueueHeadInFlight,
4145 "getNextBuffer called without releaseBuffer!");
4146
John Grossman4ff14ba2012-02-08 16:37:41 -08004147 while (true) {
4148
4149 // if we have no timed buffers, then fail
4150 if (mTimedBufferQueue.isEmpty()) {
4151 buffer->raw = 0;
4152 buffer->frameCount = 0;
4153 return NOT_ENOUGH_DATA;
4154 }
4155
4156 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4157
4158 // calculate the PTS of the head of the timed buffer queue expressed in
4159 // local time
4160 int64_t headLocalPTS;
4161 {
4162 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4163
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004164 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004165
4166 if (mMediaTimeTransform.a_to_b_denom == 0) {
4167 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004168 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004169 return NO_ERROR;
4170 }
4171
4172 int64_t transformedPTS;
4173 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4174 &transformedPTS)) {
4175 // the transform failed. this shouldn't happen, but if it does
4176 // then just drop this buffer
4177 ALOGW("timedGetNextBuffer transform failed");
4178 buffer->raw = 0;
4179 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004180 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004181 return NO_ERROR;
4182 }
4183
4184 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4185 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4186 &headLocalPTS)) {
4187 buffer->raw = 0;
4188 buffer->frameCount = 0;
4189 return INVALID_OPERATION;
4190 }
4191 } else {
4192 headLocalPTS = transformedPTS;
4193 }
4194 }
4195
4196 // adjust the head buffer's PTS to reflect the portion of the head buffer
4197 // that has already been consumed
4198 int64_t effectivePTS = headLocalPTS +
4199 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4200
4201 // Calculate the delta in samples between the head of the input buffer
4202 // queue and the start of the next output buffer that will be written.
4203 // If the transformation fails because of over or underflow, it means
4204 // that the sample's position in the output stream is so far out of
4205 // whack that it should just be dropped.
4206 int64_t sampleDelta;
4207 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4208 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004209 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4210 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004211 continue;
4212 }
4213 if (!mLocalTimeToSampleTransform.doForwardTransform(
4214 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004215 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004216 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004217 continue;
4218 }
4219
John Grossman1c345192012-03-27 14:00:17 -07004220 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4221 " sampleDelta=[%d.%08x]",
4222 head.pts(), head.position(), pts,
4223 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4224 + (sampleDelta >> 32)),
4225 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004226
4227 // if the delta between the ideal placement for the next input sample and
4228 // the current output position is within this threshold, then we will
4229 // concatenate the next input samples to the previous output
4230 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004231 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004232
4233 // if this is the first buffer of audio that we're emitting from this track
4234 // then it should be almost exactly on time.
4235 const int64_t kSampleStartupThreshold = 1LL << 32;
4236
4237 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004238 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004239 // the next input is close enough to being on time, so concatenate it
4240 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004241 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004242
John Grossman1c345192012-03-27 14:00:17 -07004243 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4244 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004245 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004246 }
4247
4248 // Looks like our output is not on time. Reset our on timed status.
4249 // Next time we mix samples from our input queue, then should be within
4250 // the StartupThreshold.
4251 mTimedAudioOutputOnTime = false;
4252 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004253 // the gap between the current output position and the proper start of
4254 // the next input sample is too big, so fill it with silence
4255 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4256
John Grossman9fbdee12012-03-26 17:51:46 -07004257 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004258 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4259 return NO_ERROR;
4260 } else {
4261 // the next input sample is late
4262 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4263 size_t onTimeSamplePosition =
4264 head.position() + lateFrames * mCblk->frameSize;
4265
4266 if (onTimeSamplePosition > head.buffer()->size()) {
4267 // all the remaining samples in the head are too late, so
4268 // drop it and move on
4269 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004270 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004271 continue;
4272 } else {
4273 // skip over the late samples
4274 head.setPosition(onTimeSamplePosition);
4275
4276 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004277 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004278
4279 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4280 return NO_ERROR;
4281 }
4282 }
4283 }
4284}
4285
4286// Yield samples from the timed buffer queue head up to the given output
4287// buffer's capacity.
4288//
4289// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004290void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004291 AudioBufferProvider::Buffer* buffer) {
4292
4293 const TimedBuffer& head = mTimedBufferQueue[0];
4294
4295 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4296 head.position());
4297
4298 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4299 mCblk->frameSize);
4300 size_t framesRequested = buffer->frameCount;
4301 buffer->frameCount = min(framesLeftInHead, framesRequested);
4302
John Grossman9fbdee12012-03-26 17:51:46 -07004303 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004304 mTimedAudioOutputOnTime = true;
4305}
4306
4307// Yield samples of silence up to the given output buffer's capacity
4308//
4309// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004310void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004311 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4312
4313 // lazily allocate a buffer filled with silence
4314 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4315 delete [] mTimedSilenceBuffer;
4316 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4317 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4318 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4319 }
4320
4321 buffer->raw = mTimedSilenceBuffer;
4322 size_t framesRequested = buffer->frameCount;
4323 buffer->frameCount = min(numFrames, framesRequested);
4324
4325 mTimedAudioOutputOnTime = false;
4326}
4327
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004328// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004329void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4330 AudioBufferProvider::Buffer* buffer) {
4331
4332 Mutex::Autolock _l(mTimedBufferQueueLock);
4333
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004334 // If the buffer which was just released is part of the buffer at the head
4335 // of the queue, be sure to update the amt of the buffer which has been
4336 // consumed. If the buffer being returned is not part of the head of the
4337 // queue, its either because the buffer is part of the silence buffer, or
4338 // because the head of the timed queue was trimmed after the mixer called
4339 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004340 if (buffer->raw == mTimedSilenceBuffer) {
4341 ALOG_ASSERT(!mQueueHeadInFlight,
4342 "Queue head in flight during release of silence buffer!");
4343 goto done;
4344 }
4345
4346 ALOG_ASSERT(mQueueHeadInFlight,
4347 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4348 " head in flight.");
4349
4350 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004351 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004352
4353 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004354 void* end = reinterpret_cast<void*>(
4355 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4356 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004357
John Grossman9fbdee12012-03-26 17:51:46 -07004358 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4359 "released buffer not within the head of the timed buffer"
4360 " queue; qHead = [%p, %p], released buffer = %p",
4361 start, end, buffer->raw);
4362
4363 head.setPosition(head.position() +
4364 (buffer->frameCount * mCblk->frameSize));
4365 mQueueHeadInFlight = false;
4366
John Grossman1c345192012-03-27 14:00:17 -07004367 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4368 "Bad bookkeeping during releaseBuffer! Should have at"
4369 " least %u queued frames, but we think we have only %u",
4370 buffer->frameCount, mFramesPendingInQueue);
4371
4372 mFramesPendingInQueue -= buffer->frameCount;
4373
John Grossman9fbdee12012-03-26 17:51:46 -07004374 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4375 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004376 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004377 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004378 }
John Grossman9fbdee12012-03-26 17:51:46 -07004379 } else {
4380 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4381 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004382 }
4383
John Grossman9fbdee12012-03-26 17:51:46 -07004384done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004385 buffer->raw = 0;
4386 buffer->frameCount = 0;
4387}
4388
4389uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4390 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004391 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004392}
4393
4394AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4395 : mPTS(0), mPosition(0) {}
4396
4397AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4398 const sp<IMemory>& buffer, int64_t pts)
4399 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4400
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401// ----------------------------------------------------------------------------
4402
4403// RecordTrack constructor must be called with AudioFlinger::mLock held
4404AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004405 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 const sp<Client>& client,
4407 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004408 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004409 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 int sessionId)
4412 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004413 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004414 mOverflow(false)
4415{
4416 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004417 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4418 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4419 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4420 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4421 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4422 } else {
4423 mCblk->frameSize = sizeof(int8_t);
4424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 }
4426}
4427
4428AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4429{
4430 sp<ThreadBase> thread = mThread.promote();
4431 if (thread != 0) {
4432 AudioSystem::releaseInput(thread->id());
4433 }
4434}
4435
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004436// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004437status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438{
4439 audio_track_cblk_t* cblk = this->cblk();
4440 uint32_t framesAvail;
4441 uint32_t framesReq = buffer->frameCount;
4442
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004443 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004444 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004446 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004447 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 }
4449
4450 framesAvail = cblk->framesAvailable_l();
4451
Glenn Kastenf6b16782011-12-15 09:51:17 -08004452 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 uint32_t s = cblk->server;
4454 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4455
4456 if (framesReq > framesAvail) {
4457 framesReq = framesAvail;
4458 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004459 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 framesReq = bufferEnd - s;
4461 }
4462
4463 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004464 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465
4466 buffer->frameCount = framesReq;
4467 return NO_ERROR;
4468 }
4469
4470getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004471 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 buffer->frameCount = 0;
4473 return NOT_ENOUGH_DATA;
4474}
4475
Glenn Kasten3acbd052012-02-28 10:39:56 -08004476status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004477 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478{
4479 sp<ThreadBase> thread = mThread.promote();
4480 if (thread != 0) {
4481 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004482 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 } else {
4484 return BAD_VALUE;
4485 }
4486}
4487
4488void AudioFlinger::RecordThread::RecordTrack::stop()
4489{
4490 sp<ThreadBase> thread = mThread.promote();
4491 if (thread != 0) {
4492 RecordThread *recordThread = (RecordThread *)thread.get();
4493 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004494 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004495 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004496 // read from buffer
4497 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 }
4499}
4500
4501void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4502{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004503 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004504 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004506 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507 mSessionId,
4508 mFrameCount,
4509 mState,
4510 mCblk->sampleRate,
4511 mCblk->server,
4512 mCblk->user);
4513}
4514
4515
4516// ----------------------------------------------------------------------------
4517
4518AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004519 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 DuplicatingThread *sourceThread,
4521 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004522 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004523 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004525 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4526 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 mActive(false), mSourceThread(sourceThread)
4528{
4529
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 if (mCblk != NULL) {
4531 mCblk->flags |= CBLK_DIRECTION_OUT;
4532 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mOutBuffer.frameCount = 0;
4534 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004535 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004536 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4537 mCblk, mBuffer, mCblk->buffers,
4538 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004540 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 }
4542}
4543
4544AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4545{
4546 clearBufferQueue();
4547}
4548
Glenn Kasten3acbd052012-02-28 10:39:56 -08004549status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004550 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551{
Glenn Kasten3acbd052012-02-28 10:39:56 -08004552 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 if (status != NO_ERROR) {
4554 return status;
4555 }
4556
4557 mActive = true;
4558 mRetryCount = 127;
4559 return status;
4560}
4561
4562void AudioFlinger::PlaybackThread::OutputTrack::stop()
4563{
4564 Track::stop();
4565 clearBufferQueue();
4566 mOutBuffer.frameCount = 0;
4567 mActive = false;
4568}
4569
4570bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4571{
4572 Buffer *pInBuffer;
4573 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004574 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 bool outputBufferFull = false;
4576 inBuffer.frameCount = frames;
4577 inBuffer.i16 = data;
4578
4579 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4580
4581 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08004582 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 sp<ThreadBase> thread = mThread.promote();
4584 if (thread != 0) {
4585 MixerThread *mixerThread = (MixerThread *)thread.get();
4586 if (mCblk->frameCount > frames){
4587 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4588 uint32_t startFrames = (mCblk->frameCount - frames);
4589 pInBuffer = new Buffer;
4590 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4591 pInBuffer->frameCount = startFrames;
4592 pInBuffer->i16 = pInBuffer->mBuffer;
4593 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4594 mBufferQueue.add(pInBuffer);
4595 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004596 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 }
4598 }
4599 }
4600 }
4601
4602 while (waitTimeLeftMs) {
4603 // First write pending buffers, then new data
4604 if (mBufferQueue.size()) {
4605 pInBuffer = mBufferQueue.itemAt(0);
4606 } else {
4607 pInBuffer = &inBuffer;
4608 }
4609
4610 if (pInBuffer->frameCount == 0) {
4611 break;
4612 }
4613
4614 if (mOutBuffer.frameCount == 0) {
4615 mOutBuffer.frameCount = pInBuffer->frameCount;
4616 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08004617 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01004618 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 outputBufferFull = true;
4620 break;
4621 }
4622 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4623 if (waitTimeLeftMs >= waitTimeMs) {
4624 waitTimeLeftMs -= waitTimeMs;
4625 } else {
4626 waitTimeLeftMs = 0;
4627 }
4628 }
4629
4630 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4631 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4632 mCblk->stepUser(outFrames);
4633 pInBuffer->frameCount -= outFrames;
4634 pInBuffer->i16 += outFrames * channelCount;
4635 mOutBuffer.frameCount -= outFrames;
4636 mOutBuffer.i16 += outFrames * channelCount;
4637
4638 if (pInBuffer->frameCount == 0) {
4639 if (mBufferQueue.size()) {
4640 mBufferQueue.removeAt(0);
4641 delete [] pInBuffer->mBuffer;
4642 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01004643 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 } else {
4645 break;
4646 }
4647 }
4648 }
4649
4650 // If we could not write all frames, allocate a buffer and queue it for next time.
4651 if (inBuffer.frameCount) {
4652 sp<ThreadBase> thread = mThread.promote();
4653 if (thread != 0 && !thread->standby()) {
4654 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4655 pInBuffer = new Buffer;
4656 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4657 pInBuffer->frameCount = inBuffer.frameCount;
4658 pInBuffer->i16 = pInBuffer->mBuffer;
4659 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4660 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01004661 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004663 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004664 }
4665 }
4666 }
4667
4668 // Calling write() with a 0 length buffer, means that no more data will be written:
4669 // If no more buffers are pending, fill output track buffer to make sure it is started
4670 // by output mixer.
4671 if (frames == 0 && mBufferQueue.size() == 0) {
4672 if (mCblk->user < mCblk->frameCount) {
4673 frames = mCblk->frameCount - mCblk->user;
4674 pInBuffer = new Buffer;
4675 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4676 pInBuffer->frameCount = frames;
4677 pInBuffer->i16 = pInBuffer->mBuffer;
4678 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4679 mBufferQueue.add(pInBuffer);
4680 } else if (mActive) {
4681 stop();
4682 }
4683 }
4684
4685 return outputBufferFull;
4686}
4687
4688status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4689{
4690 int active;
4691 status_t result;
4692 audio_track_cblk_t* cblk = mCblk;
4693 uint32_t framesReq = buffer->frameCount;
4694
Steve Block3856b092011-10-20 11:56:00 +01004695// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004696 buffer->frameCount = 0;
4697
4698 uint32_t framesAvail = cblk->framesAvailable();
4699
4700
4701 if (framesAvail == 0) {
4702 Mutex::Autolock _l(cblk->lock);
4703 goto start_loop_here;
4704 while (framesAvail == 0) {
4705 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004706 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004707 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004708 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 }
4710 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4711 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004712 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 }
4714 // read the server count again
4715 start_loop_here:
4716 framesAvail = cblk->framesAvailable_l();
4717 }
4718 }
4719
4720// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004721// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004722// }
4723
4724 if (framesReq > framesAvail) {
4725 framesReq = framesAvail;
4726 }
4727
4728 uint32_t u = cblk->user;
4729 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4730
Marco Nelissena1472d92012-03-30 14:36:54 -07004731 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732 framesReq = bufferEnd - u;
4733 }
4734
4735 buffer->frameCount = framesReq;
4736 buffer->raw = (void *)cblk->buffer(u);
4737 return NO_ERROR;
4738}
4739
4740
4741void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4742{
4743 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744
4745 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004746 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747 delete [] pBuffer->mBuffer;
4748 delete pBuffer;
4749 }
4750 mBufferQueue.clear();
4751}
4752
4753// ----------------------------------------------------------------------------
4754
4755AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4756 : RefBase(),
4757 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08004758 // 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 -07004759 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08004760 mPid(pid),
4761 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762{
4763 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4764}
4765
4766// Client destructor must be called with AudioFlinger::mLock held
4767AudioFlinger::Client::~Client()
4768{
4769 mAudioFlinger->removeClient_l(mPid);
4770}
4771
Glenn Kasten435dbe62012-01-30 10:15:48 -08004772sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773{
4774 return mMemoryDealer;
4775}
4776
John Grossman4ff14ba2012-02-08 16:37:41 -08004777// Reserve one of the limited slots for a timed audio track associated
4778// with this client
4779bool AudioFlinger::Client::reserveTimedTrack()
4780{
4781 const int kMaxTimedTracksPerClient = 4;
4782
4783 Mutex::Autolock _l(mTimedTrackLock);
4784
4785 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4786 ALOGW("can not create timed track - pid %d has exceeded the limit",
4787 mPid);
4788 return false;
4789 }
4790
4791 mTimedTrackCount++;
4792 return true;
4793}
4794
4795// Release a slot for a timed audio track
4796void AudioFlinger::Client::releaseTimedTrack()
4797{
4798 Mutex::Autolock _l(mTimedTrackLock);
4799 mTimedTrackCount--;
4800}
4801
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802// ----------------------------------------------------------------------------
4803
4804AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4805 const sp<IAudioFlingerClient>& client,
4806 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004807 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808{
4809}
4810
4811AudioFlinger::NotificationClient::~NotificationClient()
4812{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004813}
4814
4815void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4816{
4817 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08004818 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819}
4820
4821// ----------------------------------------------------------------------------
4822
4823AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4824 : BnAudioTrack(),
4825 mTrack(track)
4826{
4827}
4828
4829AudioFlinger::TrackHandle::~TrackHandle() {
4830 // just stop the track on deletion, associated resources
4831 // will be freed from the main thread once all pending buffers have
4832 // been played. Unless it's not in the active track list, in which
4833 // case we free everything now...
4834 mTrack->destroy();
4835}
4836
Glenn Kasten90716c52012-01-26 13:40:12 -08004837sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4838 return mTrack->getCblk();
4839}
4840
Glenn Kasten3acbd052012-02-28 10:39:56 -08004841status_t AudioFlinger::TrackHandle::start() {
4842 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004843}
4844
4845void AudioFlinger::TrackHandle::stop() {
4846 mTrack->stop();
4847}
4848
4849void AudioFlinger::TrackHandle::flush() {
4850 mTrack->flush();
4851}
4852
4853void AudioFlinger::TrackHandle::mute(bool e) {
4854 mTrack->mute(e);
4855}
4856
4857void AudioFlinger::TrackHandle::pause() {
4858 mTrack->pause();
4859}
4860
Mathias Agopian65ab4712010-07-14 17:59:35 -07004861status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4862{
4863 return mTrack->attachAuxEffect(EffectId);
4864}
4865
John Grossman4ff14ba2012-02-08 16:37:41 -08004866status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4867 sp<IMemory>* buffer) {
4868 if (!mTrack->isTimedTrack())
4869 return INVALID_OPERATION;
4870
4871 PlaybackThread::TimedTrack* tt =
4872 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4873 return tt->allocateTimedBuffer(size, buffer);
4874}
4875
4876status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4877 int64_t pts) {
4878 if (!mTrack->isTimedTrack())
4879 return INVALID_OPERATION;
4880
4881 PlaybackThread::TimedTrack* tt =
4882 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4883 return tt->queueTimedBuffer(buffer, pts);
4884}
4885
4886status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4887 const LinearTransform& xform, int target) {
4888
4889 if (!mTrack->isTimedTrack())
4890 return INVALID_OPERATION;
4891
4892 PlaybackThread::TimedTrack* tt =
4893 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4894 return tt->setMediaTimeTransform(
4895 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4896}
4897
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898status_t AudioFlinger::TrackHandle::onTransact(
4899 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4900{
4901 return BnAudioTrack::onTransact(code, data, reply, flags);
4902}
4903
4904// ----------------------------------------------------------------------------
4905
4906sp<IAudioRecord> AudioFlinger::openRecord(
4907 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004908 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004910 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004911 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08004913 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 int *sessionId,
4915 status_t *status)
4916{
4917 sp<RecordThread::RecordTrack> recordTrack;
4918 sp<RecordHandle> recordHandle;
4919 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 status_t lStatus;
4921 RecordThread *thread;
4922 size_t inFrameCount;
4923 int lSessionId;
4924
4925 // check calling permissions
4926 if (!recordingAllowed()) {
4927 lStatus = PERMISSION_DENIED;
4928 goto Exit;
4929 }
4930
4931 // add client to list
4932 { // scope for mLock
4933 Mutex::Autolock _l(mLock);
4934 thread = checkRecordThread_l(input);
4935 if (thread == NULL) {
4936 lStatus = BAD_VALUE;
4937 goto Exit;
4938 }
4939
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004940 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941
4942 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004943 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944 lSessionId = *sessionId;
4945 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004946 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 if (sessionId != NULL) {
4948 *sessionId = lSessionId;
4949 }
4950 }
4951 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004952 recordTrack = thread->createRecordTrack_l(client,
4953 sampleRate,
4954 format,
4955 channelMask,
4956 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004957 lSessionId,
4958 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004960 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4962 // destructor is called by the TrackBase destructor with mLock held
4963 client.clear();
4964 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965 goto Exit;
4966 }
4967
4968 // return to handle to client
4969 recordHandle = new RecordHandle(recordTrack);
4970 lStatus = NO_ERROR;
4971
4972Exit:
4973 if (status) {
4974 *status = lStatus;
4975 }
4976 return recordHandle;
4977}
4978
4979// ----------------------------------------------------------------------------
4980
4981AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4982 : BnAudioRecord(),
4983 mRecordTrack(recordTrack)
4984{
4985}
4986
4987AudioFlinger::RecordHandle::~RecordHandle() {
4988 stop();
4989}
4990
Glenn Kasten90716c52012-01-26 13:40:12 -08004991sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4992 return mRecordTrack->getCblk();
4993}
4994
Glenn Kasten3acbd052012-02-28 10:39:56 -08004995status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01004996 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08004997 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998}
4999
5000void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005001 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 mRecordTrack->stop();
5003}
5004
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005status_t AudioFlinger::RecordHandle::onTransact(
5006 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5007{
5008 return BnAudioRecord::onTransact(code, data, reply, flags);
5009}
5010
5011// ----------------------------------------------------------------------------
5012
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005013AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5014 AudioStreamIn *input,
5015 uint32_t sampleRate,
5016 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005017 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005019 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005020 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5021 // mRsmpInIndex and mInputBytes set by readInputParameters()
5022 mReqChannelCount(popcount(channels)),
5023 mReqSampleRate(sampleRate)
5024 // mBytesRead is only meaningful while active, and so is cleared in start()
5025 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026{
Glenn Kasten480b4682012-02-28 12:30:08 -08005027 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005028
Mathias Agopian65ab4712010-07-14 17:59:35 -07005029 readInputParameters();
5030}
5031
5032
5033AudioFlinger::RecordThread::~RecordThread()
5034{
5035 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005036 delete mResampler;
5037 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038}
5039
5040void AudioFlinger::RecordThread::onFirstRef()
5041{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005042 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043}
5044
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005045status_t AudioFlinger::RecordThread::readyToRun()
5046{
5047 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005048 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005049 return status;
5050}
5051
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052bool AudioFlinger::RecordThread::threadLoop()
5053{
5054 AudioBufferProvider::Buffer buffer;
5055 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005056 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005057
Eric Laurent44d98482010-09-30 16:12:31 -07005058 nsecs_t lastWarning = 0;
5059
Eric Laurentfeb0db62011-07-22 09:04:31 -07005060 acquireWakeLock();
5061
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 // start recording
5063 while (!exitPending()) {
5064
5065 processConfigEvents();
5066
5067 { // scope for mLock
5068 Mutex::Autolock _l(mLock);
5069 checkForNewParameters_l();
5070 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5071 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073 mStandby = true;
5074 }
5075
5076 if (exitPending()) break;
5077
Eric Laurentfeb0db62011-07-22 09:04:31 -07005078 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005079 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 // go to sleep
5081 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005082 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005083 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 continue;
5085 }
5086 if (mActiveTrack != 0) {
5087 if (mActiveTrack->mState == TrackBase::PAUSING) {
5088 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 mStandby = true;
5091 }
5092 mActiveTrack.clear();
5093 mStartStopCond.broadcast();
5094 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5095 if (mReqChannelCount != mActiveTrack->channelCount()) {
5096 mActiveTrack.clear();
5097 mStartStopCond.broadcast();
5098 } else if (mBytesRead != 0) {
5099 // record start succeeds only if first read from audio input
5100 // succeeds
5101 if (mBytesRead > 0) {
5102 mActiveTrack->mState = TrackBase::ACTIVE;
5103 } else {
5104 mActiveTrack.clear();
5105 }
5106 mStartStopCond.broadcast();
5107 }
5108 mStandby = false;
5109 }
5110 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005111 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112 }
5113
5114 if (mActiveTrack != 0) {
5115 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5116 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005117 unlockEffectChains(effectChains);
5118 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005119 continue;
5120 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005121 for (size_t i = 0; i < effectChains.size(); i ++) {
5122 effectChains[i]->process_l();
5123 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005124
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005126 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005128 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 // no resampling
5130 while (framesOut) {
5131 size_t framesIn = mFrameCount - mRsmpInIndex;
5132 if (framesIn) {
5133 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5134 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5135 if (framesIn > framesOut)
5136 framesIn = framesOut;
5137 mRsmpInIndex += framesIn;
5138 framesOut -= framesIn;
5139 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005140 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005141 memcpy(dst, src, framesIn * mFrameSize);
5142 } else {
5143 int16_t *src16 = (int16_t *)src;
5144 int16_t *dst16 = (int16_t *)dst;
5145 if (mChannelCount == 1) {
5146 while (framesIn--) {
5147 *dst16++ = *src16;
5148 *dst16++ = *src16++;
5149 }
5150 } else {
5151 while (framesIn--) {
5152 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5153 src16 += 2;
5154 }
5155 }
5156 }
5157 }
5158 if (framesOut && mFrameCount == mRsmpInIndex) {
5159 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005160 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005161 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 framesOut = 0;
5163 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005164 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 mRsmpInIndex = 0;
5166 }
5167 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005168 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5170 // Force input into standby so that it tries to
5171 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005172 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005173 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 }
5175 mRsmpInIndex = mFrameCount;
5176 framesOut = 0;
5177 buffer.frameCount = 0;
5178 }
5179 }
5180 }
5181 } else {
5182 // resampling
5183
5184 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5185 // alter output frame count as if we were expecting stereo samples
5186 if (mChannelCount == 1 && mReqChannelCount == 1) {
5187 framesOut >>= 1;
5188 }
5189 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5190 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5191 // are 32 bit aligned which should be always true.
5192 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005193 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005194 // the resampler always outputs stereo samples: do post stereo to mono conversion
5195 int16_t *src = (int16_t *)mRsmpOutBuffer;
5196 int16_t *dst = buffer.i16;
5197 while (framesOut--) {
5198 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5199 src += 2;
5200 }
5201 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005202 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 }
5204
5205 }
Eric Laurenta011e352012-03-29 15:51:43 -07005206 if (mFramestoDrop == 0) {
5207 mActiveTrack->releaseBuffer(&buffer);
5208 } else {
5209 if (mFramestoDrop > 0) {
5210 mFramestoDrop -= buffer.frameCount;
5211 if (mFramestoDrop < 0) {
5212 mFramestoDrop = 0;
5213 }
5214 }
5215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 mActiveTrack->overflow();
5217 }
5218 // client isn't retrieving buffers fast enough
5219 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005220 if (!mActiveTrack->setOverflow()) {
5221 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005222 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005223 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005224 lastWarning = now;
5225 }
5226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005227 // Release the processor for a while before asking for a new buffer.
5228 // This will give the application more chance to read from the buffer and
5229 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005230 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005231 }
5232 }
Eric Laurentec437d82011-07-26 20:54:46 -07005233 // enable changes in effect chain
5234 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005235 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236 }
5237
5238 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005239 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005240 }
5241 mActiveTrack.clear();
5242
5243 mStartStopCond.broadcast();
5244
Eric Laurentfeb0db62011-07-22 09:04:31 -07005245 releaseWakeLock();
5246
Steve Block3856b092011-10-20 11:56:00 +01005247 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005248 return false;
5249}
5250
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005251
5252sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5253 const sp<AudioFlinger::Client>& client,
5254 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005255 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005256 int channelMask,
5257 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005258 int sessionId,
5259 status_t *status)
5260{
5261 sp<RecordTrack> track;
5262 status_t lStatus;
5263
5264 lStatus = initCheck();
5265 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005266 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005267 goto Exit;
5268 }
5269
5270 { // scope for mLock
5271 Mutex::Autolock _l(mLock);
5272
5273 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005274 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005275
Glenn Kasten7378ca52012-01-20 13:44:40 -08005276 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005277 lStatus = NO_MEMORY;
5278 goto Exit;
5279 }
5280
5281 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005282 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5283 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005284 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005285 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5286 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005287 }
5288 lStatus = NO_ERROR;
5289
5290Exit:
5291 if (status) {
5292 *status = lStatus;
5293 }
5294 return track;
5295}
5296
Eric Laurenta011e352012-03-29 15:51:43 -07005297status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005298 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005299 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005300{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005301 // FIXME use tid here
Eric Laurenta011e352012-03-29 15:51:43 -07005302 ALOGV("RecordThread::start tid=%d, event %d, triggerSession %d", tid, event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005303 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005305
5306 if (event == AudioSystem::SYNC_EVENT_NONE) {
5307 mSyncStartEvent.clear();
5308 mFramestoDrop = 0;
5309 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5310 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5311 triggerSession,
5312 recordTrack->sessionId(),
5313 syncStartEventCallback,
5314 this);
5315 mFramestoDrop = -1;
5316 }
5317
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005319 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320 if (mActiveTrack != 0) {
5321 if (recordTrack != mActiveTrack.get()) {
5322 status = -EBUSY;
5323 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5324 mActiveTrack->mState = TrackBase::ACTIVE;
5325 }
5326 return status;
5327 }
5328
5329 recordTrack->mState = TrackBase::IDLE;
5330 mActiveTrack = recordTrack;
5331 mLock.unlock();
5332 status_t status = AudioSystem::startInput(mId);
5333 mLock.lock();
5334 if (status != NO_ERROR) {
5335 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005336 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337 return status;
5338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339 mRsmpInIndex = mFrameCount;
5340 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005341 if (mResampler != NULL) {
5342 mResampler->reset();
5343 }
5344 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005346 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 mWaitWorkCV.signal();
5348 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005349 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350 mActiveTrack.clear();
5351 status = INVALID_OPERATION;
5352 goto startError;
5353 }
5354 mStartStopCond.wait(mLock);
5355 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005356 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 status = BAD_VALUE;
5358 goto startError;
5359 }
Steve Block3856b092011-10-20 11:56:00 +01005360 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 return status;
5362 }
5363startError:
5364 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005365 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366 return status;
5367}
5368
Eric Laurenta011e352012-03-29 15:51:43 -07005369void AudioFlinger::RecordThread::clearSyncStartEvent()
5370{
5371 if (mSyncStartEvent != 0) {
5372 mSyncStartEvent->cancel();
5373 }
5374 mSyncStartEvent.clear();
5375}
5376
5377void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5378{
5379 sp<SyncEvent> strongEvent = event.promote();
5380
5381 if (strongEvent != 0) {
5382 RecordThread *me = (RecordThread *)strongEvent->cookie();
5383 me->handleSyncStartEvent(strongEvent);
5384 }
5385}
5386
5387void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5388{
5389 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5390 mActiveTrack.get(),
5391 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5392 event->listenerSession());
5393
5394 if (mActiveTrack != 0 &&
5395 event == mSyncStartEvent) {
5396 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5397 // from audio HAL
5398 mFramestoDrop = mFrameCount * 2;
5399 mSyncStartEvent.clear();
5400 }
5401}
5402
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005404 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005405 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005407 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5409 mActiveTrack->mState = TrackBase::PAUSING;
5410 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005411 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 return;
5413 }
5414 mStartStopCond.wait(mLock);
5415 // if we have been restarted, recordTrack == mActiveTrack.get() here
5416 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5417 mLock.unlock();
5418 AudioSystem::stopInput(mId);
5419 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005420 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 }
5422 }
5423 }
5424}
5425
Eric Laurenta011e352012-03-29 15:51:43 -07005426bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5427{
5428 return false;
5429}
5430
5431status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5432{
5433 if (!isValidSyncEvent(event)) {
5434 return BAD_VALUE;
5435 }
5436
5437 Mutex::Autolock _l(mLock);
5438
5439 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5440 mTrack->setSyncEvent(event);
5441 return NO_ERROR;
5442 }
5443 return NAME_NOT_FOUND;
5444}
5445
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5447{
5448 const size_t SIZE = 256;
5449 char buffer[SIZE];
5450 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451
5452 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5453 result.append(buffer);
5454
5455 if (mActiveTrack != 0) {
5456 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005457 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 mActiveTrack->dump(buffer, SIZE);
5459 result.append(buffer);
5460
5461 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5462 result.append(buffer);
5463 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5464 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005465 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 result.append(buffer);
5467 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5468 result.append(buffer);
5469 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5470 result.append(buffer);
5471
5472
5473 } else {
5474 result.append("No record client\n");
5475 }
5476 write(fd, result.string(), result.size());
5477
5478 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005479 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480
5481 return NO_ERROR;
5482}
5483
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005484// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005485status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486{
5487 size_t framesReq = buffer->frameCount;
5488 size_t framesReady = mFrameCount - mRsmpInIndex;
5489 int channelCount;
5490
5491 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005492 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005494 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5496 // Force input into standby so that it tries to
5497 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005498 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005499 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005501 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 buffer->frameCount = 0;
5503 return NOT_ENOUGH_DATA;
5504 }
5505 mRsmpInIndex = 0;
5506 framesReady = mFrameCount;
5507 }
5508
5509 if (framesReq > framesReady) {
5510 framesReq = framesReady;
5511 }
5512
5513 if (mChannelCount == 1 && mReqChannelCount == 2) {
5514 channelCount = 1;
5515 } else {
5516 channelCount = 2;
5517 }
5518 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5519 buffer->frameCount = framesReq;
5520 return NO_ERROR;
5521}
5522
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005523// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5525{
5526 mRsmpInIndex += buffer->frameCount;
5527 buffer->frameCount = 0;
5528}
5529
5530bool AudioFlinger::RecordThread::checkForNewParameters_l()
5531{
5532 bool reconfig = false;
5533
5534 while (!mNewParameters.isEmpty()) {
5535 status_t status = NO_ERROR;
5536 String8 keyValuePair = mNewParameters[0];
5537 AudioParameter param = AudioParameter(keyValuePair);
5538 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005539 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 int reqSamplingRate = mReqSampleRate;
5541 int reqChannelCount = mReqChannelCount;
5542
5543 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5544 reqSamplingRate = value;
5545 reconfig = true;
5546 }
5547 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005548 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 reconfig = true;
5550 }
5551 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005552 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 reconfig = true;
5554 }
5555 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5556 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08005557 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 // if frame count is changed after track creation
5559 if (mActiveTrack != 0) {
5560 status = INVALID_OPERATION;
5561 } else {
5562 reconfig = true;
5563 }
5564 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005565 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5566 // forward device change to effects that have requested to be
5567 // aware of attached audio device.
5568 for (size_t i = 0; i < mEffectChains.size(); i++) {
5569 mEffectChains[i]->setDevice_l(value);
5570 }
5571 // store input device and output device but do not forward output device to audio HAL.
5572 // Note that status is ignored by the caller for output device
5573 // (see AudioFlinger::setParameters()
5574 if (value & AUDIO_DEVICE_OUT_ALL) {
5575 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5576 status = BAD_VALUE;
5577 } else {
5578 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005579 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5580 if (mTrack != NULL) {
5581 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005582 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005583 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5584 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5585 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005586 }
5587 mDevice |= (uint32_t)value;
5588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005589 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005590 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005592 mInput->stream->common.standby(&mInput->stream->common);
5593 status = mInput->stream->common.set_parameters(&mInput->stream->common,
5594 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
5596 if (reconfig) {
5597 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005598 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005599 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005600 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08005601 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
5602 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 status = NO_ERROR;
5604 }
5605 if (status == NO_ERROR) {
5606 readInputParameters();
5607 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5608 }
5609 }
5610 }
5611
5612 mNewParameters.removeAt(0);
5613
5614 mParamStatus = status;
5615 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005616 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5617 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08005618 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 }
5620 return reconfig;
5621}
5622
5623String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5624{
Dima Zavinfce7a472011-04-19 22:30:36 -07005625 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005626 String8 out_s8 = String8();
5627
5628 Mutex::Autolock _l(mLock);
5629 if (initCheck() != NO_ERROR) {
5630 return out_s8;
5631 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005632
Dima Zavin799a70e2011-04-18 16:57:27 -07005633 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005634 out_s8 = String8(s);
5635 free(s);
5636 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637}
5638
5639void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5640 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08005641 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642
5643 switch (event) {
5644 case AudioSystem::INPUT_OPENED:
5645 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005646 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647 desc.samplingRate = mSampleRate;
5648 desc.format = mFormat;
5649 desc.frameCount = mFrameCount;
5650 desc.latency = 0;
5651 param2 = &desc;
5652 break;
5653
5654 case AudioSystem::INPUT_CLOSED:
5655 default:
5656 break;
5657 }
5658 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5659}
5660
5661void AudioFlinger::RecordThread::readInputParameters()
5662{
Glenn Kastene9dd0172012-01-27 18:08:45 -08005663 delete mRsmpInBuffer;
5664 // mRsmpInBuffer is always assigned a new[] below
5665 delete mRsmpOutBuffer;
5666 mRsmpOutBuffer = NULL;
5667 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08005668 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669
Dima Zavin799a70e2011-04-18 16:57:27 -07005670 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005671 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5672 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005673 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08005674 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07005675 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 mFrameCount = mInputBytes / mFrameSize;
5677 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5678
Glenn Kasten53d76db2012-03-08 12:32:47 -08005679 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 {
5681 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005682 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5683 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684 if (mChannelCount == 1 && mReqChannelCount == 2) {
5685 channelCount = 1;
5686 } else {
5687 channelCount = 2;
5688 }
5689 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5690 mResampler->setSampleRate(mSampleRate);
5691 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5692 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5693
5694 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5695 if (mChannelCount == 1 && mReqChannelCount == 1) {
5696 mFrameCount >>= 1;
5697 }
5698
5699 }
5700 mRsmpInIndex = mFrameCount;
5701}
5702
5703unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5704{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005705 Mutex::Autolock _l(mLock);
5706 if (initCheck() != NO_ERROR) {
5707 return 0;
5708 }
5709
Dima Zavin799a70e2011-04-18 16:57:27 -07005710 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711}
5712
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005713uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5714{
5715 Mutex::Autolock _l(mLock);
5716 uint32_t result = 0;
5717 if (getEffectChain_l(sessionId) != 0) {
5718 result = EFFECT_SESSION;
5719 }
5720
5721 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5722 result |= TRACK_SESSION;
5723 }
5724
5725 return result;
5726}
5727
Eric Laurent59bd0da2011-08-01 09:52:20 -07005728AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5729{
5730 Mutex::Autolock _l(mLock);
5731 return mTrack;
5732}
5733
Glenn Kastenaed850d2012-01-26 09:46:34 -08005734AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005735{
5736 Mutex::Autolock _l(mLock);
5737 return mInput;
5738}
5739
5740AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5741{
5742 Mutex::Autolock _l(mLock);
5743 AudioStreamIn *input = mInput;
5744 mInput = NULL;
5745 return input;
5746}
5747
5748// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08005749audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005750{
5751 if (mInput == NULL) {
5752 return NULL;
5753 }
5754 return &mInput->stream->common;
5755}
5756
5757
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758// ----------------------------------------------------------------------------
5759
Eric Laurenta4c5a552012-03-29 10:12:40 -07005760audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
5761{
5762 if (!settingsAllowed()) {
5763 return 0;
5764 }
5765 Mutex::Autolock _l(mLock);
5766 return loadHwModule_l(name);
5767}
5768
5769// loadHwModule_l() must be called with AudioFlinger::mLock held
5770audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
5771{
5772 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5773 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
5774 ALOGW("loadHwModule() module %s already loaded", name);
5775 return mAudioHwDevs.keyAt(i);
5776 }
5777 }
5778
Eric Laurenta4c5a552012-03-29 10:12:40 -07005779 audio_hw_device_t *dev;
5780
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005781 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005782 if (rc) {
5783 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
5784 return 0;
5785 }
5786
5787 mHardwareStatus = AUDIO_HW_INIT;
5788 rc = dev->init_check(dev);
5789 mHardwareStatus = AUDIO_HW_IDLE;
5790 if (rc) {
5791 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
5792 return 0;
5793 }
5794
5795 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
5796 (NULL != dev->set_master_volume)) {
5797 AutoMutex lock(mHardwareLock);
5798 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5799 dev->set_master_volume(dev, mMasterVolume);
5800 mHardwareStatus = AUDIO_HW_IDLE;
5801 }
5802
5803 audio_module_handle_t handle = nextUniqueId();
5804 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
5805
5806 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005807 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005808
5809 return handle;
5810
5811}
5812
5813audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
5814 audio_devices_t *pDevices,
5815 uint32_t *pSamplingRate,
5816 audio_format_t *pFormat,
5817 audio_channel_mask_t *pChannelMask,
5818 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005819 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005820{
5821 status_t status;
5822 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005823 struct audio_config config = {
5824 sample_rate: pSamplingRate ? *pSamplingRate : 0,
5825 channel_mask: pChannelMask ? *pChannelMask : 0,
5826 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
5827 };
5828 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07005829 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830
Eric Laurenta4c5a552012-03-29 10:12:40 -07005831 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5832 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07005833 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005834 config.sample_rate,
5835 config.format,
5836 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07005837 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838
5839 if (pDevices == NULL || *pDevices == 0) {
5840 return 0;
5841 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005842
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 Mutex::Autolock _l(mLock);
5844
Eric Laurenta4c5a552012-03-29 10:12:40 -07005845 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07005846 if (outHwDev == NULL)
5847 return 0;
5848
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005849 audio_io_handle_t id = nextUniqueId();
5850
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005851 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005852
5853 status = outHwDev->open_output_stream(outHwDev,
5854 id,
5855 *pDevices,
5856 (audio_output_flags_t)flags,
5857 &config,
5858 &outStream);
5859
Glenn Kasten8abf44d2012-02-02 14:16:03 -08005860 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01005861 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005862 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005863 config.sample_rate,
5864 config.format,
5865 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 status);
5867
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005868 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005869 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07005870
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005871 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005872 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
5873 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005875 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 } else {
5877 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01005878 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 }
5880 mPlaybackThreads.add(id, thread);
5881
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07005882 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
5883 if (pFormat != NULL) *pFormat = config.format;
5884 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08005885 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886
5887 // notify client processes of the new output creation
5888 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07005889
5890 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07005891 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07005892 ALOGI("Using module %d has the primary audio interface", module);
5893 mPrimaryHardwareDev = outHwDev;
5894
5895 AutoMutex lock(mHardwareLock);
5896 mHardwareStatus = AUDIO_HW_SET_MODE;
5897 outHwDev->set_mode(outHwDev, mMode);
5898
5899 // Determine the level of master volume support the primary audio HAL has,
5900 // and set the initial master volume at the same time.
5901 float initialVolume = 1.0;
5902 mMasterVolumeSupportLvl = MVS_NONE;
5903
5904 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
5905 if ((NULL != outHwDev->get_master_volume) &&
5906 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
5907 mMasterVolumeSupportLvl = MVS_FULL;
5908 } else {
5909 mMasterVolumeSupportLvl = MVS_SETONLY;
5910 initialVolume = 1.0;
5911 }
5912
5913 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
5914 if ((NULL == outHwDev->set_master_volume) ||
5915 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
5916 mMasterVolumeSupportLvl = MVS_NONE;
5917 }
5918 // now that we have a primary device, initialize master volume on other devices
5919 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
5920 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
5921
5922 if ((dev != mPrimaryHardwareDev) &&
5923 (NULL != dev->set_master_volume)) {
5924 dev->set_master_volume(dev, initialVolume);
5925 }
5926 }
5927 mHardwareStatus = AUDIO_HW_IDLE;
5928 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
5929 ? initialVolume
5930 : 1.0;
5931 mMasterVolume = initialVolume;
5932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 return id;
5934 }
5935
5936 return 0;
5937}
5938
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005939audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
5940 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941{
5942 Mutex::Autolock _l(mLock);
5943 MixerThread *thread1 = checkMixerThread_l(output1);
5944 MixerThread *thread2 = checkMixerThread_l(output2);
5945
5946 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005947 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 return 0;
5949 }
5950
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005951 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5953 thread->addOutputTrack(thread2);
5954 mPlaybackThreads.add(id, thread);
5955 // notify client processes of the new output creation
5956 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5957 return id;
5958}
5959
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005960status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961{
5962 // keep strong reference on the playback thread so that
5963 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005964 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 {
5966 Mutex::Autolock _l(mLock);
5967 thread = checkPlaybackThread_l(output);
5968 if (thread == NULL) {
5969 return BAD_VALUE;
5970 }
5971
Steve Block3856b092011-10-20 11:56:00 +01005972 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005974 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005976 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5978 dupThread->removeOutputTrack((MixerThread *)thread.get());
5979 }
5980 }
5981 }
Glenn Kastena1117922012-01-26 10:53:32 -08005982 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 mPlaybackThreads.removeItem(output);
5984 }
5985 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005986 // The thread entity (active unit of execution) is no longer running here,
5987 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005989 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005990 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005991 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005992 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005993 out->hwDev->close_output_stream(out->hwDev, out->stream);
5994 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 }
5996 return NO_ERROR;
5997}
5998
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005999status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000{
6001 Mutex::Autolock _l(mLock);
6002 PlaybackThread *thread = checkPlaybackThread_l(output);
6003
6004 if (thread == NULL) {
6005 return BAD_VALUE;
6006 }
6007
Steve Block3856b092011-10-20 11:56:00 +01006008 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 thread->suspend();
6010
6011 return NO_ERROR;
6012}
6013
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006014status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015{
6016 Mutex::Autolock _l(mLock);
6017 PlaybackThread *thread = checkPlaybackThread_l(output);
6018
6019 if (thread == NULL) {
6020 return BAD_VALUE;
6021 }
6022
Steve Block3856b092011-10-20 11:56:00 +01006023 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024
6025 thread->restore();
6026
6027 return NO_ERROR;
6028}
6029
Eric Laurenta4c5a552012-03-29 10:12:40 -07006030audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6031 audio_devices_t *pDevices,
6032 uint32_t *pSamplingRate,
6033 audio_format_t *pFormat,
6034 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035{
6036 status_t status;
6037 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006038 struct audio_config config = {
6039 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6040 channel_mask: pChannelMask ? *pChannelMask : 0,
6041 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6042 };
6043 uint32_t reqSamplingRate = config.sample_rate;
6044 audio_format_t reqFormat = config.format;
6045 audio_channel_mask_t reqChannels = config.channel_mask;
6046 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006047 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048
6049 if (pDevices == NULL || *pDevices == 0) {
6050 return 0;
6051 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006052
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 Mutex::Autolock _l(mLock);
6054
Eric Laurenta4c5a552012-03-29 10:12:40 -07006055 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006056 if (inHwDev == NULL)
6057 return 0;
6058
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006059 audio_io_handle_t id = nextUniqueId();
6060
6061 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006062 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006063 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006064 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006065 config.sample_rate,
6066 config.format,
6067 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 status);
6069
6070 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6071 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6072 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006073 if (status == BAD_VALUE &&
6074 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6075 (config.sample_rate <= 2 * reqSamplingRate) &&
6076 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006077 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006078 inStream = NULL;
6079 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 }
6081
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006082 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006083 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6084
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006085 // Start record thread
6086 // RecorThread require both input and output device indication to forward to audio
6087 // pre processing modules
6088 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6089 thread = new RecordThread(this,
6090 input,
6091 reqSamplingRate,
6092 reqChannels,
6093 id,
6094 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006096 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006097 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006098 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006099 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100
Dima Zavin799a70e2011-04-18 16:57:27 -07006101 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102
6103 // notify client processes of the new input creation
6104 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6105 return id;
6106 }
6107
6108 return 0;
6109}
6110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006111status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112{
6113 // keep strong reference on the record thread so that
6114 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006115 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 {
6117 Mutex::Autolock _l(mLock);
6118 thread = checkRecordThread_l(input);
6119 if (thread == NULL) {
6120 return BAD_VALUE;
6121 }
6122
Steve Block3856b092011-10-20 11:56:00 +01006123 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006124 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 mRecordThreads.removeItem(input);
6126 }
6127 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006128 // The thread entity (active unit of execution) is no longer running here,
6129 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006131 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006132 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006133 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006134 in->hwDev->close_input_stream(in->hwDev, in->stream);
6135 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136
6137 return NO_ERROR;
6138}
6139
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006140status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141{
6142 Mutex::Autolock _l(mLock);
6143 MixerThread *dstThread = checkMixerThread_l(output);
6144 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006145 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 return BAD_VALUE;
6147 }
6148
Steve Block3856b092011-10-20 11:56:00 +01006149 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6151
6152 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6153 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006154 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 MixerThread *srcThread = (MixerThread *)thread;
6156 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 }
Eric Laurentde070132010-07-13 04:45:46 -07006158 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159
6160 return NO_ERROR;
6161}
6162
6163
6164int AudioFlinger::newAudioSessionId()
6165{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006166 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167}
6168
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006169void AudioFlinger::acquireAudioSessionId(int audioSession)
6170{
6171 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006172 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006173 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006174 size_t num = mAudioSessionRefs.size();
6175 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006176 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006177 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6178 ref->mCnt++;
6179 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006180 return;
6181 }
6182 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006183 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6184 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006185}
6186
6187void AudioFlinger::releaseAudioSessionId(int audioSession)
6188{
6189 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006190 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006191 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006192 size_t num = mAudioSessionRefs.size();
6193 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006194 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006195 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6196 ref->mCnt--;
6197 ALOGV(" decremented refcount to %d", ref->mCnt);
6198 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006199 mAudioSessionRefs.removeAt(i);
6200 delete ref;
6201 purgeStaleEffects_l();
6202 }
6203 return;
6204 }
6205 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006206 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006207}
6208
6209void AudioFlinger::purgeStaleEffects_l() {
6210
Steve Block3856b092011-10-20 11:56:00 +01006211 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006212
6213 Vector< sp<EffectChain> > chains;
6214
6215 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6216 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6217 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6218 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006219 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6220 chains.push(ec);
6221 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006222 }
6223 }
6224 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6225 sp<RecordThread> t = mRecordThreads.valueAt(i);
6226 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6227 sp<EffectChain> ec = t->mEffectChains[j];
6228 chains.push(ec);
6229 }
6230 }
6231
6232 for (size_t i = 0; i < chains.size(); i++) {
6233 sp<EffectChain> ec = chains[i];
6234 int sessionid = ec->sessionId();
6235 sp<ThreadBase> t = ec->mThread.promote();
6236 if (t == 0) {
6237 continue;
6238 }
6239 size_t numsessionrefs = mAudioSessionRefs.size();
6240 bool found = false;
6241 for (size_t k = 0; k < numsessionrefs; k++) {
6242 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006243 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006244 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006245 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006246 found = true;
6247 break;
6248 }
6249 }
6250 if (!found) {
6251 // remove all effects from the chain
6252 while (ec->mEffects.size()) {
6253 sp<EffectModule> effect = ec->mEffects[0];
6254 effect->unPin();
6255 Mutex::Autolock _l (t->mLock);
6256 t->removeEffect_l(effect);
6257 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6258 sp<EffectHandle> handle = effect->mHandles[j].promote();
6259 if (handle != 0) {
6260 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006261 if (handle->mHasControl && handle->mEnabled) {
6262 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6263 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006264 }
6265 }
6266 AudioSystem::unregisterEffect(effect->id());
6267 }
6268 }
6269 }
6270 return;
6271}
6272
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006274AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275{
Glenn Kastena1117922012-01-26 10:53:32 -08006276 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277}
6278
6279// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006280AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281{
6282 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006283 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284}
6285
6286// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006287AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288{
Glenn Kastena1117922012-01-26 10:53:32 -08006289 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290}
6291
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006292uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006294 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295}
6296
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006297AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006298{
6299 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6300 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006301 AudioStreamOut *output = thread->getOutput();
6302 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006303 return thread;
6304 }
6305 }
6306 return NULL;
6307}
6308
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006309uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006310{
6311 PlaybackThread *thread = primaryPlaybackThread_l();
6312
6313 if (thread == NULL) {
6314 return 0;
6315 }
6316
6317 return thread->device();
6318}
6319
Eric Laurenta011e352012-03-29 15:51:43 -07006320sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6321 int triggerSession,
6322 int listenerSession,
6323 sync_event_callback_t callBack,
6324 void *cookie)
6325{
6326 Mutex::Autolock _l(mLock);
6327
6328 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6329 status_t playStatus = NAME_NOT_FOUND;
6330 status_t recStatus = NAME_NOT_FOUND;
6331 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6332 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6333 if (playStatus == NO_ERROR) {
6334 return event;
6335 }
6336 }
6337 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6338 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6339 if (recStatus == NO_ERROR) {
6340 return event;
6341 }
6342 }
6343 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6344 mPendingSyncEvents.add(event);
6345 } else {
6346 ALOGV("createSyncEvent() invalid event %d", event->type());
6347 event.clear();
6348 }
6349 return event;
6350}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006351
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352// ----------------------------------------------------------------------------
6353// Effect management
6354// ----------------------------------------------------------------------------
6355
6356
Glenn Kastenf587ba52012-01-26 16:25:10 -08006357status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358{
6359 Mutex::Autolock _l(mLock);
6360 return EffectQueryNumberEffects(numEffects);
6361}
6362
Glenn Kastenf587ba52012-01-26 16:25:10 -08006363status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364{
6365 Mutex::Autolock _l(mLock);
6366 return EffectQueryEffect(index, descriptor);
6367}
6368
Glenn Kasten5e92a782012-01-30 07:40:52 -08006369status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006370 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006371{
6372 Mutex::Autolock _l(mLock);
6373 return EffectGetDescriptor(pUuid, descriptor);
6374}
6375
6376
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6378 effect_descriptor_t *pDesc,
6379 const sp<IEffectClient>& effectClient,
6380 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006381 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 int sessionId,
6383 status_t *status,
6384 int *id,
6385 int *enabled)
6386{
6387 status_t lStatus = NO_ERROR;
6388 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006391 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006392 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393
6394 if (pDesc == NULL) {
6395 lStatus = BAD_VALUE;
6396 goto Exit;
6397 }
6398
Eric Laurent84e9a102010-09-23 16:10:16 -07006399 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006400 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006401 lStatus = PERMISSION_DENIED;
6402 goto Exit;
6403 }
6404
Dima Zavinfce7a472011-04-19 22:30:36 -07006405 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006406 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006407 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006408 lStatus = PERMISSION_DENIED;
6409 goto Exit;
6410 }
6411
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006412 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006414 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006415 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006416 lStatus = BAD_VALUE;
6417 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006418 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006419 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006420 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006421 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006422 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006423 }
6424 }
6425
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 {
6427 Mutex::Autolock _l(mLock);
6428
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429
6430 if (!EffectIsNullUuid(&pDesc->uuid)) {
6431 // if uuid is specified, request effect descriptor
6432 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6433 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006434 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 goto Exit;
6436 }
6437 } else {
6438 // if uuid is not specified, look for an available implementation
6439 // of the required type in effect factory
6440 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006441 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 lStatus = BAD_VALUE;
6443 goto Exit;
6444 }
6445 uint32_t numEffects = 0;
6446 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006447 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 bool found = false;
6449
6450 lStatus = EffectQueryNumberEffects(&numEffects);
6451 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006452 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 goto Exit;
6454 }
6455 for (uint32_t i = 0; i < numEffects; i++) {
6456 lStatus = EffectQueryEffect(i, &desc);
6457 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006458 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459 continue;
6460 }
6461 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6462 // If matching type found save effect descriptor. If the session is
6463 // 0 and the effect is not auxiliary, continue enumeration in case
6464 // an auxiliary version of this effect type is available
6465 found = true;
6466 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006467 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6469 break;
6470 }
6471 }
6472 }
6473 if (!found) {
6474 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006475 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 goto Exit;
6477 }
6478 // For same effect type, chose auxiliary version over insert version if
6479 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6482 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6483 }
6484 }
6485
6486 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006487 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6489 lStatus = INVALID_OPERATION;
6490 goto Exit;
6491 }
6492
Eric Laurent59255e42011-07-27 19:49:51 -07006493 // check recording permission for visualizer
6494 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6495 !recordingAllowed()) {
6496 lStatus = PERMISSION_DENIED;
6497 goto Exit;
6498 }
6499
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 // return effect descriptor
6501 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6502
6503 // If output is not specified try to find a matching audio session ID in one of the
6504 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006505 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6506 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006507 // Note: io is never 0 when creating an effect on an input
6508 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006509 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6511 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006512 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006513 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006516 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6518 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6519 io = mRecordThreads.keyAt(i);
6520 break;
6521 }
6522 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006523 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006524 // If no output thread contains the requested session ID, default to
6525 // first output. The effect chain will be moved to the correct output
6526 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006527 if (io == 0 && mPlaybackThreads.size()) {
6528 io = mPlaybackThreads.keyAt(0);
6529 }
Steve Block3856b092011-10-20 11:56:00 +01006530 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006531 }
6532 ThreadBase *thread = checkRecordThread_l(io);
6533 if (thread == NULL) {
6534 thread = checkPlaybackThread_l(io);
6535 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006536 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006537 lStatus = BAD_VALUE;
6538 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006541
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006542 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006544 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006545 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6546 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 if (handle != 0 && id != NULL) {
6548 *id = handle->id();
6549 }
6550 }
6551
6552Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006553 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 *status = lStatus;
6555 }
6556 return handle;
6557}
6558
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006559status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
6560 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006561{
Steve Block3856b092011-10-20 11:56:00 +01006562 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006563 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006564 Mutex::Autolock _l(mLock);
6565 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006566 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006567 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 }
Eric Laurentde070132010-07-13 04:45:46 -07006569 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6570 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006571 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006572 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 }
Eric Laurentde070132010-07-13 04:45:46 -07006574 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6575 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006576 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006577 return BAD_VALUE;
6578 }
6579
6580 Mutex::Autolock _dl(dstThread->mLock);
6581 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006582 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006583
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 return NO_ERROR;
6585}
6586
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006587// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006588status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006589 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006590 AudioFlinger::PlaybackThread *dstThread,
6591 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006592{
Steve Block3856b092011-10-20 11:56:00 +01006593 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006594 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006595
Eric Laurent59255e42011-07-27 19:49:51 -07006596 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006597 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006598 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006599 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006600 return INVALID_OPERATION;
6601 }
6602
Eric Laurent39e94f82010-07-28 01:32:47 -07006603 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006604 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006605 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006606 // removed.
6607 srcThread->removeEffectChain_l(chain);
6608
6609 // transfer all effects one by one so that new effect chain is created on new thread with
6610 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006611 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07006612 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006613 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006614 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6615 while (effect != 0) {
6616 srcThread->removeEffect_l(effect);
6617 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006618 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6619 if (effect->state() == EffectModule::ACTIVE ||
6620 effect->state() == EffectModule::STOPPING) {
6621 effect->start();
6622 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006623 // if the move request is not received from audio policy manager, the effect must be
6624 // re-registered with the new strategy and output
6625 if (dstChain == 0) {
6626 dstChain = effect->chain().promote();
6627 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006628 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07006629 srcThread->addEffect_l(effect);
6630 return NO_INIT;
6631 }
6632 strategy = dstChain->strategy();
6633 }
6634 if (reRegister) {
6635 AudioSystem::unregisterEffect(effect->id());
6636 AudioSystem::registerEffect(&effect->desc(),
6637 dstOutput,
6638 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006639 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006640 effect->id());
6641 }
Eric Laurentde070132010-07-13 04:45:46 -07006642 effect = chain->getEffectFromId_l(0);
6643 }
6644
6645 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646}
6647
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006648
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006650sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651 const sp<AudioFlinger::Client>& client,
6652 const sp<IEffectClient>& effectClient,
6653 int32_t priority,
6654 int sessionId,
6655 effect_descriptor_t *desc,
6656 int *enabled,
6657 status_t *status
6658 )
6659{
6660 sp<EffectModule> effect;
6661 sp<EffectHandle> handle;
6662 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006664 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 bool effectCreated = false;
6666 bool effectRegistered = false;
6667
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006668 lStatus = initCheck();
6669 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006670 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 goto Exit;
6672 }
6673
6674 // Do not allow effects with session ID 0 on direct output or duplicating threads
6675 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006676 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006677 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07006678 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 lStatus = BAD_VALUE;
6680 goto Exit;
6681 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006682 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08006683 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006684 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006685 desc->name, desc->flags, mType);
6686 lStatus = BAD_VALUE;
6687 goto Exit;
6688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689
Steve Block3856b092011-10-20 11:56:00 +01006690 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691
6692 { // scope for mLock
6693 Mutex::Autolock _l(mLock);
6694
6695 // check for existing effect chain with the requested audio session
6696 chain = getEffectChain_l(sessionId);
6697 if (chain == 0) {
6698 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006699 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006700 chain = new EffectChain(this, sessionId);
6701 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006702 chain->setStrategy(getStrategyForSession_l(sessionId));
6703 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006705 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 }
6707
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08006708 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006709
6710 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006711 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006713 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714 if (lStatus != NO_ERROR) {
6715 goto Exit;
6716 }
6717 effectRegistered = true;
6718 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006719 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 lStatus = effect->status();
6721 if (lStatus != NO_ERROR) {
6722 goto Exit;
6723 }
Eric Laurentcab11242010-07-15 12:50:15 -07006724 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 if (lStatus != NO_ERROR) {
6726 goto Exit;
6727 }
6728 effectCreated = true;
6729
6730 effect->setDevice(mDevice);
6731 effect->setMode(mAudioFlinger->getMode());
6732 }
6733 // create effect handle and connect it to effect module
6734 handle = new EffectHandle(effect, client, effectClient, priority);
6735 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08006736 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737 *enabled = (int)effect->isEnabled();
6738 }
6739 }
6740
6741Exit:
6742 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006743 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006745 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 }
6747 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006748 AudioSystem::unregisterEffect(effect->id());
6749 }
6750 if (chainCreated) {
6751 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752 }
6753 handle.clear();
6754 }
6755
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006756 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757 *status = lStatus;
6758 }
6759 return handle;
6760}
6761
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006762sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6763{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006764 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08006765 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006766}
6767
Eric Laurentde070132010-07-13 04:45:46 -07006768// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6769// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006770status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006771{
6772 // check for existing effect chain with the requested audio session
6773 int sessionId = effect->sessionId();
6774 sp<EffectChain> chain = getEffectChain_l(sessionId);
6775 bool chainCreated = false;
6776
6777 if (chain == 0) {
6778 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01006779 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006780 chain = new EffectChain(this, sessionId);
6781 addEffectChain_l(chain);
6782 chain->setStrategy(getStrategyForSession_l(sessionId));
6783 chainCreated = true;
6784 }
Steve Block3856b092011-10-20 11:56:00 +01006785 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006786
6787 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006788 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07006789 this, effect->desc().name, chain.get());
6790 return BAD_VALUE;
6791 }
6792
6793 status_t status = chain->addEffect_l(effect);
6794 if (status != NO_ERROR) {
6795 if (chainCreated) {
6796 removeEffectChain_l(chain);
6797 }
6798 return status;
6799 }
6800
6801 effect->setDevice(mDevice);
6802 effect->setMode(mAudioFlinger->getMode());
6803 return NO_ERROR;
6804}
6805
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006806void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006807
Steve Block3856b092011-10-20 11:56:00 +01006808 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006810 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6811 detachAuxEffect_l(effect->id());
6812 }
6813
6814 sp<EffectChain> chain = effect->chain().promote();
6815 if (chain != 0) {
6816 // remove effect chain if removing last effect
6817 if (chain->removeEffect_l(effect) == 0) {
6818 removeEffectChain_l(chain);
6819 }
6820 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00006821 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07006822 }
6823}
6824
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006825void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006826 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006827{
6828 effectChains = mEffectChains;
6829 for (size_t i = 0; i < mEffectChains.size(); i++) {
6830 mEffectChains[i]->lock();
6831 }
6832}
6833
6834void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006835 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006836{
6837 for (size_t i = 0; i < effectChains.size(); i++) {
6838 effectChains[i]->unlock();
6839 }
6840}
6841
6842sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6843{
6844 Mutex::Autolock _l(mLock);
6845 return getEffectChain_l(sessionId);
6846}
6847
6848sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6849{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006850 size_t size = mEffectChains.size();
6851 for (size_t i = 0; i < size; i++) {
6852 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08006853 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006854 }
6855 }
Glenn Kasten090f0192012-01-30 13:00:02 -08006856 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006857}
6858
Glenn Kastenf78aee72012-01-04 11:00:47 -08006859void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006860{
6861 Mutex::Autolock _l(mLock);
6862 size_t size = mEffectChains.size();
6863 for (size_t i = 0; i < size; i++) {
6864 mEffectChains[i]->setMode_l(mode);
6865 }
6866}
6867
6868void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006869 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08006870 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006871
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006873 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874 // delete the effect module if removing last handle on it
6875 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006876 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006877 removeEffect_l(effect);
6878 AudioSystem::unregisterEffect(effect->id());
6879 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 }
6881}
6882
6883status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6884{
6885 int session = chain->sessionId();
6886 int16_t *buffer = mMixBuffer;
6887 bool ownsBuffer = false;
6888
Steve Block3856b092011-10-20 11:56:00 +01006889 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 if (session > 0) {
6891 // Only one effect chain can be present in direct output thread and it uses
6892 // the mix buffer as input
6893 if (mType != DIRECT) {
6894 size_t numSamples = mFrameCount * mChannelCount;
6895 buffer = new int16_t[numSamples];
6896 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01006897 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898 ownsBuffer = true;
6899 }
6900
6901 // Attach all tracks with same session ID to this chain.
6902 for (size_t i = 0; i < mTracks.size(); ++i) {
6903 sp<Track> track = mTracks[i];
6904 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006905 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006907 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 }
6909 }
6910
6911 // indicate all active tracks in the chain
6912 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6913 sp<Track> track = mActiveTracks[i].promote();
6914 if (track == 0) continue;
6915 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006916 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006917 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 }
6919 }
6920 }
6921
6922 chain->setInBuffer(buffer, ownsBuffer);
6923 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006924 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006925 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006926 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6927 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006929 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6930 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006931 // Effect chain for other sessions are inserted at beginning of effect
6932 // chains list to be processed before output mix effects. Relative order between other
6933 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 size_t size = mEffectChains.size();
6935 size_t i = 0;
6936 for (i = 0; i < size; i++) {
6937 if (mEffectChains[i]->sessionId() < session) break;
6938 }
6939 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006940 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941
6942 return NO_ERROR;
6943}
6944
6945size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6946{
6947 int session = chain->sessionId();
6948
Steve Block3856b092011-10-20 11:56:00 +01006949 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950
6951 for (size_t i = 0; i < mEffectChains.size(); i++) {
6952 if (chain == mEffectChains[i]) {
6953 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006954 // detach all active tracks from the chain
6955 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6956 sp<Track> track = mActiveTracks[i].promote();
6957 if (track == 0) continue;
6958 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006959 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006960 chain.get(), session);
6961 chain->decActiveTrackCnt();
6962 }
6963 }
6964
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 // detach all tracks with same session ID from this chain
6966 for (size_t i = 0; i < mTracks.size(); ++i) {
6967 sp<Track> track = mTracks[i];
6968 if (session == track->sessionId()) {
6969 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006970 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 }
6972 }
Eric Laurentde070132010-07-13 04:45:46 -07006973 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006974 }
6975 }
6976 return mEffectChains.size();
6977}
6978
Eric Laurentde070132010-07-13 04:45:46 -07006979status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6980 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981{
6982 Mutex::Autolock _l(mLock);
6983 return attachAuxEffect_l(track, EffectId);
6984}
6985
Eric Laurentde070132010-07-13 04:45:46 -07006986status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6987 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988{
6989 status_t status = NO_ERROR;
6990
6991 if (EffectId == 0) {
6992 track->setAuxBuffer(0, NULL);
6993 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006994 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6995 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 if (effect != 0) {
6997 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6998 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6999 } else {
7000 status = INVALID_OPERATION;
7001 }
7002 } else {
7003 status = BAD_VALUE;
7004 }
7005 }
7006 return status;
7007}
7008
7009void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7010{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007011 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012 sp<Track> track = mTracks[i];
7013 if (track->auxEffectId() == effectId) {
7014 attachAuxEffect_l(track, 0);
7015 }
7016 }
7017}
7018
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007019status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7020{
7021 // only one chain per input thread
7022 if (mEffectChains.size() != 0) {
7023 return INVALID_OPERATION;
7024 }
Steve Block3856b092011-10-20 11:56:00 +01007025 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007026
7027 chain->setInBuffer(NULL);
7028 chain->setOutBuffer(NULL);
7029
Eric Laurent59255e42011-07-27 19:49:51 -07007030 checkSuspendOnAddEffectChain_l(chain);
7031
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007032 mEffectChains.add(chain);
7033
7034 return NO_ERROR;
7035}
7036
7037size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7038{
Steve Block3856b092011-10-20 11:56:00 +01007039 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007040 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007041 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7042 chain.get(), mEffectChains.size(), this);
7043 if (mEffectChains.size() == 1) {
7044 mEffectChains.removeAt(0);
7045 }
7046 return 0;
7047}
7048
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049// ----------------------------------------------------------------------------
7050// EffectModule implementation
7051// ----------------------------------------------------------------------------
7052
7053#undef LOG_TAG
7054#define LOG_TAG "AudioFlinger::EffectModule"
7055
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007056AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 const wp<AudioFlinger::EffectChain>& chain,
7058 effect_descriptor_t *desc,
7059 int id,
7060 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007061 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007062 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063{
Steve Block3856b092011-10-20 11:56:00 +01007064 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007066 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 return;
7068 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069
7070 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7071
7072 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007073 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074
7075 if (mStatus != NO_ERROR) {
7076 return;
7077 }
7078 lStatus = init();
7079 if (lStatus < 0) {
7080 mStatus = lStatus;
7081 goto Error;
7082 }
7083
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007084 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7085 mPinned = true;
7086 }
Steve Block3856b092011-10-20 11:56:00 +01007087 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 return;
7089Error:
7090 EffectRelease(mEffectInterface);
7091 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007092 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093}
7094
7095AudioFlinger::EffectModule::~EffectModule()
7096{
Steve Block3856b092011-10-20 11:56:00 +01007097 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007099 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7100 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7101 sp<ThreadBase> thread = mThread.promote();
7102 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007103 audio_stream_t *stream = thread->stream();
7104 if (stream != NULL) {
7105 stream->remove_audio_effect(stream, mEffectInterface);
7106 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007107 }
7108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109 // release effect engine
7110 EffectRelease(mEffectInterface);
7111 }
7112}
7113
Glenn Kasten435dbe62012-01-30 10:15:48 -08007114status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115{
7116 status_t status;
7117
7118 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 int priority = handle->priority();
7120 size_t size = mHandles.size();
7121 sp<EffectHandle> h;
7122 size_t i;
7123 for (i = 0; i < size; i++) {
7124 h = mHandles[i].promote();
7125 if (h == 0) continue;
7126 if (h->priority() <= priority) break;
7127 }
7128 // if inserted in first place, move effect control from previous owner to this handle
7129 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007130 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007132 enabled = h->enabled();
7133 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 }
Eric Laurent59255e42011-07-27 19:49:51 -07007135 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 status = NO_ERROR;
7137 } else {
7138 status = ALREADY_EXISTS;
7139 }
Steve Block3856b092011-10-20 11:56:00 +01007140 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007141 mHandles.insertAt(handle, i);
7142 return status;
7143}
7144
7145size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7146{
7147 Mutex::Autolock _l(mLock);
7148 size_t size = mHandles.size();
7149 size_t i;
7150 for (i = 0; i < size; i++) {
7151 if (mHandles[i] == handle) break;
7152 }
7153 if (i == size) {
7154 return size;
7155 }
Steve Block3856b092011-10-20 11:56:00 +01007156 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007157
7158 bool enabled = false;
7159 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007160 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007161 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007162 enabled = hdl->enabled();
7163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 mHandles.removeAt(i);
7165 size = mHandles.size();
7166 // if removed from first place, move effect control from this handle to next in line
7167 if (i == 0 && size != 0) {
7168 sp<EffectHandle> h = mHandles[0].promote();
7169 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007170 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 }
7172 }
7173
Eric Laurentec437d82011-07-26 20:54:46 -07007174 // Prevent calls to process() and other functions on effect interface from now on.
7175 // The effect engine will be released by the destructor when the last strong reference on
7176 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007177 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007178 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007179 }
7180
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 return size;
7182}
7183
Eric Laurent59255e42011-07-27 19:49:51 -07007184sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7185{
7186 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007187 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007188}
7189
Glenn Kasten58123c32012-02-03 10:32:24 -08007190void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007191{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007192 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 // keep a strong reference on this EffectModule to avoid calling the
7194 // destructor before we exit
7195 sp<EffectModule> keep(this);
7196 {
7197 sp<ThreadBase> thread = mThread.promote();
7198 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007199 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200 }
7201 }
7202}
7203
7204void AudioFlinger::EffectModule::updateState() {
7205 Mutex::Autolock _l(mLock);
7206
7207 switch (mState) {
7208 case RESTART:
7209 reset_l();
7210 // FALL THROUGH
7211
7212 case STARTING:
7213 // clear auxiliary effect input buffer for next accumulation
7214 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7215 memset(mConfig.inputCfg.buffer.raw,
7216 0,
7217 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7218 }
7219 start_l();
7220 mState = ACTIVE;
7221 break;
7222 case STOPPING:
7223 stop_l();
7224 mDisableWaitCnt = mMaxDisableWaitCnt;
7225 mState = STOPPED;
7226 break;
7227 case STOPPED:
7228 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7229 // turn off sequence.
7230 if (--mDisableWaitCnt == 0) {
7231 reset_l();
7232 mState = IDLE;
7233 }
7234 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007235 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236 break;
7237 }
7238}
7239
7240void AudioFlinger::EffectModule::process()
7241{
7242 Mutex::Autolock _l(mLock);
7243
Eric Laurentec437d82011-07-26 20:54:46 -07007244 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245 mConfig.inputCfg.buffer.raw == NULL ||
7246 mConfig.outputCfg.buffer.raw == NULL) {
7247 return;
7248 }
7249
Eric Laurent8f45bd72010-08-31 13:50:07 -07007250 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7252 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007253 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007255 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 }
7257
7258 // do the actual processing in the effect engine
7259 int ret = (*mEffectInterface)->process(mEffectInterface,
7260 &mConfig.inputCfg.buffer,
7261 &mConfig.outputCfg.buffer);
7262
7263 // force transition to IDLE state when engine is ready
7264 if (mState == STOPPED && ret == -ENODATA) {
7265 mDisableWaitCnt = 1;
7266 }
7267
7268 // clear auxiliary effect input buffer for next accumulation
7269 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007270 memset(mConfig.inputCfg.buffer.raw, 0,
7271 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272 }
7273 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007274 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7275 // If an insert effect is idle and input buffer is different from output buffer,
7276 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007278 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007279 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7280 int16_t *in = mConfig.inputCfg.buffer.s16;
7281 int16_t *out = mConfig.outputCfg.buffer.s16;
7282 for (size_t i = 0; i < frameCnt; i++) {
7283 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 }
7286 }
7287}
7288
7289void AudioFlinger::EffectModule::reset_l()
7290{
7291 if (mEffectInterface == NULL) {
7292 return;
7293 }
7294 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7295}
7296
7297status_t AudioFlinger::EffectModule::configure()
7298{
7299 uint32_t channels;
7300 if (mEffectInterface == NULL) {
7301 return NO_INIT;
7302 }
7303
7304 sp<ThreadBase> thread = mThread.promote();
7305 if (thread == 0) {
7306 return DEAD_OBJECT;
7307 }
7308
7309 // TODO: handle configuration of effects replacing track process
7310 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007311 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007313 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 }
7315
7316 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007317 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 } else {
7319 mConfig.inputCfg.channels = channels;
7320 }
7321 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007322 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7323 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 mConfig.inputCfg.samplingRate = thread->sampleRate();
7325 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7326 mConfig.inputCfg.bufferProvider.cookie = NULL;
7327 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7328 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7329 mConfig.outputCfg.bufferProvider.cookie = NULL;
7330 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7331 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7332 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7333 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007334 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007335 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 // - in other sessions:
7337 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7338 // other effect: overwrites output buffer: input buffer == output buffer
7339 // Auxiliary effect:
7340 // accumulates in output buffer: input buffer != output buffer
7341 // Therefore: accumulate <=> input buffer != output buffer
7342 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7343 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7344 } else {
7345 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7346 }
7347 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7348 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7349 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7350 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7351
Steve Block3856b092011-10-20 11:56:00 +01007352 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007353 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7354
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007356 uint32_t size = sizeof(int);
7357 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007358 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007359 sizeof(effect_config_t),
7360 &mConfig,
7361 &size,
7362 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 if (status == 0) {
7364 status = cmdStatus;
7365 }
7366
7367 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7368 (1000 * mConfig.outputCfg.buffer.frameCount);
7369
7370 return status;
7371}
7372
7373status_t AudioFlinger::EffectModule::init()
7374{
7375 Mutex::Autolock _l(mLock);
7376 if (mEffectInterface == NULL) {
7377 return NO_INIT;
7378 }
7379 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007380 uint32_t size = sizeof(status_t);
7381 status_t status = (*mEffectInterface)->command(mEffectInterface,
7382 EFFECT_CMD_INIT,
7383 0,
7384 NULL,
7385 &size,
7386 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 if (status == 0) {
7388 status = cmdStatus;
7389 }
7390 return status;
7391}
7392
Eric Laurentec35a142011-10-05 17:42:25 -07007393status_t AudioFlinger::EffectModule::start()
7394{
7395 Mutex::Autolock _l(mLock);
7396 return start_l();
7397}
7398
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399status_t AudioFlinger::EffectModule::start_l()
7400{
7401 if (mEffectInterface == NULL) {
7402 return NO_INIT;
7403 }
7404 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007405 uint32_t size = sizeof(status_t);
7406 status_t status = (*mEffectInterface)->command(mEffectInterface,
7407 EFFECT_CMD_ENABLE,
7408 0,
7409 NULL,
7410 &size,
7411 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412 if (status == 0) {
7413 status = cmdStatus;
7414 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007415 if (status == 0 &&
7416 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7417 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7418 sp<ThreadBase> thread = mThread.promote();
7419 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007420 audio_stream_t *stream = thread->stream();
7421 if (stream != NULL) {
7422 stream->add_audio_effect(stream, mEffectInterface);
7423 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007424 }
7425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 return status;
7427}
7428
Eric Laurentec437d82011-07-26 20:54:46 -07007429status_t AudioFlinger::EffectModule::stop()
7430{
7431 Mutex::Autolock _l(mLock);
7432 return stop_l();
7433}
7434
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435status_t AudioFlinger::EffectModule::stop_l()
7436{
7437 if (mEffectInterface == NULL) {
7438 return NO_INIT;
7439 }
7440 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007441 uint32_t size = sizeof(status_t);
7442 status_t status = (*mEffectInterface)->command(mEffectInterface,
7443 EFFECT_CMD_DISABLE,
7444 0,
7445 NULL,
7446 &size,
7447 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 if (status == 0) {
7449 status = cmdStatus;
7450 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007451 if (status == 0 &&
7452 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7453 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7454 sp<ThreadBase> thread = mThread.promote();
7455 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007456 audio_stream_t *stream = thread->stream();
7457 if (stream != NULL) {
7458 stream->remove_audio_effect(stream, mEffectInterface);
7459 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007460 }
7461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462 return status;
7463}
7464
Eric Laurent25f43952010-07-28 05:40:18 -07007465status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7466 uint32_t cmdSize,
7467 void *pCmdData,
7468 uint32_t *replySize,
7469 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007470{
7471 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007472// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473
Eric Laurentec437d82011-07-26 20:54:46 -07007474 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475 return NO_INIT;
7476 }
Eric Laurent25f43952010-07-28 05:40:18 -07007477 status_t status = (*mEffectInterface)->command(mEffectInterface,
7478 cmdCode,
7479 cmdSize,
7480 pCmdData,
7481 replySize,
7482 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007484 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 for (size_t i = 1; i < mHandles.size(); i++) {
7486 sp<EffectHandle> h = mHandles[i].promote();
7487 if (h != 0) {
7488 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7489 }
7490 }
7491 }
7492 return status;
7493}
7494
7495status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7496{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007497
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007499 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500
7501 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007502 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7503 if (enabled && status != NO_ERROR) {
7504 return status;
7505 }
7506
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 switch (mState) {
7508 // going from disabled to enabled
7509 case IDLE:
7510 mState = STARTING;
7511 break;
7512 case STOPPED:
7513 mState = RESTART;
7514 break;
7515 case STOPPING:
7516 mState = ACTIVE;
7517 break;
7518
7519 // going from enabled to disabled
7520 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007521 mState = STOPPED;
7522 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 case STARTING:
7524 mState = IDLE;
7525 break;
7526 case ACTIVE:
7527 mState = STOPPING;
7528 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007529 case DESTROYED:
7530 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 }
7532 for (size_t i = 1; i < mHandles.size(); i++) {
7533 sp<EffectHandle> h = mHandles[i].promote();
7534 if (h != 0) {
7535 h->setEnabled(enabled);
7536 }
7537 }
7538 }
7539 return NO_ERROR;
7540}
7541
Glenn Kastenc59c0042012-02-02 14:06:11 -08007542bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543{
7544 switch (mState) {
7545 case RESTART:
7546 case STARTING:
7547 case ACTIVE:
7548 return true;
7549 case IDLE:
7550 case STOPPING:
7551 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007552 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 default:
7554 return false;
7555 }
7556}
7557
Glenn Kastenc59c0042012-02-02 14:06:11 -08007558bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07007559{
7560 switch (mState) {
7561 case RESTART:
7562 case ACTIVE:
7563 case STOPPING:
7564 case STOPPED:
7565 return true;
7566 case IDLE:
7567 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007568 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007569 default:
7570 return false;
7571 }
7572}
7573
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7575{
7576 Mutex::Autolock _l(mLock);
7577 status_t status = NO_ERROR;
7578
7579 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7580 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007581 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007582 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7583 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584 status_t cmdStatus;
7585 uint32_t volume[2];
7586 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007587 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 volume[0] = *left;
7589 volume[1] = *right;
7590 if (controller) {
7591 pVolume = volume;
7592 }
Eric Laurent25f43952010-07-28 05:40:18 -07007593 status = (*mEffectInterface)->command(mEffectInterface,
7594 EFFECT_CMD_SET_VOLUME,
7595 size,
7596 volume,
7597 &size,
7598 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7600 *left = volume[0];
7601 *right = volume[1];
7602 }
7603 }
7604 return status;
7605}
7606
7607status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7608{
7609 Mutex::Autolock _l(mLock);
7610 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007611 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7612 // audio pre processing modules on RecordThread can receive both output and
7613 // input device indication in the same call
7614 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7615 if (dev) {
7616 status_t cmdStatus;
7617 uint32_t size = sizeof(status_t);
7618
7619 status = (*mEffectInterface)->command(mEffectInterface,
7620 EFFECT_CMD_SET_DEVICE,
7621 sizeof(uint32_t),
7622 &dev,
7623 &size,
7624 &cmdStatus);
7625 if (status == NO_ERROR) {
7626 status = cmdStatus;
7627 }
7628 }
7629 dev = device & AUDIO_DEVICE_IN_ALL;
7630 if (dev) {
7631 status_t cmdStatus;
7632 uint32_t size = sizeof(status_t);
7633
7634 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7635 EFFECT_CMD_SET_INPUT_DEVICE,
7636 sizeof(uint32_t),
7637 &dev,
7638 &size,
7639 &cmdStatus);
7640 if (status2 == NO_ERROR) {
7641 status2 = cmdStatus;
7642 }
7643 if (status == NO_ERROR) {
7644 status = status2;
7645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007646 }
7647 }
7648 return status;
7649}
7650
Glenn Kastenf78aee72012-01-04 11:00:47 -08007651status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652{
7653 Mutex::Autolock _l(mLock);
7654 status_t status = NO_ERROR;
7655 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007657 uint32_t size = sizeof(status_t);
7658 status = (*mEffectInterface)->command(mEffectInterface,
7659 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08007660 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07007661 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007662 &size,
7663 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007664 if (status == NO_ERROR) {
7665 status = cmdStatus;
7666 }
7667 }
7668 return status;
7669}
7670
Eric Laurent59255e42011-07-27 19:49:51 -07007671void AudioFlinger::EffectModule::setSuspended(bool suspended)
7672{
7673 Mutex::Autolock _l(mLock);
7674 mSuspended = suspended;
7675}
Glenn Kastena3a85482012-01-04 11:01:11 -08007676
7677bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07007678{
7679 Mutex::Autolock _l(mLock);
7680 return mSuspended;
7681}
7682
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7684{
7685 const size_t SIZE = 256;
7686 char buffer[SIZE];
7687 String8 result;
7688
7689 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7690 result.append(buffer);
7691
7692 bool locked = tryLock(mLock);
7693 // failed to lock - AudioFlinger is probably deadlocked
7694 if (!locked) {
7695 result.append("\t\tCould not lock Fx mutex:\n");
7696 }
7697
7698 result.append("\t\tSession Status State Engine:\n");
7699 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7700 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7701 result.append(buffer);
7702
7703 result.append("\t\tDescriptor:\n");
7704 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7705 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7706 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7707 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7708 result.append(buffer);
7709 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7710 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7711 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7712 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7713 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007714 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007715 mDescriptor.apiVersion,
7716 mDescriptor.flags);
7717 result.append(buffer);
7718 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7719 mDescriptor.name);
7720 result.append(buffer);
7721 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7722 mDescriptor.implementor);
7723 result.append(buffer);
7724
7725 result.append("\t\t- Input configuration:\n");
7726 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7727 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7728 (uint32_t)mConfig.inputCfg.buffer.raw,
7729 mConfig.inputCfg.buffer.frameCount,
7730 mConfig.inputCfg.samplingRate,
7731 mConfig.inputCfg.channels,
7732 mConfig.inputCfg.format);
7733 result.append(buffer);
7734
7735 result.append("\t\t- Output configuration:\n");
7736 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7737 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7738 (uint32_t)mConfig.outputCfg.buffer.raw,
7739 mConfig.outputCfg.buffer.frameCount,
7740 mConfig.outputCfg.samplingRate,
7741 mConfig.outputCfg.channels,
7742 mConfig.outputCfg.format);
7743 result.append(buffer);
7744
7745 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7746 result.append(buffer);
7747 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7748 for (size_t i = 0; i < mHandles.size(); ++i) {
7749 sp<EffectHandle> handle = mHandles[i].promote();
7750 if (handle != 0) {
7751 handle->dump(buffer, SIZE);
7752 result.append(buffer);
7753 }
7754 }
7755
7756 result.append("\n");
7757
7758 write(fd, result.string(), result.length());
7759
7760 if (locked) {
7761 mLock.unlock();
7762 }
7763
7764 return NO_ERROR;
7765}
7766
7767// ----------------------------------------------------------------------------
7768// EffectHandle implementation
7769// ----------------------------------------------------------------------------
7770
7771#undef LOG_TAG
7772#define LOG_TAG "AudioFlinger::EffectHandle"
7773
7774AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7775 const sp<AudioFlinger::Client>& client,
7776 const sp<IEffectClient>& effectClient,
7777 int32_t priority)
7778 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007779 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007780 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781{
Steve Block3856b092011-10-20 11:56:00 +01007782 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007784 if (client == 0) {
7785 return;
7786 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7788 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7789 if (mCblkMemory != 0) {
7790 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7791
Glenn Kastena0d68332012-01-27 16:47:15 -08007792 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 new(mCblk) effect_param_cblk_t();
7794 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007796 } else {
Steve Block29357bc2012-01-06 19:20:56 +00007797 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 return;
7799 }
7800}
7801
7802AudioFlinger::EffectHandle::~EffectHandle()
7803{
Steve Block3856b092011-10-20 11:56:00 +01007804 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007805 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01007806 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807}
7808
7809status_t AudioFlinger::EffectHandle::enable()
7810{
Steve Block3856b092011-10-20 11:56:00 +01007811 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 if (!mHasControl) return INVALID_OPERATION;
7813 if (mEffect == 0) return DEAD_OBJECT;
7814
Eric Laurentdb7c0792011-08-10 10:37:50 -07007815 if (mEnabled) {
7816 return NO_ERROR;
7817 }
7818
Eric Laurent59255e42011-07-27 19:49:51 -07007819 mEnabled = true;
7820
7821 sp<ThreadBase> thread = mEffect->thread().promote();
7822 if (thread != 0) {
7823 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7824 }
7825
7826 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7827 if (mEffect->suspended()) {
7828 return NO_ERROR;
7829 }
7830
Eric Laurentdb7c0792011-08-10 10:37:50 -07007831 status_t status = mEffect->setEnabled(true);
7832 if (status != NO_ERROR) {
7833 if (thread != 0) {
7834 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7835 }
7836 mEnabled = false;
7837 }
7838 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839}
7840
7841status_t AudioFlinger::EffectHandle::disable()
7842{
Steve Block3856b092011-10-20 11:56:00 +01007843 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007845 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846
Eric Laurentdb7c0792011-08-10 10:37:50 -07007847 if (!mEnabled) {
7848 return NO_ERROR;
7849 }
Eric Laurent59255e42011-07-27 19:49:51 -07007850 mEnabled = false;
7851
7852 if (mEffect->suspended()) {
7853 return NO_ERROR;
7854 }
7855
7856 status_t status = mEffect->setEnabled(false);
7857
7858 sp<ThreadBase> thread = mEffect->thread().promote();
7859 if (thread != 0) {
7860 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7861 }
7862
7863 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864}
7865
7866void AudioFlinger::EffectHandle::disconnect()
7867{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007868 disconnect(true);
7869}
7870
Glenn Kasten58123c32012-02-03 10:32:24 -08007871void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007872{
Glenn Kasten58123c32012-02-03 10:32:24 -08007873 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874 if (mEffect == 0) {
7875 return;
7876 }
Glenn Kasten58123c32012-02-03 10:32:24 -08007877 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07007878
Eric Laurenta85a74a2011-10-19 11:44:54 -07007879 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007880 sp<ThreadBase> thread = mEffect->thread().promote();
7881 if (thread != 0) {
7882 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7883 }
Eric Laurent59255e42011-07-27 19:49:51 -07007884 }
7885
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 // release sp on module => module destructor can be called now
7887 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007888 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08007889 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08007890 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007891 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7892 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08007893 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007894 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7896 mClient.clear();
7897 }
7898}
7899
Eric Laurent25f43952010-07-28 05:40:18 -07007900status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7901 uint32_t cmdSize,
7902 void *pCmdData,
7903 uint32_t *replySize,
7904 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007905{
Steve Block3856b092011-10-20 11:56:00 +01007906// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07007907// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908
7909 // only get parameter command is permitted for applications not controlling the effect
7910 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7911 return INVALID_OPERATION;
7912 }
7913 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007914 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915
7916 // handle commands that are not forwarded transparently to effect engine
7917 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7918 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7919 // no risk to block the whole media server process or mixer threads is we are stuck here
7920 Mutex::Autolock _l(mCblk->lock);
7921 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7922 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7923 mCblk->serverIndex = 0;
7924 mCblk->clientIndex = 0;
7925 return BAD_VALUE;
7926 }
7927 status_t status = NO_ERROR;
7928 while (mCblk->serverIndex < mCblk->clientIndex) {
7929 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007930 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931 int *p = (int *)(mBuffer + mCblk->serverIndex);
7932 int size = *p++;
7933 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007934 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 break;
7936 }
7937 effect_param_t *param = (effect_param_t *)p;
7938 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007939 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 mCblk->serverIndex += size;
7941 continue;
7942 }
Eric Laurent25f43952010-07-28 05:40:18 -07007943 uint32_t psize = sizeof(effect_param_t) +
7944 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7945 param->vsize;
7946 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7947 psize,
7948 p,
7949 &rsize,
7950 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007951 // stop at first error encountered
7952 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007953 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007954 *(int *)pReplyData = reply;
7955 break;
7956 } else if (reply != NO_ERROR) {
7957 *(int *)pReplyData = reply;
7958 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 }
7960 mCblk->serverIndex += size;
7961 }
7962 mCblk->serverIndex = 0;
7963 mCblk->clientIndex = 0;
7964 return status;
7965 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007966 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 return enable();
7968 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007969 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 return disable();
7971 }
7972
7973 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7974}
7975
Eric Laurent59255e42011-07-27 19:49:51 -07007976void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977{
Steve Block3856b092011-10-20 11:56:00 +01007978 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979
7980 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007981 mEnabled = enabled;
7982
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 if (signal && mEffectClient != 0) {
7984 mEffectClient->controlStatusChanged(hasControl);
7985 }
7986}
7987
Eric Laurent25f43952010-07-28 05:40:18 -07007988void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7989 uint32_t cmdSize,
7990 void *pCmdData,
7991 uint32_t replySize,
7992 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007993{
7994 if (mEffectClient != 0) {
7995 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7996 }
7997}
7998
7999
8000
8001void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8002{
8003 if (mEffectClient != 0) {
8004 mEffectClient->enableStatusChanged(enabled);
8005 }
8006}
8007
8008status_t AudioFlinger::EffectHandle::onTransact(
8009 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8010{
8011 return BnEffect::onTransact(code, data, reply, flags);
8012}
8013
8014
8015void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8016{
Glenn Kastena0d68332012-01-27 16:47:15 -08008017 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018
8019 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008020 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008021 mPriority,
8022 mHasControl,
8023 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008024 mCblk ? mCblk->clientIndex : 0,
8025 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 );
8027
8028 if (locked) {
8029 mCblk->lock.unlock();
8030 }
8031}
8032
8033#undef LOG_TAG
8034#define LOG_TAG "AudioFlinger::EffectChain"
8035
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008036AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008038 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008039 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8040 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008041{
Dima Zavinfce7a472011-04-19 22:30:36 -07008042 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008043 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008044 return;
8045 }
8046 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8047 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048}
8049
8050AudioFlinger::EffectChain::~EffectChain()
8051{
8052 if (mOwnInBuffer) {
8053 delete mInBuffer;
8054 }
8055
8056}
8057
Eric Laurent59255e42011-07-27 19:49:51 -07008058// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008059sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 size_t size = mEffects.size();
8062
8063 for (size_t i = 0; i < size; i++) {
8064 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008065 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 }
8067 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008068 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008069}
8070
Eric Laurent59255e42011-07-27 19:49:51 -07008071// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008072sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008073{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008074 size_t size = mEffects.size();
8075
8076 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008077 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8078 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008079 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080 }
8081 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008082 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083}
8084
Eric Laurent59255e42011-07-27 19:49:51 -07008085// getEffectFromType_l() must be called with ThreadBase::mLock held
8086sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8087 const effect_uuid_t *type)
8088{
Eric Laurent59255e42011-07-27 19:49:51 -07008089 size_t size = mEffects.size();
8090
8091 for (size_t i = 0; i < size; i++) {
8092 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008093 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008094 }
8095 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008096 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008097}
8098
Mathias Agopian65ab4712010-07-14 17:59:35 -07008099// Must be called with EffectChain::mLock locked
8100void AudioFlinger::EffectChain::process_l()
8101{
Eric Laurentdac69112010-09-28 14:09:57 -07008102 sp<ThreadBase> thread = mThread.promote();
8103 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008104 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008105 return;
8106 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008107 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8108 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008109 // always process effects unless no more tracks are on the session and the effect tail
8110 // has been rendered
8111 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008112 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008113 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008114
Eric Laurent544fe9b2011-11-11 15:42:52 -08008115 if (!tracksOnSession && mTailBufferCount == 0) {
8116 doProcess = false;
8117 }
8118
8119 if (activeTrackCnt() == 0) {
8120 // if no track is active and the effect tail has not been rendered,
8121 // the input buffer must be cleared here as the mixer process will not do it
8122 if (tracksOnSession || mTailBufferCount > 0) {
8123 size_t numSamples = thread->frameCount() * thread->channelCount();
8124 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8125 if (mTailBufferCount > 0) {
8126 mTailBufferCount--;
8127 }
8128 }
8129 }
Eric Laurentdac69112010-09-28 14:09:57 -07008130 }
8131
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008133 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008134 for (size_t i = 0; i < size; i++) {
8135 mEffects[i]->process();
8136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137 }
8138 for (size_t i = 0; i < size; i++) {
8139 mEffects[i]->updateState();
8140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141}
8142
Eric Laurentcab11242010-07-15 12:50:15 -07008143// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008144status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145{
8146 effect_descriptor_t desc = effect->desc();
8147 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8148
8149 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008150 effect->setChain(this);
8151 sp<ThreadBase> thread = mThread.promote();
8152 if (thread == 0) {
8153 return NO_INIT;
8154 }
8155 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156
8157 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8158 // Auxiliary effects are inserted at the beginning of mEffects vector as
8159 // they are processed first and accumulated in chain input buffer
8160 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008161
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162 // the input buffer for auxiliary effect contains mono samples in
8163 // 32 bit format. This is to avoid saturation in AudoMixer
8164 // accumulation stage. Saturation is done in EffectModule::process() before
8165 // calling the process in effect engine
8166 size_t numSamples = thread->frameCount();
8167 int32_t *buffer = new int32_t[numSamples];
8168 memset(buffer, 0, numSamples * sizeof(int32_t));
8169 effect->setInBuffer((int16_t *)buffer);
8170 // auxiliary effects output samples to chain input buffer for further processing
8171 // by insert effects
8172 effect->setOutBuffer(mInBuffer);
8173 } else {
8174 // Insert effects are inserted at the end of mEffects vector as they are processed
8175 // after track and auxiliary effects.
8176 // Insert effect order as a function of indicated preference:
8177 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8178 // another effect is present
8179 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8180 // last effect claiming first position
8181 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8182 // first effect claiming last position
8183 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8184 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8185 // already present
8186
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008187 size_t size = mEffects.size();
8188 size_t idx_insert = size;
8189 ssize_t idx_insert_first = -1;
8190 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008192 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008193 effect_descriptor_t d = mEffects[i]->desc();
8194 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8195 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8196 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8197 // check invalid effect chaining combinations
8198 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8199 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008200 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008201 return INVALID_OPERATION;
8202 }
8203 // remember position of first insert effect and by default
8204 // select this as insert position for new effect
8205 if (idx_insert == size) {
8206 idx_insert = i;
8207 }
8208 // remember position of last insert effect claiming
8209 // first position
8210 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8211 idx_insert_first = i;
8212 }
8213 // remember position of first insert effect claiming
8214 // last position
8215 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8216 idx_insert_last == -1) {
8217 idx_insert_last = i;
8218 }
8219 }
8220 }
8221
8222 // modify idx_insert from first position if needed
8223 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8224 if (idx_insert_last != -1) {
8225 idx_insert = idx_insert_last;
8226 } else {
8227 idx_insert = size;
8228 }
8229 } else {
8230 if (idx_insert_first != -1) {
8231 idx_insert = idx_insert_first + 1;
8232 }
8233 }
8234
8235 // always read samples from chain input buffer
8236 effect->setInBuffer(mInBuffer);
8237
8238 // if last effect in the chain, output samples to chain
8239 // output buffer, otherwise to chain input buffer
8240 if (idx_insert == size) {
8241 if (idx_insert != 0) {
8242 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8243 mEffects[idx_insert-1]->configure();
8244 }
8245 effect->setOutBuffer(mOutBuffer);
8246 } else {
8247 effect->setOutBuffer(mInBuffer);
8248 }
8249 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250
Steve Block3856b092011-10-20 11:56:00 +01008251 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008252 }
8253 effect->configure();
8254 return NO_ERROR;
8255}
8256
Eric Laurentcab11242010-07-15 12:50:15 -07008257// removeEffect_l() must be called with PlaybackThread::mLock held
8258size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259{
8260 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008261 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8263
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008264 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008265 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008266 // calling stop here will remove pre-processing effect from the audio HAL.
8267 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8268 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008269 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8270 mEffects[i]->state() == EffectModule::STOPPING) {
8271 mEffects[i]->stop();
8272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008273 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8274 delete[] effect->inBuffer();
8275 } else {
8276 if (i == size - 1 && i != 0) {
8277 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8278 mEffects[i - 1]->configure();
8279 }
8280 }
8281 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008282 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008283 break;
8284 }
8285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008286
8287 return mEffects.size();
8288}
8289
Eric Laurentcab11242010-07-15 12:50:15 -07008290// setDevice_l() must be called with PlaybackThread::mLock held
8291void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292{
8293 size_t size = mEffects.size();
8294 for (size_t i = 0; i < size; i++) {
8295 mEffects[i]->setDevice(device);
8296 }
8297}
8298
Eric Laurentcab11242010-07-15 12:50:15 -07008299// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008300void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008301{
8302 size_t size = mEffects.size();
8303 for (size_t i = 0; i < size; i++) {
8304 mEffects[i]->setMode(mode);
8305 }
8306}
8307
Eric Laurentcab11242010-07-15 12:50:15 -07008308// setVolume_l() must be called with PlaybackThread::mLock held
8309bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310{
8311 uint32_t newLeft = *left;
8312 uint32_t newRight = *right;
8313 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008314 int ctrlIdx = -1;
8315 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316
Eric Laurentcab11242010-07-15 12:50:15 -07008317 // first update volume controller
8318 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008319 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008320 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8321 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008322 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008323 break;
8324 }
8325 }
8326
8327 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008328 if (hasControl) {
8329 *left = mNewLeftVolume;
8330 *right = mNewRightVolume;
8331 }
8332 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008333 }
8334
8335 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008336 mLeftVolume = newLeft;
8337 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008338
8339 // second get volume update from volume controller
8340 if (ctrlIdx >= 0) {
8341 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008342 mNewLeftVolume = newLeft;
8343 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008344 }
8345 // then indicate volume to all other effects in chain.
8346 // Pass altered volume to effects before volume controller
8347 // and requested volume to effects after controller
8348 uint32_t lVol = newLeft;
8349 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008350
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008352 if ((int)i == ctrlIdx) continue;
8353 // this also works for ctrlIdx == -1 when there is no volume controller
8354 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355 lVol = *left;
8356 rVol = *right;
8357 }
8358 mEffects[i]->setVolume(&lVol, &rVol, false);
8359 }
8360 *left = newLeft;
8361 *right = newRight;
8362
8363 return hasControl;
8364}
8365
Mathias Agopian65ab4712010-07-14 17:59:35 -07008366status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8367{
8368 const size_t SIZE = 256;
8369 char buffer[SIZE];
8370 String8 result;
8371
8372 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8373 result.append(buffer);
8374
8375 bool locked = tryLock(mLock);
8376 // failed to lock - AudioFlinger is probably deadlocked
8377 if (!locked) {
8378 result.append("\tCould not lock mutex:\n");
8379 }
8380
Eric Laurentcab11242010-07-15 12:50:15 -07008381 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8382 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008383 mEffects.size(),
8384 (uint32_t)mInBuffer,
8385 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008386 mActiveTrackCnt);
8387 result.append(buffer);
8388 write(fd, result.string(), result.size());
8389
8390 for (size_t i = 0; i < mEffects.size(); ++i) {
8391 sp<EffectModule> effect = mEffects[i];
8392 if (effect != 0) {
8393 effect->dump(fd, args);
8394 }
8395 }
8396
8397 if (locked) {
8398 mLock.unlock();
8399 }
8400
8401 return NO_ERROR;
8402}
8403
Eric Laurent59255e42011-07-27 19:49:51 -07008404// must be called with ThreadBase::mLock held
8405void AudioFlinger::EffectChain::setEffectSuspended_l(
8406 const effect_uuid_t *type, bool suspend)
8407{
8408 sp<SuspendedEffectDesc> desc;
8409 // use effect type UUID timelow as key as there is no real risk of identical
8410 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008411 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008412 if (suspend) {
8413 if (index >= 0) {
8414 desc = mSuspendedEffects.valueAt(index);
8415 } else {
8416 desc = new SuspendedEffectDesc();
8417 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8418 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008419 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008420 }
8421 if (desc->mRefCount++ == 0) {
8422 sp<EffectModule> effect = getEffectIfEnabled(type);
8423 if (effect != 0) {
8424 desc->mEffect = effect;
8425 effect->setSuspended(true);
8426 effect->setEnabled(false);
8427 }
8428 }
8429 } else {
8430 if (index < 0) {
8431 return;
8432 }
8433 desc = mSuspendedEffects.valueAt(index);
8434 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008435 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008436 desc->mRefCount = 1;
8437 }
8438 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008439 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008440 if (desc->mEffect != 0) {
8441 sp<EffectModule> effect = desc->mEffect.promote();
8442 if (effect != 0) {
8443 effect->setSuspended(false);
8444 sp<EffectHandle> handle = effect->controlHandle();
8445 if (handle != 0) {
8446 effect->setEnabled(handle->enabled());
8447 }
8448 }
8449 desc->mEffect.clear();
8450 }
8451 mSuspendedEffects.removeItemsAt(index);
8452 }
8453 }
8454}
8455
8456// must be called with ThreadBase::mLock held
8457void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8458{
8459 sp<SuspendedEffectDesc> desc;
8460
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008461 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008462 if (suspend) {
8463 if (index >= 0) {
8464 desc = mSuspendedEffects.valueAt(index);
8465 } else {
8466 desc = new SuspendedEffectDesc();
8467 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008468 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008469 }
8470 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008471 Vector< sp<EffectModule> > effects;
8472 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008473 for (size_t i = 0; i < effects.size(); i++) {
8474 setEffectSuspended_l(&effects[i]->desc().type, true);
8475 }
8476 }
8477 } else {
8478 if (index < 0) {
8479 return;
8480 }
8481 desc = mSuspendedEffects.valueAt(index);
8482 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008483 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008484 desc->mRefCount = 1;
8485 }
8486 if (--desc->mRefCount == 0) {
8487 Vector<const effect_uuid_t *> types;
8488 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8489 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8490 continue;
8491 }
8492 types.add(&mSuspendedEffects.valueAt(i)->mType);
8493 }
8494 for (size_t i = 0; i < types.size(); i++) {
8495 setEffectSuspended_l(types[i], false);
8496 }
Steve Block3856b092011-10-20 11:56:00 +01008497 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008498 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8499 }
8500 }
8501}
8502
Eric Laurent6bffdb82011-09-23 08:40:41 -07008503
8504// The volume effect is used for automated tests only
8505#ifndef OPENSL_ES_H_
8506static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8507 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8508const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8509#endif //OPENSL_ES_H_
8510
Eric Laurentdb7c0792011-08-10 10:37:50 -07008511bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8512{
8513 // auxiliary effects and visualizer are never suspended on output mix
8514 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8515 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008516 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8517 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008518 return false;
8519 }
8520 return true;
8521}
8522
Glenn Kastend0539712012-01-30 12:56:03 -08008523void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008524{
Glenn Kastend0539712012-01-30 12:56:03 -08008525 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008526 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008527 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8528 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008529 }
Eric Laurent59255e42011-07-27 19:49:51 -07008530 }
Eric Laurent59255e42011-07-27 19:49:51 -07008531}
8532
8533sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8534 const effect_uuid_t *type)
8535{
Glenn Kasten090f0192012-01-30 13:00:02 -08008536 sp<EffectModule> effect = getEffectFromType_l(type);
8537 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008538}
8539
8540void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8541 bool enabled)
8542{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008543 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008544 if (enabled) {
8545 if (index < 0) {
8546 // if the effect is not suspend check if all effects are suspended
8547 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8548 if (index < 0) {
8549 return;
8550 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008551 if (!isEffectEligibleForSuspend(effect->desc())) {
8552 return;
8553 }
Eric Laurent59255e42011-07-27 19:49:51 -07008554 setEffectSuspended_l(&effect->desc().type, enabled);
8555 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008556 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008557 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07008558 return;
8559 }
Eric Laurent59255e42011-07-27 19:49:51 -07008560 }
Steve Block3856b092011-10-20 11:56:00 +01008561 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008562 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008563 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8564 // if effect is requested to suspended but was not yet enabled, supend it now.
8565 if (desc->mEffect == 0) {
8566 desc->mEffect = effect;
8567 effect->setEnabled(false);
8568 effect->setSuspended(true);
8569 }
8570 } else {
8571 if (index < 0) {
8572 return;
8573 }
Steve Block3856b092011-10-20 11:56:00 +01008574 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008575 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008576 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8577 desc->mEffect.clear();
8578 effect->setSuspended(false);
8579 }
8580}
8581
Mathias Agopian65ab4712010-07-14 17:59:35 -07008582#undef LOG_TAG
8583#define LOG_TAG "AudioFlinger"
8584
8585// ----------------------------------------------------------------------------
8586
8587status_t AudioFlinger::onTransact(
8588 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8589{
8590 return BnAudioFlinger::onTransact(code, data, reply, flags);
8591}
8592
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593}; // namespace android